diff --git a/tools/php-cs-fixer/composer.json b/tools/php-cs-fixer/composer.json new file mode 100644 index 00000000..0c6c56b8 --- /dev/null +++ b/tools/php-cs-fixer/composer.json @@ -0,0 +1,5 @@ +{ + "require": { + "friendsofphp/php-cs-fixer": "^3.40" + } +} diff --git a/tools/php-cs-fixer/composer.lock b/tools/php-cs-fixer/composer.lock new file mode 100644 index 00000000..bc075086 --- /dev/null +++ b/tools/php-cs-fixer/composer.lock @@ -0,0 +1,1843 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "b59468c98698b5b5e9a22616a237b42c", + "packages": [ + { + "name": "composer/pcre", + "version": "3.1.1", + "source": { + "type": "git", + "url": "https://github.com/composer/pcre.git", + "reference": "00104306927c7a0919b4ced2aaa6782c1e61a3c9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/pcre/zipball/00104306927c7a0919b4ced2aaa6782c1e61a3c9", + "reference": "00104306927c7a0919b4ced2aaa6782c1e61a3c9", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.3", + "phpstan/phpstan-strict-rules": "^1.1", + "symfony/phpunit-bridge": "^5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\Pcre\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + } + ], + "description": "PCRE wrapping library that offers type-safe preg_* replacements.", + "keywords": [ + "PCRE", + "preg", + "regex", + "regular expression" + ], + "support": { + "issues": "https://github.com/composer/pcre/issues", + "source": "https://github.com/composer/pcre/tree/3.1.1" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "time": "2023-10-11T07:11:09+00:00" + }, + { + "name": "composer/semver", + "version": "3.4.0", + "source": { + "type": "git", + "url": "https://github.com/composer/semver.git", + "reference": "35e8d0af4486141bc745f23a29cc2091eb624a32" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/semver/zipball/35e8d0af4486141bc745f23a29cc2091eb624a32", + "reference": "35e8d0af4486141bc745f23a29cc2091eb624a32", + "shasum": "" + }, + "require": { + "php": "^5.3.2 || ^7.0 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.4", + "symfony/phpunit-bridge": "^4.2 || ^5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\Semver\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nils Adermann", + "email": "naderman@naderman.de", + "homepage": "http://www.naderman.de" + }, + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + }, + { + "name": "Rob Bast", + "email": "rob.bast@gmail.com", + "homepage": "http://robbast.nl" + } + ], + "description": "Semver library that offers utilities, version constraint parsing and validation.", + "keywords": [ + "semantic", + "semver", + "validation", + "versioning" + ], + "support": { + "irc": "ircs://irc.libera.chat:6697/composer", + "issues": "https://github.com/composer/semver/issues", + "source": "https://github.com/composer/semver/tree/3.4.0" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "time": "2023-08-31T09:50:34+00:00" + }, + { + "name": "composer/xdebug-handler", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/composer/xdebug-handler.git", + "reference": "ced299686f41dce890debac69273b47ffe98a40c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/xdebug-handler/zipball/ced299686f41dce890debac69273b47ffe98a40c", + "reference": "ced299686f41dce890debac69273b47ffe98a40c", + "shasum": "" + }, + "require": { + "composer/pcre": "^1 || ^2 || ^3", + "php": "^7.2.5 || ^8.0", + "psr/log": "^1 || ^2 || ^3" + }, + "require-dev": { + "phpstan/phpstan": "^1.0", + "phpstan/phpstan-strict-rules": "^1.1", + "symfony/phpunit-bridge": "^6.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Composer\\XdebugHandler\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "John Stevenson", + "email": "john-stevenson@blueyonder.co.uk" + } + ], + "description": "Restarts a process without Xdebug.", + "keywords": [ + "Xdebug", + "performance" + ], + "support": { + "irc": "irc://irc.freenode.org/composer", + "issues": "https://github.com/composer/xdebug-handler/issues", + "source": "https://github.com/composer/xdebug-handler/tree/3.0.3" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "time": "2022-02-25T21:32:43+00:00" + }, + { + "name": "friendsofphp/php-cs-fixer", + "version": "v3.40.2", + "source": { + "type": "git", + "url": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer.git", + "reference": "4344562a516b76afe8f2d64b2e52214c30d64ed8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/4344562a516b76afe8f2d64b2e52214c30d64ed8", + "reference": "4344562a516b76afe8f2d64b2e52214c30d64ed8", + "shasum": "" + }, + "require": { + "composer/semver": "^3.4", + "composer/xdebug-handler": "^3.0.3", + "ext-json": "*", + "ext-tokenizer": "*", + "php": "^7.4 || ^8.0", + "sebastian/diff": "^4.0 || ^5.0", + "symfony/console": "^5.4 || ^6.0 || ^7.0", + "symfony/event-dispatcher": "^5.4 || ^6.0 || ^7.0", + "symfony/filesystem": "^5.4 || ^6.0 || ^7.0", + "symfony/finder": "^5.4 || ^6.0 || ^7.0", + "symfony/options-resolver": "^5.4 || ^6.0 || ^7.0", + "symfony/polyfill-mbstring": "^1.28", + "symfony/polyfill-php80": "^1.28", + "symfony/polyfill-php81": "^1.28", + "symfony/process": "^5.4 || ^6.0 || ^7.0", + "symfony/stopwatch": "^5.4 || ^6.0 || ^7.0" + }, + "require-dev": { + "facile-it/paraunit": "^1.3 || ^2.0", + "justinrainbow/json-schema": "^5.2", + "keradus/cli-executor": "^2.1", + "mikey179/vfsstream": "^1.6.11", + "php-coveralls/php-coveralls": "^2.7", + "php-cs-fixer/accessible-object": "^1.1", + "php-cs-fixer/phpunit-constraint-isidenticalstring": "^1.4", + "php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "^1.4", + "phpspec/prophecy": "^1.17", + "phpspec/prophecy-phpunit": "^2.0", + "phpunit/phpunit": "^9.6", + "symfony/phpunit-bridge": "^6.3.8 || ^7.0", + "symfony/yaml": "^5.4 || ^6.0 || ^7.0" + }, + "suggest": { + "ext-dom": "For handling output formats in XML", + "ext-mbstring": "For handling non-UTF8 characters." + }, + "bin": [ + "php-cs-fixer" + ], + "type": "application", + "autoload": { + "psr-4": { + "PhpCsFixer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Dariusz Rumiński", + "email": "dariusz.ruminski@gmail.com" + } + ], + "description": "A tool to automatically fix PHP code style", + "keywords": [ + "Static code analysis", + "fixer", + "standards", + "static analysis" + ], + "support": { + "issues": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues", + "source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.40.2" + }, + "funding": [ + { + "url": "https://github.com/keradus", + "type": "github" + } + ], + "time": "2023-12-03T09:21:33+00:00" + }, + { + "name": "psr/container", + "version": "2.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "shasum": "" + }, + "require": { + "php": ">=7.4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "support": { + "issues": "https://github.com/php-fig/container/issues", + "source": "https://github.com/php-fig/container/tree/2.0.2" + }, + "time": "2021-11-05T16:47:00+00:00" + }, + { + "name": "psr/event-dispatcher", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/event-dispatcher.git", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/event-dispatcher/zipball/dbefd12671e8a14ec7f180cab83036ed26714bb0", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0", + "shasum": "" + }, + "require": { + "php": ">=7.2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\EventDispatcher\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Standard interfaces for event handling.", + "keywords": [ + "events", + "psr", + "psr-14" + ], + "support": { + "issues": "https://github.com/php-fig/event-dispatcher/issues", + "source": "https://github.com/php-fig/event-dispatcher/tree/1.0.0" + }, + "time": "2019-01-08T18:20:26+00:00" + }, + { + "name": "psr/log", + "version": "3.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/fe5ea303b0887d5caefd3d431c3e61ad47037001", + "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https://github.com/php-fig/log/tree/3.0.0" + }, + "time": "2021-07-14T16:46:02+00:00" + }, + { + "name": "sebastian/diff", + "version": "5.0.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/diff.git", + "reference": "912dc2fbe3e3c1e7873313cc801b100b6c68c87b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/912dc2fbe3e3c1e7873313cc801b100b6c68c87b", + "reference": "912dc2fbe3e3c1e7873313cc801b100b6c68c87b", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.0", + "symfony/process": "^4.2 || ^5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + } + ], + "description": "Diff implementation", + "homepage": "https://github.com/sebastianbergmann/diff", + "keywords": [ + "diff", + "udiff", + "unidiff", + "unified diff" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/diff/issues", + "security": "https://github.com/sebastianbergmann/diff/security/policy", + "source": "https://github.com/sebastianbergmann/diff/tree/5.0.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-05-01T07:48:21+00:00" + }, + { + "name": "symfony/console", + "version": "v7.0.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/console.git", + "reference": "cdce5c684b2f920bb1343deecdfba356ffad83d5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/console/zipball/cdce5c684b2f920bb1343deecdfba356ffad83d5", + "reference": "cdce5c684b2f920bb1343deecdfba356ffad83d5", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/polyfill-mbstring": "~1.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/string": "^6.4|^7.0" + }, + "conflict": { + "symfony/dependency-injection": "<6.4", + "symfony/dotenv": "<6.4", + "symfony/event-dispatcher": "<6.4", + "symfony/lock": "<6.4", + "symfony/process": "<6.4" + }, + "provide": { + "psr/log-implementation": "1.0|2.0|3.0" + }, + "require-dev": { + "psr/log": "^1|^2|^3", + "symfony/config": "^6.4|^7.0", + "symfony/dependency-injection": "^6.4|^7.0", + "symfony/event-dispatcher": "^6.4|^7.0", + "symfony/http-foundation": "^6.4|^7.0", + "symfony/http-kernel": "^6.4|^7.0", + "symfony/lock": "^6.4|^7.0", + "symfony/messenger": "^6.4|^7.0", + "symfony/process": "^6.4|^7.0", + "symfony/stopwatch": "^6.4|^7.0", + "symfony/var-dumper": "^6.4|^7.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Console\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Eases the creation of beautiful and testable command line interfaces", + "homepage": "https://symfony.com", + "keywords": [ + "cli", + "command-line", + "console", + "terminal" + ], + "support": { + "source": "https://github.com/symfony/console/tree/v7.0.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-12-01T15:10:06+00:00" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v3.4.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/7c3aff79d10325257a001fcf92d991f24fc967cf", + "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-05-23T14:45:45+00:00" + }, + { + "name": "symfony/event-dispatcher", + "version": "v7.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "c459b40ffe67c49af6fd392aac374c9edf8a027e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/c459b40ffe67c49af6fd392aac374c9edf8a027e", + "reference": "c459b40ffe67c49af6fd392aac374c9edf8a027e", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/event-dispatcher-contracts": "^2.5|^3" + }, + "conflict": { + "symfony/dependency-injection": "<6.4", + "symfony/service-contracts": "<2.5" + }, + "provide": { + "psr/event-dispatcher-implementation": "1.0", + "symfony/event-dispatcher-implementation": "2.0|3.0" + }, + "require-dev": { + "psr/log": "^1|^2|^3", + "symfony/config": "^6.4|^7.0", + "symfony/dependency-injection": "^6.4|^7.0", + "symfony/error-handler": "^6.4|^7.0", + "symfony/expression-language": "^6.4|^7.0", + "symfony/http-foundation": "^6.4|^7.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/stopwatch": "^6.4|^7.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\EventDispatcher\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides tools that allow your application components to communicate with each other by dispatching events and listening to them", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/event-dispatcher/tree/v7.0.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-07-27T16:29:09+00:00" + }, + { + "name": "symfony/event-dispatcher-contracts", + "version": "v3.4.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher-contracts.git", + "reference": "a76aed96a42d2b521153fb382d418e30d18b59df" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/a76aed96a42d2b521153fb382d418e30d18b59df", + "reference": "a76aed96a42d2b521153fb382d418e30d18b59df", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/event-dispatcher": "^1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\EventDispatcher\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to dispatching event", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-05-23T14:45:45+00:00" + }, + { + "name": "symfony/filesystem", + "version": "v7.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/filesystem.git", + "reference": "7da8ea2362a283771478c5f7729cfcb43a76b8b7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/7da8ea2362a283771478c5f7729cfcb43a76b8b7", + "reference": "7da8ea2362a283771478c5f7729cfcb43a76b8b7", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-mbstring": "~1.8" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Filesystem\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides basic utilities for the filesystem", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/filesystem/tree/v7.0.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-07-27T06:33:22+00:00" + }, + { + "name": "symfony/finder", + "version": "v7.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/finder.git", + "reference": "6e5688d69f7cfc4ed4a511e96007e06c2d34ce56" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/finder/zipball/6e5688d69f7cfc4ed4a511e96007e06c2d34ce56", + "reference": "6e5688d69f7cfc4ed4a511e96007e06c2d34ce56", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "symfony/filesystem": "^6.4|^7.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Finder\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Finds files and directories via an intuitive fluent interface", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/finder/tree/v7.0.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-10-31T17:59:56+00:00" + }, + { + "name": "symfony/options-resolver", + "version": "v7.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/options-resolver.git", + "reference": "700ff4096e346f54cb628ea650767c8130f1001f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/700ff4096e346f54cb628ea650767c8130f1001f", + "reference": "700ff4096e346f54cb628ea650767c8130f1001f", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/deprecation-contracts": "^2.5|^3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\OptionsResolver\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides an improved replacement for the array_replace PHP function", + "homepage": "https://symfony.com", + "keywords": [ + "config", + "configuration", + "options" + ], + "support": { + "source": "https://github.com/symfony/options-resolver/tree/v7.0.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-08-08T10:20:21+00:00" + }, + { + "name": "symfony/polyfill-ctype", + "version": "v1.28.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-ctype.git", + "reference": "ea208ce43cbb04af6867b4fdddb1bdbf84cc28cb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/ea208ce43cbb04af6867b4fdddb1bdbf84cc28cb", + "reference": "ea208ce43cbb04af6867b4fdddb1bdbf84cc28cb", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-ctype": "*" + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Ctype\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for ctype functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "ctype", + "polyfill", + "portable" + ], + "support": { + "source": "https://github.com/symfony/polyfill-ctype/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-01-26T09:26:14+00:00" + }, + { + "name": "symfony/polyfill-intl-grapheme", + "version": "v1.28.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-grapheme.git", + "reference": "875e90aeea2777b6f135677f618529449334a612" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/875e90aeea2777b6f135677f618529449334a612", + "reference": "875e90aeea2777b6f135677f618529449334a612", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Grapheme\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's grapheme_* functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "grapheme", + "intl", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-01-26T09:26:14+00:00" + }, + { + "name": "symfony/polyfill-intl-normalizer", + "version": "v1.28.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-normalizer.git", + "reference": "8c4ad05dd0120b6a53c1ca374dca2ad0a1c4ed92" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/8c4ad05dd0120b6a53c1ca374dca2ad0a1c4ed92", + "reference": "8c4ad05dd0120b6a53c1ca374dca2ad0a1c4ed92", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Normalizer\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's Normalizer class and related functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "intl", + "normalizer", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-01-26T09:26:14+00:00" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.28.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "42292d99c55abe617799667f454222c54c60e229" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/42292d99c55abe617799667f454222c54c60e229", + "reference": "42292d99c55abe617799667f454222c54c60e229", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-mbstring": "*" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-07-28T09:04:16+00:00" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.28.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/6caa57379c4aec19c0a12a38b59b26487dcfe4b5", + "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-01-26T09:26:14+00:00" + }, + { + "name": "symfony/polyfill-php81", + "version": "v1.28.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php81.git", + "reference": "7581cd600fa9fd681b797d00b02f068e2f13263b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php81/zipball/7581cd600fa9fd681b797d00b02f068e2f13263b", + "reference": "7581cd600fa9fd681b797d00b02f068e2f13263b", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php81\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php81/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-01-26T09:26:14+00:00" + }, + { + "name": "symfony/process", + "version": "v7.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/process.git", + "reference": "13bdb1670c7f510494e04fcb2bfa29af63db9c0d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/process/zipball/13bdb1670c7f510494e04fcb2bfa29af63db9c0d", + "reference": "13bdb1670c7f510494e04fcb2bfa29af63db9c0d", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Process\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Executes commands in sub-processes", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/process/tree/v7.0.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-11-20T16:43:42+00:00" + }, + { + "name": "symfony/service-contracts", + "version": "v3.4.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/service-contracts.git", + "reference": "b3313c2dbffaf71c8de2934e2ea56ed2291a3838" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/b3313c2dbffaf71c8de2934e2ea56ed2291a3838", + "reference": "b3313c2dbffaf71c8de2934e2ea56ed2291a3838", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/container": "^2.0" + }, + "conflict": { + "ext-psr": "<1.1|>=2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\Service\\": "" + }, + "exclude-from-classmap": [ + "/Test/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to writing services", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/service-contracts/tree/v3.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-07-30T20:28:31+00:00" + }, + { + "name": "symfony/stopwatch", + "version": "v7.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/stopwatch.git", + "reference": "7bbfa3dd564a0ce12eb4acaaa46823c740f9cb7a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/stopwatch/zipball/7bbfa3dd564a0ce12eb4acaaa46823c740f9cb7a", + "reference": "7bbfa3dd564a0ce12eb4acaaa46823c740f9cb7a", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/service-contracts": "^2.5|^3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Stopwatch\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides a way to profile code", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/stopwatch/tree/v7.0.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-07-05T13:06:06+00:00" + }, + { + "name": "symfony/string", + "version": "v7.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/string.git", + "reference": "92bd2bfbba476d4a1838e5e12168bef2fd1e6620" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/string/zipball/92bd2bfbba476d4a1838e5e12168bef2fd1e6620", + "reference": "92bd2bfbba476d4a1838e5e12168bef2fd1e6620", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-intl-grapheme": "~1.0", + "symfony/polyfill-intl-normalizer": "~1.0", + "symfony/polyfill-mbstring": "~1.0" + }, + "conflict": { + "symfony/translation-contracts": "<2.5" + }, + "require-dev": { + "symfony/error-handler": "^6.4|^7.0", + "symfony/http-client": "^6.4|^7.0", + "symfony/intl": "^6.4|^7.0", + "symfony/translation-contracts": "^2.5|^3.0", + "symfony/var-exporter": "^6.4|^7.0" + }, + "type": "library", + "autoload": { + "files": [ + "Resources/functions.php" + ], + "psr-4": { + "Symfony\\Component\\String\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way", + "homepage": "https://symfony.com", + "keywords": [ + "grapheme", + "i18n", + "string", + "unicode", + "utf-8", + "utf8" + ], + "support": { + "source": "https://github.com/symfony/string/tree/v7.0.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-11-29T08:40:23+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": [], + "platform-dev": [], + "plugin-api-version": "2.2.0" +} diff --git a/tools/php-cs-fixer/vendor/autoload.php b/tools/php-cs-fixer/vendor/autoload.php new file mode 100644 index 00000000..ce61e6f1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/autoload.php @@ -0,0 +1,7 @@ +realpath = realpath($opened_path) ?: $opened_path; + $opened_path = $this->realpath; + $this->handle = fopen($this->realpath, $mode); + $this->position = 0; + + return (bool) $this->handle; + } + + public function stream_read($count) + { + $data = fread($this->handle, $count); + + if ($this->position === 0) { + $data = preg_replace('{^#!.*\r?\n}', '', $data); + } + + $this->position += strlen($data); + + return $data; + } + + public function stream_cast($castAs) + { + return $this->handle; + } + + public function stream_close() + { + fclose($this->handle); + } + + public function stream_lock($operation) + { + return $operation ? flock($this->handle, $operation) : true; + } + + public function stream_seek($offset, $whence) + { + if (0 === fseek($this->handle, $offset, $whence)) { + $this->position = ftell($this->handle); + return true; + } + + return false; + } + + public function stream_tell() + { + return $this->position; + } + + public function stream_eof() + { + return feof($this->handle); + } + + public function stream_stat() + { + return array(); + } + + public function stream_set_option($option, $arg1, $arg2) + { + return true; + } + + public function url_stat($path, $flags) + { + $path = substr($path, 17); + if (file_exists($path)) { + return stat($path); + } + + return false; + } + } + } + + if (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper')) { + include("phpvfscomposer://" . __DIR__ . '/..'.'/friendsofphp/php-cs-fixer/php-cs-fixer'); + exit(0); + } +} + +include __DIR__ . '/..'.'/friendsofphp/php-cs-fixer/php-cs-fixer'; diff --git a/tools/php-cs-fixer/vendor/composer/ClassLoader.php b/tools/php-cs-fixer/vendor/composer/ClassLoader.php new file mode 100644 index 00000000..afef3fa2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/ClassLoader.php @@ -0,0 +1,572 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see https://www.php-fig.org/psr/psr-0/ + * @see https://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + /** @var ?string */ + private $vendorDir; + + // PSR-4 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array[] + * @psalm-var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr4 = array(); + + // PSR-0 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixesPsr0 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var string[] + * @psalm-var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var bool[] + * @psalm-var array + */ + private $missingClasses = array(); + + /** @var ?string */ + private $apcuPrefix; + + /** + * @var self[] + */ + private static $registeredLoaders = array(); + + /** + * @param ?string $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + } + + /** + * @return string[] + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array[] + * @psalm-return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return string[] Array of classname => path + * @psalm-return array + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param string[] $classMap Class to filename map + * @psalm-param array $classMap + * + * @return void + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + * + * @return void + */ + public function add($prefix, $paths, $prepend = false) + { + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + (array) $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + (array) $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = (array) $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + (array) $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + (array) $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + (array) $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + (array) $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 base directories + * + * @return void + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + * + * @return void + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + * + * @return void + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + * + * @return void + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + * + * @return void + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + + if (null === $this->vendorDir) { + return; + } + + if ($prepend) { + self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; + } else { + unset(self::$registeredLoaders[$this->vendorDir]); + self::$registeredLoaders[$this->vendorDir] = $this; + } + } + + /** + * Unregisters this instance as an autoloader. + * + * @return void + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + + if (null !== $this->vendorDir) { + unset(self::$registeredLoaders[$this->vendorDir]); + } + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return true|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + includeFile($file); + + return true; + } + + return null; + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { + return false; + } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + /** + * Returns the currently registered loaders indexed by their corresponding vendor directories. + * + * @return self[] + */ + public static function getRegisteredLoaders() + { + return self::$registeredLoaders; + } + + /** + * @param string $class + * @param string $ext + * @return string|false + */ + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath . '\\'; + if (isset($this->prefixDirsPsr4[$search])) { + $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + foreach ($this->prefixDirsPsr4[$search] as $dir) { + if (file_exists($file = $dir . $pathEnd)) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } +} + +/** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + * @private + */ +function includeFile($file) +{ + include $file; +} diff --git a/tools/php-cs-fixer/vendor/composer/InstalledVersions.php b/tools/php-cs-fixer/vendor/composer/InstalledVersions.php new file mode 100644 index 00000000..d50e0c9f --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/InstalledVersions.php @@ -0,0 +1,350 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Autoload\ClassLoader; +use Composer\Semver\VersionParser; + +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + */ +class InstalledVersions +{ + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array}|array{}|null + */ + private static $installed; + + /** + * @var bool|null + */ + private static $canGetVendors; + + /** + * @var array[] + * @psalm-var array}> + */ + private static $installedByVendor = array(); + + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() + { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = array_keys($installed['versions']); + } + + if (1 === \count($packages)) { + return $packages[0]; + } + + return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); + } + + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) + { + $packagesByType = array(); + + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + + return $packagesByType; + } + + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = true) + { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']); + } + } + + return false; + } + + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) + { + $constraint = $parser->parseConstraints($constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + + return $provided->matches($constraint); + } + + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + + return implode(' || ', $ranges); + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['version'])) { + return null; + } + + return $installed['versions'][$packageName]['version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + + return $installed['versions'][$packageName]['pretty_version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['reference'])) { + return null; + } + + return $installed['versions'][$packageName]['reference']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @return array + * @psalm-return array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string} + */ + public static function getRootPackage() + { + $installed = self::getInstalled(); + + return $installed[0]['root']; + } + + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array} + */ + public static function getRawData() + { + @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = include __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + + return self::$installed; + } + + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() + { + return self::getInstalled(); + } + + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + + if (self::$canGetVendors) { + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (is_file($vendorDir.'/composer/installed.php')) { + $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php'; + if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { + self::$installed = $installed[count($installed) - 1]; + } + } + } + } + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = require __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + $installed[] = self::$installed; + + return $installed; + } +} diff --git a/tools/php-cs-fixer/vendor/composer/LICENSE b/tools/php-cs-fixer/vendor/composer/LICENSE new file mode 100644 index 00000000..f27399a0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) Nils Adermann, Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/tools/php-cs-fixer/vendor/composer/autoload_classmap.php b/tools/php-cs-fixer/vendor/composer/autoload_classmap.php new file mode 100644 index 00000000..cc6c28d3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/autoload_classmap.php @@ -0,0 +1,34 @@ + $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'CURLStringFile' => $vendorDir . '/symfony/polyfill-php81/Resources/stubs/CURLStringFile.php', + 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', + 'Normalizer' => $vendorDir . '/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php', + 'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php', + 'ReturnTypeWillChange' => $vendorDir . '/symfony/polyfill-php81/Resources/stubs/ReturnTypeWillChange.php', + 'SebastianBergmann\\Diff\\Chunk' => $vendorDir . '/sebastian/diff/src/Chunk.php', + 'SebastianBergmann\\Diff\\ConfigurationException' => $vendorDir . '/sebastian/diff/src/Exception/ConfigurationException.php', + 'SebastianBergmann\\Diff\\Diff' => $vendorDir . '/sebastian/diff/src/Diff.php', + 'SebastianBergmann\\Diff\\Differ' => $vendorDir . '/sebastian/diff/src/Differ.php', + 'SebastianBergmann\\Diff\\Exception' => $vendorDir . '/sebastian/diff/src/Exception/Exception.php', + 'SebastianBergmann\\Diff\\InvalidArgumentException' => $vendorDir . '/sebastian/diff/src/Exception/InvalidArgumentException.php', + 'SebastianBergmann\\Diff\\Line' => $vendorDir . '/sebastian/diff/src/Line.php', + 'SebastianBergmann\\Diff\\LongestCommonSubsequenceCalculator' => $vendorDir . '/sebastian/diff/src/LongestCommonSubsequenceCalculator.php', + 'SebastianBergmann\\Diff\\MemoryEfficientLongestCommonSubsequenceCalculator' => $vendorDir . '/sebastian/diff/src/MemoryEfficientLongestCommonSubsequenceCalculator.php', + 'SebastianBergmann\\Diff\\Output\\AbstractChunkOutputBuilder' => $vendorDir . '/sebastian/diff/src/Output/AbstractChunkOutputBuilder.php', + 'SebastianBergmann\\Diff\\Output\\DiffOnlyOutputBuilder' => $vendorDir . '/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php', + 'SebastianBergmann\\Diff\\Output\\DiffOutputBuilderInterface' => $vendorDir . '/sebastian/diff/src/Output/DiffOutputBuilderInterface.php', + 'SebastianBergmann\\Diff\\Output\\StrictUnifiedDiffOutputBuilder' => $vendorDir . '/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php', + 'SebastianBergmann\\Diff\\Output\\UnifiedDiffOutputBuilder' => $vendorDir . '/sebastian/diff/src/Output/UnifiedDiffOutputBuilder.php', + 'SebastianBergmann\\Diff\\Parser' => $vendorDir . '/sebastian/diff/src/Parser.php', + 'SebastianBergmann\\Diff\\TimeEfficientLongestCommonSubsequenceCalculator' => $vendorDir . '/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php', + 'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', + 'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', + 'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', +); diff --git a/tools/php-cs-fixer/vendor/composer/autoload_files.php b/tools/php-cs-fixer/vendor/composer/autoload_files.php new file mode 100644 index 00000000..ccf1f887 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/autoload_files.php @@ -0,0 +1,17 @@ + $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php', + '320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php', + 'e69f7f6ee287b969198c3c9d6777bd38' => $vendorDir . '/symfony/polyfill-intl-normalizer/bootstrap.php', + '8825ede83f2f289127722d4e842cf7e8' => $vendorDir . '/symfony/polyfill-intl-grapheme/bootstrap.php', + '6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php', + 'b6b991a57620e2fb6b2f66f03fe9ddc2' => $vendorDir . '/symfony/string/Resources/functions.php', + '23c18046f52bef3eea034657bafda50f' => $vendorDir . '/symfony/polyfill-php81/bootstrap.php', + 'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php', +); diff --git a/tools/php-cs-fixer/vendor/composer/autoload_namespaces.php b/tools/php-cs-fixer/vendor/composer/autoload_namespaces.php new file mode 100644 index 00000000..b7fc0125 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($vendorDir . '/symfony/polyfill-php81'), + 'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'), + 'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'), + 'Symfony\\Polyfill\\Intl\\Normalizer\\' => array($vendorDir . '/symfony/polyfill-intl-normalizer'), + 'Symfony\\Polyfill\\Intl\\Grapheme\\' => array($vendorDir . '/symfony/polyfill-intl-grapheme'), + 'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'), + 'Symfony\\Contracts\\Service\\' => array($vendorDir . '/symfony/service-contracts'), + 'Symfony\\Contracts\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher-contracts'), + 'Symfony\\Component\\String\\' => array($vendorDir . '/symfony/string'), + 'Symfony\\Component\\Stopwatch\\' => array($vendorDir . '/symfony/stopwatch'), + 'Symfony\\Component\\Process\\' => array($vendorDir . '/symfony/process'), + 'Symfony\\Component\\OptionsResolver\\' => array($vendorDir . '/symfony/options-resolver'), + 'Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'), + 'Symfony\\Component\\Filesystem\\' => array($vendorDir . '/symfony/filesystem'), + 'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'), + 'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'), + 'Psr\\Log\\' => array($vendorDir . '/psr/log/src'), + 'Psr\\EventDispatcher\\' => array($vendorDir . '/psr/event-dispatcher/src'), + 'Psr\\Container\\' => array($vendorDir . '/psr/container/src'), + 'PhpCsFixer\\' => array($vendorDir . '/friendsofphp/php-cs-fixer/src'), + 'Composer\\XdebugHandler\\' => array($vendorDir . '/composer/xdebug-handler/src'), + 'Composer\\Semver\\' => array($vendorDir . '/composer/semver/src'), + 'Composer\\Pcre\\' => array($vendorDir . '/composer/pcre/src'), +); diff --git a/tools/php-cs-fixer/vendor/composer/autoload_real.php b/tools/php-cs-fixer/vendor/composer/autoload_real.php new file mode 100644 index 00000000..ec1cd2c5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/autoload_real.php @@ -0,0 +1,80 @@ += 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); + if ($useStaticLoader) { + require __DIR__ . '/autoload_static.php'; + + call_user_func(\Composer\Autoload\ComposerStaticInitd6b4bfe3ef87af372b76a8e671c3e7c3::getInitializer($loader)); + } else { + $map = require __DIR__ . '/autoload_namespaces.php'; + foreach ($map as $namespace => $path) { + $loader->set($namespace, $path); + } + + $map = require __DIR__ . '/autoload_psr4.php'; + foreach ($map as $namespace => $path) { + $loader->setPsr4($namespace, $path); + } + + $classMap = require __DIR__ . '/autoload_classmap.php'; + if ($classMap) { + $loader->addClassMap($classMap); + } + } + + $loader->register(true); + + if ($useStaticLoader) { + $includeFiles = Composer\Autoload\ComposerStaticInitd6b4bfe3ef87af372b76a8e671c3e7c3::$files; + } else { + $includeFiles = require __DIR__ . '/autoload_files.php'; + } + foreach ($includeFiles as $fileIdentifier => $file) { + composerRequired6b4bfe3ef87af372b76a8e671c3e7c3($fileIdentifier, $file); + } + + return $loader; + } +} + +/** + * @param string $fileIdentifier + * @param string $file + * @return void + */ +function composerRequired6b4bfe3ef87af372b76a8e671c3e7c3($fileIdentifier, $file) +{ + if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { + $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; + + require $file; + } +} diff --git a/tools/php-cs-fixer/vendor/composer/autoload_static.php b/tools/php-cs-fixer/vendor/composer/autoload_static.php new file mode 100644 index 00000000..63ffb56d --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/autoload_static.php @@ -0,0 +1,187 @@ + __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php', + '320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php', + 'e69f7f6ee287b969198c3c9d6777bd38' => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer/bootstrap.php', + '8825ede83f2f289127722d4e842cf7e8' => __DIR__ . '/..' . '/symfony/polyfill-intl-grapheme/bootstrap.php', + '6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php', + 'b6b991a57620e2fb6b2f66f03fe9ddc2' => __DIR__ . '/..' . '/symfony/string/Resources/functions.php', + '23c18046f52bef3eea034657bafda50f' => __DIR__ . '/..' . '/symfony/polyfill-php81/bootstrap.php', + 'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php', + ); + + public static $prefixLengthsPsr4 = array ( + 'S' => + array ( + 'Symfony\\Polyfill\\Php81\\' => 23, + 'Symfony\\Polyfill\\Php80\\' => 23, + 'Symfony\\Polyfill\\Mbstring\\' => 26, + 'Symfony\\Polyfill\\Intl\\Normalizer\\' => 33, + 'Symfony\\Polyfill\\Intl\\Grapheme\\' => 31, + 'Symfony\\Polyfill\\Ctype\\' => 23, + 'Symfony\\Contracts\\Service\\' => 26, + 'Symfony\\Contracts\\EventDispatcher\\' => 34, + 'Symfony\\Component\\String\\' => 25, + 'Symfony\\Component\\Stopwatch\\' => 28, + 'Symfony\\Component\\Process\\' => 26, + 'Symfony\\Component\\OptionsResolver\\' => 34, + 'Symfony\\Component\\Finder\\' => 25, + 'Symfony\\Component\\Filesystem\\' => 29, + 'Symfony\\Component\\EventDispatcher\\' => 34, + 'Symfony\\Component\\Console\\' => 26, + ), + 'P' => + array ( + 'Psr\\Log\\' => 8, + 'Psr\\EventDispatcher\\' => 20, + 'Psr\\Container\\' => 14, + 'PhpCsFixer\\' => 11, + ), + 'C' => + array ( + 'Composer\\XdebugHandler\\' => 23, + 'Composer\\Semver\\' => 16, + 'Composer\\Pcre\\' => 14, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'Symfony\\Polyfill\\Php81\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php81', + ), + 'Symfony\\Polyfill\\Php80\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php80', + ), + 'Symfony\\Polyfill\\Mbstring\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring', + ), + 'Symfony\\Polyfill\\Intl\\Normalizer\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer', + ), + 'Symfony\\Polyfill\\Intl\\Grapheme\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-intl-grapheme', + ), + 'Symfony\\Polyfill\\Ctype\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-ctype', + ), + 'Symfony\\Contracts\\Service\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/service-contracts', + ), + 'Symfony\\Contracts\\EventDispatcher\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/event-dispatcher-contracts', + ), + 'Symfony\\Component\\String\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/string', + ), + 'Symfony\\Component\\Stopwatch\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/stopwatch', + ), + 'Symfony\\Component\\Process\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/process', + ), + 'Symfony\\Component\\OptionsResolver\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/options-resolver', + ), + 'Symfony\\Component\\Finder\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/finder', + ), + 'Symfony\\Component\\Filesystem\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/filesystem', + ), + 'Symfony\\Component\\EventDispatcher\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/event-dispatcher', + ), + 'Symfony\\Component\\Console\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/console', + ), + 'Psr\\Log\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/log/src', + ), + 'Psr\\EventDispatcher\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/event-dispatcher/src', + ), + 'Psr\\Container\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/container/src', + ), + 'PhpCsFixer\\' => + array ( + 0 => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src', + ), + 'Composer\\XdebugHandler\\' => + array ( + 0 => __DIR__ . '/..' . '/composer/xdebug-handler/src', + ), + 'Composer\\Semver\\' => + array ( + 0 => __DIR__ . '/..' . '/composer/semver/src', + ), + 'Composer\\Pcre\\' => + array ( + 0 => __DIR__ . '/..' . '/composer/pcre/src', + ), + ); + + public static $classMap = array ( + 'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'CURLStringFile' => __DIR__ . '/..' . '/symfony/polyfill-php81/Resources/stubs/CURLStringFile.php', + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + 'Normalizer' => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php', + 'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php', + 'ReturnTypeWillChange' => __DIR__ . '/..' . '/symfony/polyfill-php81/Resources/stubs/ReturnTypeWillChange.php', + 'SebastianBergmann\\Diff\\Chunk' => __DIR__ . '/..' . '/sebastian/diff/src/Chunk.php', + 'SebastianBergmann\\Diff\\ConfigurationException' => __DIR__ . '/..' . '/sebastian/diff/src/Exception/ConfigurationException.php', + 'SebastianBergmann\\Diff\\Diff' => __DIR__ . '/..' . '/sebastian/diff/src/Diff.php', + 'SebastianBergmann\\Diff\\Differ' => __DIR__ . '/..' . '/sebastian/diff/src/Differ.php', + 'SebastianBergmann\\Diff\\Exception' => __DIR__ . '/..' . '/sebastian/diff/src/Exception/Exception.php', + 'SebastianBergmann\\Diff\\InvalidArgumentException' => __DIR__ . '/..' . '/sebastian/diff/src/Exception/InvalidArgumentException.php', + 'SebastianBergmann\\Diff\\Line' => __DIR__ . '/..' . '/sebastian/diff/src/Line.php', + 'SebastianBergmann\\Diff\\LongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/sebastian/diff/src/LongestCommonSubsequenceCalculator.php', + 'SebastianBergmann\\Diff\\MemoryEfficientLongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/sebastian/diff/src/MemoryEfficientLongestCommonSubsequenceCalculator.php', + 'SebastianBergmann\\Diff\\Output\\AbstractChunkOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/AbstractChunkOutputBuilder.php', + 'SebastianBergmann\\Diff\\Output\\DiffOnlyOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php', + 'SebastianBergmann\\Diff\\Output\\DiffOutputBuilderInterface' => __DIR__ . '/..' . '/sebastian/diff/src/Output/DiffOutputBuilderInterface.php', + 'SebastianBergmann\\Diff\\Output\\StrictUnifiedDiffOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php', + 'SebastianBergmann\\Diff\\Output\\UnifiedDiffOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/UnifiedDiffOutputBuilder.php', + 'SebastianBergmann\\Diff\\Parser' => __DIR__ . '/..' . '/sebastian/diff/src/Parser.php', + 'SebastianBergmann\\Diff\\TimeEfficientLongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php', + 'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', + 'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', + 'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInitd6b4bfe3ef87af372b76a8e671c3e7c3::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInitd6b4bfe3ef87af372b76a8e671c3e7c3::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInitd6b4bfe3ef87af372b76a8e671c3e7c3::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/tools/php-cs-fixer/vendor/composer/installed.json b/tools/php-cs-fixer/vendor/composer/installed.json new file mode 100644 index 00000000..bdc2ea51 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/installed.json @@ -0,0 +1,1905 @@ +{ + "packages": [ + { + "name": "composer/pcre", + "version": "3.1.1", + "version_normalized": "3.1.1.0", + "source": { + "type": "git", + "url": "https://github.com/composer/pcre.git", + "reference": "00104306927c7a0919b4ced2aaa6782c1e61a3c9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/pcre/zipball/00104306927c7a0919b4ced2aaa6782c1e61a3c9", + "reference": "00104306927c7a0919b4ced2aaa6782c1e61a3c9", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.3", + "phpstan/phpstan-strict-rules": "^1.1", + "symfony/phpunit-bridge": "^5" + }, + "time": "2023-10-11T07:11:09+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Composer\\Pcre\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + } + ], + "description": "PCRE wrapping library that offers type-safe preg_* replacements.", + "keywords": [ + "PCRE", + "preg", + "regex", + "regular expression" + ], + "support": { + "issues": "https://github.com/composer/pcre/issues", + "source": "https://github.com/composer/pcre/tree/3.1.1" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "install-path": "./pcre" + }, + { + "name": "composer/semver", + "version": "3.4.0", + "version_normalized": "3.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/composer/semver.git", + "reference": "35e8d0af4486141bc745f23a29cc2091eb624a32" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/semver/zipball/35e8d0af4486141bc745f23a29cc2091eb624a32", + "reference": "35e8d0af4486141bc745f23a29cc2091eb624a32", + "shasum": "" + }, + "require": { + "php": "^5.3.2 || ^7.0 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.4", + "symfony/phpunit-bridge": "^4.2 || ^5" + }, + "time": "2023-08-31T09:50:34+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Composer\\Semver\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nils Adermann", + "email": "naderman@naderman.de", + "homepage": "http://www.naderman.de" + }, + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + }, + { + "name": "Rob Bast", + "email": "rob.bast@gmail.com", + "homepage": "http://robbast.nl" + } + ], + "description": "Semver library that offers utilities, version constraint parsing and validation.", + "keywords": [ + "semantic", + "semver", + "validation", + "versioning" + ], + "support": { + "irc": "ircs://irc.libera.chat:6697/composer", + "issues": "https://github.com/composer/semver/issues", + "source": "https://github.com/composer/semver/tree/3.4.0" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "install-path": "./semver" + }, + { + "name": "composer/xdebug-handler", + "version": "3.0.3", + "version_normalized": "3.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/composer/xdebug-handler.git", + "reference": "ced299686f41dce890debac69273b47ffe98a40c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/xdebug-handler/zipball/ced299686f41dce890debac69273b47ffe98a40c", + "reference": "ced299686f41dce890debac69273b47ffe98a40c", + "shasum": "" + }, + "require": { + "composer/pcre": "^1 || ^2 || ^3", + "php": "^7.2.5 || ^8.0", + "psr/log": "^1 || ^2 || ^3" + }, + "require-dev": { + "phpstan/phpstan": "^1.0", + "phpstan/phpstan-strict-rules": "^1.1", + "symfony/phpunit-bridge": "^6.0" + }, + "time": "2022-02-25T21:32:43+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Composer\\XdebugHandler\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "John Stevenson", + "email": "john-stevenson@blueyonder.co.uk" + } + ], + "description": "Restarts a process without Xdebug.", + "keywords": [ + "Xdebug", + "performance" + ], + "support": { + "irc": "irc://irc.freenode.org/composer", + "issues": "https://github.com/composer/xdebug-handler/issues", + "source": "https://github.com/composer/xdebug-handler/tree/3.0.3" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "install-path": "./xdebug-handler" + }, + { + "name": "friendsofphp/php-cs-fixer", + "version": "v3.40.2", + "version_normalized": "3.40.2.0", + "source": { + "type": "git", + "url": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer.git", + "reference": "4344562a516b76afe8f2d64b2e52214c30d64ed8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/4344562a516b76afe8f2d64b2e52214c30d64ed8", + "reference": "4344562a516b76afe8f2d64b2e52214c30d64ed8", + "shasum": "" + }, + "require": { + "composer/semver": "^3.4", + "composer/xdebug-handler": "^3.0.3", + "ext-json": "*", + "ext-tokenizer": "*", + "php": "^7.4 || ^8.0", + "sebastian/diff": "^4.0 || ^5.0", + "symfony/console": "^5.4 || ^6.0 || ^7.0", + "symfony/event-dispatcher": "^5.4 || ^6.0 || ^7.0", + "symfony/filesystem": "^5.4 || ^6.0 || ^7.0", + "symfony/finder": "^5.4 || ^6.0 || ^7.0", + "symfony/options-resolver": "^5.4 || ^6.0 || ^7.0", + "symfony/polyfill-mbstring": "^1.28", + "symfony/polyfill-php80": "^1.28", + "symfony/polyfill-php81": "^1.28", + "symfony/process": "^5.4 || ^6.0 || ^7.0", + "symfony/stopwatch": "^5.4 || ^6.0 || ^7.0" + }, + "require-dev": { + "facile-it/paraunit": "^1.3 || ^2.0", + "justinrainbow/json-schema": "^5.2", + "keradus/cli-executor": "^2.1", + "mikey179/vfsstream": "^1.6.11", + "php-coveralls/php-coveralls": "^2.7", + "php-cs-fixer/accessible-object": "^1.1", + "php-cs-fixer/phpunit-constraint-isidenticalstring": "^1.4", + "php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "^1.4", + "phpspec/prophecy": "^1.17", + "phpspec/prophecy-phpunit": "^2.0", + "phpunit/phpunit": "^9.6", + "symfony/phpunit-bridge": "^6.3.8 || ^7.0", + "symfony/yaml": "^5.4 || ^6.0 || ^7.0" + }, + "suggest": { + "ext-dom": "For handling output formats in XML", + "ext-mbstring": "For handling non-UTF8 characters." + }, + "time": "2023-12-03T09:21:33+00:00", + "bin": [ + "php-cs-fixer" + ], + "type": "application", + "installation-source": "dist", + "autoload": { + "psr-4": { + "PhpCsFixer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Dariusz Rumiński", + "email": "dariusz.ruminski@gmail.com" + } + ], + "description": "A tool to automatically fix PHP code style", + "keywords": [ + "Static code analysis", + "fixer", + "standards", + "static analysis" + ], + "support": { + "issues": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues", + "source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.40.2" + }, + "funding": [ + { + "url": "https://github.com/keradus", + "type": "github" + } + ], + "install-path": "../friendsofphp/php-cs-fixer" + }, + { + "name": "psr/container", + "version": "2.0.2", + "version_normalized": "2.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "shasum": "" + }, + "require": { + "php": ">=7.4.0" + }, + "time": "2021-11-05T16:47:00+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "support": { + "issues": "https://github.com/php-fig/container/issues", + "source": "https://github.com/php-fig/container/tree/2.0.2" + }, + "install-path": "../psr/container" + }, + { + "name": "psr/event-dispatcher", + "version": "1.0.0", + "version_normalized": "1.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/event-dispatcher.git", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/event-dispatcher/zipball/dbefd12671e8a14ec7f180cab83036ed26714bb0", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0", + "shasum": "" + }, + "require": { + "php": ">=7.2.0" + }, + "time": "2019-01-08T18:20:26+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\EventDispatcher\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Standard interfaces for event handling.", + "keywords": [ + "events", + "psr", + "psr-14" + ], + "support": { + "issues": "https://github.com/php-fig/event-dispatcher/issues", + "source": "https://github.com/php-fig/event-dispatcher/tree/1.0.0" + }, + "install-path": "../psr/event-dispatcher" + }, + { + "name": "psr/log", + "version": "3.0.0", + "version_normalized": "3.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/fe5ea303b0887d5caefd3d431c3e61ad47037001", + "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "time": "2021-07-14T16:46:02+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https://github.com/php-fig/log/tree/3.0.0" + }, + "install-path": "../psr/log" + }, + { + "name": "sebastian/diff", + "version": "5.0.3", + "version_normalized": "5.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/diff.git", + "reference": "912dc2fbe3e3c1e7873313cc801b100b6c68c87b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/912dc2fbe3e3c1e7873313cc801b100b6c68c87b", + "reference": "912dc2fbe3e3c1e7873313cc801b100b6c68c87b", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.0", + "symfony/process": "^4.2 || ^5" + }, + "time": "2023-05-01T07:48:21+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "installation-source": "dist", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + } + ], + "description": "Diff implementation", + "homepage": "https://github.com/sebastianbergmann/diff", + "keywords": [ + "diff", + "udiff", + "unidiff", + "unified diff" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/diff/issues", + "security": "https://github.com/sebastianbergmann/diff/security/policy", + "source": "https://github.com/sebastianbergmann/diff/tree/5.0.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "install-path": "../sebastian/diff" + }, + { + "name": "symfony/console", + "version": "v7.0.1", + "version_normalized": "7.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/console.git", + "reference": "cdce5c684b2f920bb1343deecdfba356ffad83d5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/console/zipball/cdce5c684b2f920bb1343deecdfba356ffad83d5", + "reference": "cdce5c684b2f920bb1343deecdfba356ffad83d5", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/polyfill-mbstring": "~1.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/string": "^6.4|^7.0" + }, + "conflict": { + "symfony/dependency-injection": "<6.4", + "symfony/dotenv": "<6.4", + "symfony/event-dispatcher": "<6.4", + "symfony/lock": "<6.4", + "symfony/process": "<6.4" + }, + "provide": { + "psr/log-implementation": "1.0|2.0|3.0" + }, + "require-dev": { + "psr/log": "^1|^2|^3", + "symfony/config": "^6.4|^7.0", + "symfony/dependency-injection": "^6.4|^7.0", + "symfony/event-dispatcher": "^6.4|^7.0", + "symfony/http-foundation": "^6.4|^7.0", + "symfony/http-kernel": "^6.4|^7.0", + "symfony/lock": "^6.4|^7.0", + "symfony/messenger": "^6.4|^7.0", + "symfony/process": "^6.4|^7.0", + "symfony/stopwatch": "^6.4|^7.0", + "symfony/var-dumper": "^6.4|^7.0" + }, + "time": "2023-12-01T15:10:06+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Console\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Eases the creation of beautiful and testable command line interfaces", + "homepage": "https://symfony.com", + "keywords": [ + "cli", + "command-line", + "console", + "terminal" + ], + "support": { + "source": "https://github.com/symfony/console/tree/v7.0.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/console" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v3.4.0", + "version_normalized": "3.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/7c3aff79d10325257a001fcf92d991f24fc967cf", + "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "time": "2023-05-23T14:45:45+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/deprecation-contracts" + }, + { + "name": "symfony/event-dispatcher", + "version": "v7.0.0", + "version_normalized": "7.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "c459b40ffe67c49af6fd392aac374c9edf8a027e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/c459b40ffe67c49af6fd392aac374c9edf8a027e", + "reference": "c459b40ffe67c49af6fd392aac374c9edf8a027e", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/event-dispatcher-contracts": "^2.5|^3" + }, + "conflict": { + "symfony/dependency-injection": "<6.4", + "symfony/service-contracts": "<2.5" + }, + "provide": { + "psr/event-dispatcher-implementation": "1.0", + "symfony/event-dispatcher-implementation": "2.0|3.0" + }, + "require-dev": { + "psr/log": "^1|^2|^3", + "symfony/config": "^6.4|^7.0", + "symfony/dependency-injection": "^6.4|^7.0", + "symfony/error-handler": "^6.4|^7.0", + "symfony/expression-language": "^6.4|^7.0", + "symfony/http-foundation": "^6.4|^7.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/stopwatch": "^6.4|^7.0" + }, + "time": "2023-07-27T16:29:09+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\EventDispatcher\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides tools that allow your application components to communicate with each other by dispatching events and listening to them", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/event-dispatcher/tree/v7.0.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/event-dispatcher" + }, + { + "name": "symfony/event-dispatcher-contracts", + "version": "v3.4.0", + "version_normalized": "3.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher-contracts.git", + "reference": "a76aed96a42d2b521153fb382d418e30d18b59df" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/a76aed96a42d2b521153fb382d418e30d18b59df", + "reference": "a76aed96a42d2b521153fb382d418e30d18b59df", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/event-dispatcher": "^1" + }, + "time": "2023-05-23T14:45:45+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Contracts\\EventDispatcher\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to dispatching event", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/event-dispatcher-contracts" + }, + { + "name": "symfony/filesystem", + "version": "v7.0.0", + "version_normalized": "7.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/filesystem.git", + "reference": "7da8ea2362a283771478c5f7729cfcb43a76b8b7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/7da8ea2362a283771478c5f7729cfcb43a76b8b7", + "reference": "7da8ea2362a283771478c5f7729cfcb43a76b8b7", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-mbstring": "~1.8" + }, + "time": "2023-07-27T06:33:22+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Filesystem\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides basic utilities for the filesystem", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/filesystem/tree/v7.0.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/filesystem" + }, + { + "name": "symfony/finder", + "version": "v7.0.0", + "version_normalized": "7.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/finder.git", + "reference": "6e5688d69f7cfc4ed4a511e96007e06c2d34ce56" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/finder/zipball/6e5688d69f7cfc4ed4a511e96007e06c2d34ce56", + "reference": "6e5688d69f7cfc4ed4a511e96007e06c2d34ce56", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "symfony/filesystem": "^6.4|^7.0" + }, + "time": "2023-10-31T17:59:56+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Finder\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Finds files and directories via an intuitive fluent interface", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/finder/tree/v7.0.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/finder" + }, + { + "name": "symfony/options-resolver", + "version": "v7.0.0", + "version_normalized": "7.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/options-resolver.git", + "reference": "700ff4096e346f54cb628ea650767c8130f1001f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/700ff4096e346f54cb628ea650767c8130f1001f", + "reference": "700ff4096e346f54cb628ea650767c8130f1001f", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/deprecation-contracts": "^2.5|^3" + }, + "time": "2023-08-08T10:20:21+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\OptionsResolver\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides an improved replacement for the array_replace PHP function", + "homepage": "https://symfony.com", + "keywords": [ + "config", + "configuration", + "options" + ], + "support": { + "source": "https://github.com/symfony/options-resolver/tree/v7.0.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/options-resolver" + }, + { + "name": "symfony/polyfill-ctype", + "version": "v1.28.0", + "version_normalized": "1.28.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-ctype.git", + "reference": "ea208ce43cbb04af6867b4fdddb1bdbf84cc28cb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/ea208ce43cbb04af6867b4fdddb1bdbf84cc28cb", + "reference": "ea208ce43cbb04af6867b4fdddb1bdbf84cc28cb", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-ctype": "*" + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "time": "2023-01-26T09:26:14+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Ctype\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for ctype functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "ctype", + "polyfill", + "portable" + ], + "support": { + "source": "https://github.com/symfony/polyfill-ctype/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-ctype" + }, + { + "name": "symfony/polyfill-intl-grapheme", + "version": "v1.28.0", + "version_normalized": "1.28.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-grapheme.git", + "reference": "875e90aeea2777b6f135677f618529449334a612" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/875e90aeea2777b6f135677f618529449334a612", + "reference": "875e90aeea2777b6f135677f618529449334a612", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "time": "2023-01-26T09:26:14+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Grapheme\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's grapheme_* functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "grapheme", + "intl", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-intl-grapheme" + }, + { + "name": "symfony/polyfill-intl-normalizer", + "version": "v1.28.0", + "version_normalized": "1.28.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-normalizer.git", + "reference": "8c4ad05dd0120b6a53c1ca374dca2ad0a1c4ed92" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/8c4ad05dd0120b6a53c1ca374dca2ad0a1c4ed92", + "reference": "8c4ad05dd0120b6a53c1ca374dca2ad0a1c4ed92", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "time": "2023-01-26T09:26:14+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Normalizer\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's Normalizer class and related functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "intl", + "normalizer", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-intl-normalizer" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.28.0", + "version_normalized": "1.28.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "42292d99c55abe617799667f454222c54c60e229" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/42292d99c55abe617799667f454222c54c60e229", + "reference": "42292d99c55abe617799667f454222c54c60e229", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-mbstring": "*" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "time": "2023-07-28T09:04:16+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-mbstring" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.28.0", + "version_normalized": "1.28.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/6caa57379c4aec19c0a12a38b59b26487dcfe4b5", + "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "time": "2023-01-26T09:26:14+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-php80" + }, + { + "name": "symfony/polyfill-php81", + "version": "v1.28.0", + "version_normalized": "1.28.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php81.git", + "reference": "7581cd600fa9fd681b797d00b02f068e2f13263b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php81/zipball/7581cd600fa9fd681b797d00b02f068e2f13263b", + "reference": "7581cd600fa9fd681b797d00b02f068e2f13263b", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "time": "2023-01-26T09:26:14+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php81\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php81/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-php81" + }, + { + "name": "symfony/process", + "version": "v7.0.0", + "version_normalized": "7.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/process.git", + "reference": "13bdb1670c7f510494e04fcb2bfa29af63db9c0d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/process/zipball/13bdb1670c7f510494e04fcb2bfa29af63db9c0d", + "reference": "13bdb1670c7f510494e04fcb2bfa29af63db9c0d", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "time": "2023-11-20T16:43:42+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Process\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Executes commands in sub-processes", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/process/tree/v7.0.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/process" + }, + { + "name": "symfony/service-contracts", + "version": "v3.4.0", + "version_normalized": "3.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/service-contracts.git", + "reference": "b3313c2dbffaf71c8de2934e2ea56ed2291a3838" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/b3313c2dbffaf71c8de2934e2ea56ed2291a3838", + "reference": "b3313c2dbffaf71c8de2934e2ea56ed2291a3838", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/container": "^2.0" + }, + "conflict": { + "ext-psr": "<1.1|>=2" + }, + "time": "2023-07-30T20:28:31+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Contracts\\Service\\": "" + }, + "exclude-from-classmap": [ + "/Test/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to writing services", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/service-contracts/tree/v3.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/service-contracts" + }, + { + "name": "symfony/stopwatch", + "version": "v7.0.0", + "version_normalized": "7.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/stopwatch.git", + "reference": "7bbfa3dd564a0ce12eb4acaaa46823c740f9cb7a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/stopwatch/zipball/7bbfa3dd564a0ce12eb4acaaa46823c740f9cb7a", + "reference": "7bbfa3dd564a0ce12eb4acaaa46823c740f9cb7a", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/service-contracts": "^2.5|^3" + }, + "time": "2023-07-05T13:06:06+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Stopwatch\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides a way to profile code", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/stopwatch/tree/v7.0.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/stopwatch" + }, + { + "name": "symfony/string", + "version": "v7.0.0", + "version_normalized": "7.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/string.git", + "reference": "92bd2bfbba476d4a1838e5e12168bef2fd1e6620" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/string/zipball/92bd2bfbba476d4a1838e5e12168bef2fd1e6620", + "reference": "92bd2bfbba476d4a1838e5e12168bef2fd1e6620", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-intl-grapheme": "~1.0", + "symfony/polyfill-intl-normalizer": "~1.0", + "symfony/polyfill-mbstring": "~1.0" + }, + "conflict": { + "symfony/translation-contracts": "<2.5" + }, + "require-dev": { + "symfony/error-handler": "^6.4|^7.0", + "symfony/http-client": "^6.4|^7.0", + "symfony/intl": "^6.4|^7.0", + "symfony/translation-contracts": "^2.5|^3.0", + "symfony/var-exporter": "^6.4|^7.0" + }, + "time": "2023-11-29T08:40:23+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "Resources/functions.php" + ], + "psr-4": { + "Symfony\\Component\\String\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way", + "homepage": "https://symfony.com", + "keywords": [ + "grapheme", + "i18n", + "string", + "unicode", + "utf-8", + "utf8" + ], + "support": { + "source": "https://github.com/symfony/string/tree/v7.0.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/string" + } + ], + "dev": true, + "dev-package-names": [] +} diff --git a/tools/php-cs-fixer/vendor/composer/installed.php b/tools/php-cs-fixer/vendor/composer/installed.php new file mode 100644 index 00000000..73ecf15b --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/installed.php @@ -0,0 +1,266 @@ + array( + 'pretty_version' => 'dev-main', + 'version' => 'dev-main', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'reference' => '98028bded195634cac191342b95a7b516c59edae', + 'name' => '__root__', + 'dev' => true, + ), + 'versions' => array( + '__root__' => array( + 'pretty_version' => 'dev-main', + 'version' => 'dev-main', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'reference' => '98028bded195634cac191342b95a7b516c59edae', + 'dev_requirement' => false, + ), + 'composer/pcre' => array( + 'pretty_version' => '3.1.1', + 'version' => '3.1.1.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/./pcre', + 'aliases' => array(), + 'reference' => '00104306927c7a0919b4ced2aaa6782c1e61a3c9', + 'dev_requirement' => false, + ), + 'composer/semver' => array( + 'pretty_version' => '3.4.0', + 'version' => '3.4.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/./semver', + 'aliases' => array(), + 'reference' => '35e8d0af4486141bc745f23a29cc2091eb624a32', + 'dev_requirement' => false, + ), + 'composer/xdebug-handler' => array( + 'pretty_version' => '3.0.3', + 'version' => '3.0.3.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/./xdebug-handler', + 'aliases' => array(), + 'reference' => 'ced299686f41dce890debac69273b47ffe98a40c', + 'dev_requirement' => false, + ), + 'friendsofphp/php-cs-fixer' => array( + 'pretty_version' => 'v3.40.2', + 'version' => '3.40.2.0', + 'type' => 'application', + 'install_path' => __DIR__ . '/../friendsofphp/php-cs-fixer', + 'aliases' => array(), + 'reference' => '4344562a516b76afe8f2d64b2e52214c30d64ed8', + 'dev_requirement' => false, + ), + 'psr/container' => array( + 'pretty_version' => '2.0.2', + 'version' => '2.0.2.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/container', + 'aliases' => array(), + 'reference' => 'c71ecc56dfe541dbd90c5360474fbc405f8d5963', + 'dev_requirement' => false, + ), + 'psr/event-dispatcher' => array( + 'pretty_version' => '1.0.0', + 'version' => '1.0.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/event-dispatcher', + 'aliases' => array(), + 'reference' => 'dbefd12671e8a14ec7f180cab83036ed26714bb0', + 'dev_requirement' => false, + ), + 'psr/event-dispatcher-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'psr/log' => array( + 'pretty_version' => '3.0.0', + 'version' => '3.0.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/log', + 'aliases' => array(), + 'reference' => 'fe5ea303b0887d5caefd3d431c3e61ad47037001', + 'dev_requirement' => false, + ), + 'psr/log-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0|2.0|3.0', + ), + ), + 'sebastian/diff' => array( + 'pretty_version' => '5.0.3', + 'version' => '5.0.3.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../sebastian/diff', + 'aliases' => array(), + 'reference' => '912dc2fbe3e3c1e7873313cc801b100b6c68c87b', + 'dev_requirement' => false, + ), + 'symfony/console' => array( + 'pretty_version' => 'v7.0.1', + 'version' => '7.0.1.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/console', + 'aliases' => array(), + 'reference' => 'cdce5c684b2f920bb1343deecdfba356ffad83d5', + 'dev_requirement' => false, + ), + 'symfony/deprecation-contracts' => array( + 'pretty_version' => 'v3.4.0', + 'version' => '3.4.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/deprecation-contracts', + 'aliases' => array(), + 'reference' => '7c3aff79d10325257a001fcf92d991f24fc967cf', + 'dev_requirement' => false, + ), + 'symfony/event-dispatcher' => array( + 'pretty_version' => 'v7.0.0', + 'version' => '7.0.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/event-dispatcher', + 'aliases' => array(), + 'reference' => 'c459b40ffe67c49af6fd392aac374c9edf8a027e', + 'dev_requirement' => false, + ), + 'symfony/event-dispatcher-contracts' => array( + 'pretty_version' => 'v3.4.0', + 'version' => '3.4.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/event-dispatcher-contracts', + 'aliases' => array(), + 'reference' => 'a76aed96a42d2b521153fb382d418e30d18b59df', + 'dev_requirement' => false, + ), + 'symfony/event-dispatcher-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '2.0|3.0', + ), + ), + 'symfony/filesystem' => array( + 'pretty_version' => 'v7.0.0', + 'version' => '7.0.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/filesystem', + 'aliases' => array(), + 'reference' => '7da8ea2362a283771478c5f7729cfcb43a76b8b7', + 'dev_requirement' => false, + ), + 'symfony/finder' => array( + 'pretty_version' => 'v7.0.0', + 'version' => '7.0.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/finder', + 'aliases' => array(), + 'reference' => '6e5688d69f7cfc4ed4a511e96007e06c2d34ce56', + 'dev_requirement' => false, + ), + 'symfony/options-resolver' => array( + 'pretty_version' => 'v7.0.0', + 'version' => '7.0.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/options-resolver', + 'aliases' => array(), + 'reference' => '700ff4096e346f54cb628ea650767c8130f1001f', + 'dev_requirement' => false, + ), + 'symfony/polyfill-ctype' => array( + 'pretty_version' => 'v1.28.0', + 'version' => '1.28.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-ctype', + 'aliases' => array(), + 'reference' => 'ea208ce43cbb04af6867b4fdddb1bdbf84cc28cb', + 'dev_requirement' => false, + ), + 'symfony/polyfill-intl-grapheme' => array( + 'pretty_version' => 'v1.28.0', + 'version' => '1.28.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-intl-grapheme', + 'aliases' => array(), + 'reference' => '875e90aeea2777b6f135677f618529449334a612', + 'dev_requirement' => false, + ), + 'symfony/polyfill-intl-normalizer' => array( + 'pretty_version' => 'v1.28.0', + 'version' => '1.28.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-intl-normalizer', + 'aliases' => array(), + 'reference' => '8c4ad05dd0120b6a53c1ca374dca2ad0a1c4ed92', + 'dev_requirement' => false, + ), + 'symfony/polyfill-mbstring' => array( + 'pretty_version' => 'v1.28.0', + 'version' => '1.28.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-mbstring', + 'aliases' => array(), + 'reference' => '42292d99c55abe617799667f454222c54c60e229', + 'dev_requirement' => false, + ), + 'symfony/polyfill-php80' => array( + 'pretty_version' => 'v1.28.0', + 'version' => '1.28.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-php80', + 'aliases' => array(), + 'reference' => '6caa57379c4aec19c0a12a38b59b26487dcfe4b5', + 'dev_requirement' => false, + ), + 'symfony/polyfill-php81' => array( + 'pretty_version' => 'v1.28.0', + 'version' => '1.28.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-php81', + 'aliases' => array(), + 'reference' => '7581cd600fa9fd681b797d00b02f068e2f13263b', + 'dev_requirement' => false, + ), + 'symfony/process' => array( + 'pretty_version' => 'v7.0.0', + 'version' => '7.0.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/process', + 'aliases' => array(), + 'reference' => '13bdb1670c7f510494e04fcb2bfa29af63db9c0d', + 'dev_requirement' => false, + ), + 'symfony/service-contracts' => array( + 'pretty_version' => 'v3.4.0', + 'version' => '3.4.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/service-contracts', + 'aliases' => array(), + 'reference' => 'b3313c2dbffaf71c8de2934e2ea56ed2291a3838', + 'dev_requirement' => false, + ), + 'symfony/stopwatch' => array( + 'pretty_version' => 'v7.0.0', + 'version' => '7.0.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/stopwatch', + 'aliases' => array(), + 'reference' => '7bbfa3dd564a0ce12eb4acaaa46823c740f9cb7a', + 'dev_requirement' => false, + ), + 'symfony/string' => array( + 'pretty_version' => 'v7.0.0', + 'version' => '7.0.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/string', + 'aliases' => array(), + 'reference' => '92bd2bfbba476d4a1838e5e12168bef2fd1e6620', + 'dev_requirement' => false, + ), + ), +); diff --git a/tools/php-cs-fixer/vendor/composer/pcre/LICENSE b/tools/php-cs-fixer/vendor/composer/pcre/LICENSE new file mode 100644 index 00000000..c5a282ff --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/pcre/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2021 Composer + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/composer/pcre/README.md b/tools/php-cs-fixer/vendor/composer/pcre/README.md new file mode 100644 index 00000000..973b17d8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/pcre/README.md @@ -0,0 +1,181 @@ +composer/pcre +============= + +PCRE wrapping library that offers type-safe `preg_*` replacements. + +This library gives you a way to ensure `preg_*` functions do not fail silently, returning +unexpected `null`s that may not be handled. + +As of 3.0 this library enforces [`PREG_UNMATCHED_AS_NULL`](#preg_unmatched_as_null) usage +for all matching and replaceCallback functions, [read more below](#preg_unmatched_as_null) +to understand the implications. + +It thus makes it easier to work with static analysis tools like PHPStan or Psalm as it +simplifies and reduces the possible return values from all the `preg_*` functions which +are quite packed with edge cases. + +This library is a thin wrapper around `preg_*` functions with [some limitations](#restrictions--limitations). +If you are looking for a richer API to handle regular expressions have a look at +[rawr/t-regx](https://packagist.org/packages/rawr/t-regx) instead. + +[![Continuous Integration](https://github.com/composer/pcre/workflows/Continuous%20Integration/badge.svg?branch=main)](https://github.com/composer/pcre/actions) + + +Installation +------------ + +Install the latest version with: + +```bash +$ composer require composer/pcre +``` + + +Requirements +------------ + +* PHP 7.4.0 is required for 3.x versions +* PHP 7.2.0 is required for 2.x versions +* PHP 5.3.2 is required for 1.x versions + + +Basic usage +----------- + +Instead of: + +```php +if (preg_match('{fo+}', $string, $matches)) { ... } +if (preg_match('{fo+}', $string, $matches, PREG_OFFSET_CAPTURE)) { ... } +if (preg_match_all('{fo+}', $string, $matches)) { ... } +$newString = preg_replace('{fo+}', 'bar', $string); +$newString = preg_replace_callback('{fo+}', function ($match) { return strtoupper($match[0]); }, $string); +$newString = preg_replace_callback_array(['{fo+}' => fn ($match) => strtoupper($match[0])], $string); +$filtered = preg_grep('{[a-z]}', $elements); +$array = preg_split('{[a-z]+}', $string); +``` + +You can now call these on the `Preg` class: + +```php +use Composer\Pcre\Preg; + +if (Preg::match('{fo+}', $string, $matches)) { ... } +if (Preg::matchWithOffsets('{fo+}', $string, $matches)) { ... } +if (Preg::matchAll('{fo+}', $string, $matches)) { ... } +$newString = Preg::replace('{fo+}', 'bar', $string); +$newString = Preg::replaceCallback('{fo+}', function ($match) { return strtoupper($match[0]); }, $string); +$newString = Preg::replaceCallbackArray(['{fo+}' => fn ($match) => strtoupper($match[0])], $string); +$filtered = Preg::grep('{[a-z]}', $elements); +$array = Preg::split('{[a-z]+}', $string); +``` + +The main difference is if anything fails to match/replace/.., it will throw a `Composer\Pcre\PcreException` +instead of returning `null` (or false in some cases), so you can now use the return values safely relying on +the fact that they can only be strings (for replace), ints (for match) or arrays (for grep/split). + +Additionally the `Preg` class provides match methods that return `bool` rather than `int`, for stricter type safety +when the number of pattern matches is not useful: + +```php +use Composer\Pcre\Preg; + +if (Preg::isMatch('{fo+}', $string, $matches)) // bool +if (Preg::isMatchAll('{fo+}', $string, $matches)) // bool +``` + +Finally the `Preg` class provides a few `*StrictGroups` method variants that ensure match groups +are always present and thus non-nullable, making it easier to write type-safe code: + +```php +use Composer\Pcre\Preg; + +// $matches is guaranteed to be an array of strings, if a subpattern does not match and produces a null it will throw +if (Preg::matchStrictGroups('{fo+}', $string, $matches)) +if (Preg::matchAllStrictGroups('{fo+}', $string, $matches)) +``` + +**Note:** This is generally safe to use as long as you do not have optional subpatterns (i.e. `(something)?` +or `(something)*` or branches with a `|` that result in some groups not being matched at all). +A subpattern that can match an empty string like `(.*)` is **not** optional, it will be present as an +empty string in the matches. A non-matching subpattern, even if optional like `(?:foo)?` will anyway not be present in +matches so it is also not a problem to use these with `*StrictGroups` methods. + +If you would prefer a slightly more verbose usage, replacing by-ref arguments by result objects, you can use the `Regex` class: + +```php +use Composer\Pcre\Regex; + +// this is useful when you are just interested in knowing if something matched +// as it returns a bool instead of int(1/0) for match +$bool = Regex::isMatch('{fo+}', $string); + +$result = Regex::match('{fo+}', $string); +if ($result->matched) { something($result->matches); } + +$result = Regex::matchWithOffsets('{fo+}', $string); +if ($result->matched) { something($result->matches); } + +$result = Regex::matchAll('{fo+}', $string); +if ($result->matched && $result->count > 3) { something($result->matches); } + +$newString = Regex::replace('{fo+}', 'bar', $string)->result; +$newString = Regex::replaceCallback('{fo+}', function ($match) { return strtoupper($match[0]); }, $string)->result; +$newString = Regex::replaceCallbackArray(['{fo+}' => fn ($match) => strtoupper($match[0])], $string)->result; +``` + +Note that `preg_grep` and `preg_split` are only callable via the `Preg` class as they do not have +complex return types warranting a specific result object. + +See the [MatchResult](src/MatchResult.php), [MatchWithOffsetsResult](src/MatchWithOffsetsResult.php), [MatchAllResult](src/MatchAllResult.php), +[MatchAllWithOffsetsResult](src/MatchAllWithOffsetsResult.php), and [ReplaceResult](src/ReplaceResult.php) class sources for more details. + +Restrictions / Limitations +-------------------------- + +Due to type safety requirements a few restrictions are in place. + +- matching using `PREG_OFFSET_CAPTURE` is made available via `matchWithOffsets` and `matchAllWithOffsets`. + You cannot pass the flag to `match`/`matchAll`. +- `Preg::split` will also reject `PREG_SPLIT_OFFSET_CAPTURE` and you should use `splitWithOffsets` + instead. +- `matchAll` rejects `PREG_SET_ORDER` as it also changes the shape of the returned matches. There + is no alternative provided as you can fairly easily code around it. +- `preg_filter` is not supported as it has a rather crazy API, most likely you should rather + use `Preg::grep` in combination with some loop and `Preg::replace`. +- `replace`, `replaceCallback` and `replaceCallbackArray` do not support an array `$subject`, + only simple strings. +- As of 2.0, the library always uses `PREG_UNMATCHED_AS_NULL` for matching, which offers [much + saner/more predictable results](#preg_unmatched_as_null). As of 3.0 the flag is also set for + `replaceCallback` and `replaceCallbackArray`. + +#### PREG_UNMATCHED_AS_NULL + +As of 2.0, this library always uses PREG_UNMATCHED_AS_NULL for all `match*` and `isMatch*` +functions. As of 3.0 it is also done for `replaceCallback` and `replaceCallbackArray`. + +This means your matches will always contain all matching groups, either as null if unmatched +or as string if it matched. + +The advantages in clarity and predictability are clearer if you compare the two outputs of +running this with and without PREG_UNMATCHED_AS_NULL in $flags: + +```php +preg_match('/(a)(b)*(c)(d)*/', 'ac', $matches, $flags); +``` + +| no flag | PREG_UNMATCHED_AS_NULL | +| --- | --- | +| array (size=4) | array (size=5) | +| 0 => string 'ac' (length=2) | 0 => string 'ac' (length=2) | +| 1 => string 'a' (length=1) | 1 => string 'a' (length=1) | +| 2 => string '' (length=0) | 2 => null | +| 3 => string 'c' (length=1) | 3 => string 'c' (length=1) | +| | 4 => null | +| group 2 (any unmatched group preceding one that matched) is set to `''`. You cannot tell if it matched an empty string or did not match at all | group 2 is `null` when unmatched and a string if it matched, easy to check for | +| group 4 (any optional group without a matching one following) is missing altogether. So you have to check with `isset()`, but really you want `isset($m[4]) && $m[4] !== ''` for safety unless you are very careful to check that a non-optional group follows it | group 4 is always set, and null in this case as there was no match, easy to check for with `$m[4] !== null` | + +License +------- + +composer/pcre is licensed under the MIT License, see the LICENSE file for details. diff --git a/tools/php-cs-fixer/vendor/composer/pcre/composer.json b/tools/php-cs-fixer/vendor/composer/pcre/composer.json new file mode 100644 index 00000000..40477ff4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/pcre/composer.json @@ -0,0 +1,46 @@ +{ + "name": "composer/pcre", + "description": "PCRE wrapping library that offers type-safe preg_* replacements.", + "type": "library", + "license": "MIT", + "keywords": [ + "pcre", + "regex", + "preg", + "regular expression" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + } + ], + "require": { + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "symfony/phpunit-bridge": "^5", + "phpstan/phpstan": "^1.3", + "phpstan/phpstan-strict-rules": "^1.1" + }, + "autoload": { + "psr-4": { + "Composer\\Pcre\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "Composer\\Pcre\\": "tests" + } + }, + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "scripts": { + "test": "vendor/bin/simple-phpunit", + "phpstan": "phpstan analyse" + } +} diff --git a/tools/php-cs-fixer/vendor/composer/pcre/src/MatchAllResult.php b/tools/php-cs-fixer/vendor/composer/pcre/src/MatchAllResult.php new file mode 100644 index 00000000..4310c536 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/pcre/src/MatchAllResult.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +final class MatchAllResult +{ + /** + * An array of match group => list of matched strings + * + * @readonly + * @var array> + */ + public $matches; + + /** + * @readonly + * @var 0|positive-int + */ + public $count; + + /** + * @readonly + * @var bool + */ + public $matched; + + /** + * @param 0|positive-int $count + * @param array> $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + $this->count = $count; + } +} diff --git a/tools/php-cs-fixer/vendor/composer/pcre/src/MatchAllStrictGroupsResult.php b/tools/php-cs-fixer/vendor/composer/pcre/src/MatchAllStrictGroupsResult.php new file mode 100644 index 00000000..69dcd062 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/pcre/src/MatchAllStrictGroupsResult.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +final class MatchAllStrictGroupsResult +{ + /** + * An array of match group => list of matched strings + * + * @readonly + * @var array> + */ + public $matches; + + /** + * @readonly + * @var 0|positive-int + */ + public $count; + + /** + * @readonly + * @var bool + */ + public $matched; + + /** + * @param 0|positive-int $count + * @param array> $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + $this->count = $count; + } +} diff --git a/tools/php-cs-fixer/vendor/composer/pcre/src/MatchAllWithOffsetsResult.php b/tools/php-cs-fixer/vendor/composer/pcre/src/MatchAllWithOffsetsResult.php new file mode 100644 index 00000000..032a02cd --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/pcre/src/MatchAllWithOffsetsResult.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +final class MatchAllWithOffsetsResult +{ + /** + * An array of match group => list of matches, every match being a pair of string matched + offset in bytes (or -1 if no match) + * + * @readonly + * @var array> + * @phpstan-var array}>> + */ + public $matches; + + /** + * @readonly + * @var 0|positive-int + */ + public $count; + + /** + * @readonly + * @var bool + */ + public $matched; + + /** + * @param 0|positive-int $count + * @param array> $matches + * @phpstan-param array}>> $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + $this->count = $count; + } +} diff --git a/tools/php-cs-fixer/vendor/composer/pcre/src/MatchResult.php b/tools/php-cs-fixer/vendor/composer/pcre/src/MatchResult.php new file mode 100644 index 00000000..e951a5ee --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/pcre/src/MatchResult.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +final class MatchResult +{ + /** + * An array of match group => string matched + * + * @readonly + * @var array + */ + public $matches; + + /** + * @readonly + * @var bool + */ + public $matched; + + /** + * @param 0|positive-int $count + * @param array $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + } +} diff --git a/tools/php-cs-fixer/vendor/composer/pcre/src/MatchStrictGroupsResult.php b/tools/php-cs-fixer/vendor/composer/pcre/src/MatchStrictGroupsResult.php new file mode 100644 index 00000000..126ee629 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/pcre/src/MatchStrictGroupsResult.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +final class MatchStrictGroupsResult +{ + /** + * An array of match group => string matched + * + * @readonly + * @var array + */ + public $matches; + + /** + * @readonly + * @var bool + */ + public $matched; + + /** + * @param 0|positive-int $count + * @param array $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + } +} diff --git a/tools/php-cs-fixer/vendor/composer/pcre/src/MatchWithOffsetsResult.php b/tools/php-cs-fixer/vendor/composer/pcre/src/MatchWithOffsetsResult.php new file mode 100644 index 00000000..ba4d4bc4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/pcre/src/MatchWithOffsetsResult.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +final class MatchWithOffsetsResult +{ + /** + * An array of match group => pair of string matched + offset in bytes (or -1 if no match) + * + * @readonly + * @var array + * @phpstan-var array}> + */ + public $matches; + + /** + * @readonly + * @var bool + */ + public $matched; + + /** + * @param 0|positive-int $count + * @param array $matches + * @phpstan-param array}> $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + } +} diff --git a/tools/php-cs-fixer/vendor/composer/pcre/src/PcreException.php b/tools/php-cs-fixer/vendor/composer/pcre/src/PcreException.php new file mode 100644 index 00000000..218b2f2d --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/pcre/src/PcreException.php @@ -0,0 +1,60 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +class PcreException extends \RuntimeException +{ + /** + * @param string $function + * @param string|string[] $pattern + * @return self + */ + public static function fromFunction($function, $pattern) + { + $code = preg_last_error(); + + if (is_array($pattern)) { + $pattern = implode(', ', $pattern); + } + + return new PcreException($function.'(): failed executing "'.$pattern.'": '.self::pcreLastErrorMessage($code), $code); + } + + /** + * @param int $code + * @return string + */ + private static function pcreLastErrorMessage($code) + { + if (function_exists('preg_last_error_msg')) { + return preg_last_error_msg(); + } + + // older php versions did not set the code properly in all cases + if (PHP_VERSION_ID < 70201 && $code === 0) { + return 'UNDEFINED_ERROR'; + } + + $constants = get_defined_constants(true); + if (!isset($constants['pcre'])) { + return 'UNDEFINED_ERROR'; + } + + foreach ($constants['pcre'] as $const => $val) { + if ($val === $code && substr($const, -6) === '_ERROR') { + return $const; + } + } + + return 'UNDEFINED_ERROR'; + } +} diff --git a/tools/php-cs-fixer/vendor/composer/pcre/src/Preg.php b/tools/php-cs-fixer/vendor/composer/pcre/src/Preg.php new file mode 100644 index 00000000..6fe01722 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/pcre/src/Preg.php @@ -0,0 +1,428 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +class Preg +{ + /** @internal */ + public const ARRAY_MSG = '$subject as an array is not supported. You can use \'foreach\' instead.'; + /** @internal */ + public const INVALID_TYPE_MSG = '$subject must be a string, %s given.'; + + /** + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @return 0|1 + * + * @param-out array $matches + */ + public static function match(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int + { + self::checkOffsetCapture($flags, 'matchWithOffsets'); + + $result = preg_match($pattern, $subject, $matches, $flags | PREG_UNMATCHED_AS_NULL, $offset); + if ($result === false) { + throw PcreException::fromFunction('preg_match', $pattern); + } + + return $result; + } + + /** + * Variant of `match()` which outputs non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @return 0|1 + * @throws UnexpectedNullMatchException + * + * @param-out array $matches + */ + public static function matchStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int + { + $result = self::match($pattern, $subject, $matchesInternal, $flags, $offset); + $matches = self::enforceNonNullMatches($pattern, $matchesInternal, 'match'); + + return $result; + } + + /** + * Runs preg_match with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL and PREG_OFFSET_CAPTURE are always set, no other flags are supported + * @return 0|1 + * + * @param-out array}> $matches + */ + public static function matchWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0): int + { + $result = preg_match($pattern, $subject, $matches, $flags | PREG_UNMATCHED_AS_NULL | PREG_OFFSET_CAPTURE, $offset); + if ($result === false) { + throw PcreException::fromFunction('preg_match', $pattern); + } + + return $result; + } + + /** + * @param non-empty-string $pattern + * @param array> $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @return 0|positive-int + * + * @param-out array> $matches + */ + public static function matchAll(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int + { + self::checkOffsetCapture($flags, 'matchAllWithOffsets'); + self::checkSetOrder($flags); + + $result = preg_match_all($pattern, $subject, $matches, $flags | PREG_UNMATCHED_AS_NULL, $offset); + if (!is_int($result)) { // PHP < 8 may return null, 8+ returns int|false + throw PcreException::fromFunction('preg_match_all', $pattern); + } + + return $result; + } + + /** + * Variant of `match()` which outputs non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param array> $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @return 0|positive-int + * @throws UnexpectedNullMatchException + * + * @param-out array> $matches + */ + public static function matchAllStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int + { + $result = self::matchAll($pattern, $subject, $matchesInternal, $flags, $offset); + $matches = self::enforceNonNullMatchAll($pattern, $matchesInternal, 'matchAll'); + + return $result; + } + + /** + * Runs preg_match_all with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param array> $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL and PREG_MATCH_OFFSET are always set, no other flags are supported + * @return 0|positive-int + * + * @param-out array}>> $matches + */ + public static function matchAllWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0): int + { + self::checkSetOrder($flags); + + $result = preg_match_all($pattern, $subject, $matches, $flags | PREG_UNMATCHED_AS_NULL | PREG_OFFSET_CAPTURE, $offset); + if (!is_int($result)) { // PHP < 8 may return null, 8+ returns int|false + throw PcreException::fromFunction('preg_match_all', $pattern); + } + + return $result; + } + + /** + * @param string|string[] $pattern + * @param string|string[] $replacement + * @param string $subject + * @param int $count Set by method + * + * @param-out int<0, max> $count + */ + public static function replace($pattern, $replacement, $subject, int $limit = -1, int &$count = null): string + { + if (!is_scalar($subject)) { + if (is_array($subject)) { + throw new \InvalidArgumentException(static::ARRAY_MSG); + } + + throw new \TypeError(sprintf(static::INVALID_TYPE_MSG, gettype($subject))); + } + + $result = preg_replace($pattern, $replacement, $subject, $limit, $count); + if ($result === null) { + throw PcreException::fromFunction('preg_replace', $pattern); + } + + return $result; + } + + /** + * @param string|string[] $pattern + * @param callable(array): string $replacement + * @param string $subject + * @param int $count Set by method + * @param int-mask $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set + * + * @param-out int<0, max> $count + */ + public static function replaceCallback($pattern, callable $replacement, $subject, int $limit = -1, int &$count = null, int $flags = 0): string + { + if (!is_scalar($subject)) { + if (is_array($subject)) { + throw new \InvalidArgumentException(static::ARRAY_MSG); + } + + throw new \TypeError(sprintf(static::INVALID_TYPE_MSG, gettype($subject))); + } + + $result = preg_replace_callback($pattern, $replacement, $subject, $limit, $count, $flags | PREG_UNMATCHED_AS_NULL); + if ($result === null) { + throw PcreException::fromFunction('preg_replace_callback', $pattern); + } + + return $result; + } + + /** + * Variant of `replaceCallback()` which outputs non-null matches (or throws) + * + * @param string $pattern + * @param callable(array): string $replacement + * @param string $subject + * @param int $count Set by method + * @param int-mask $flags PREG_OFFSET_CAPTURE or PREG_UNMATCHED_AS_NULL, only available on PHP 7.4+ + * + * @param-out int<0, max> $count + */ + public static function replaceCallbackStrictGroups(string $pattern, callable $replacement, $subject, int $limit = -1, int &$count = null, int $flags = 0): string + { + return self::replaceCallback($pattern, function (array $matches) use ($pattern, $replacement) { + return $replacement(self::enforceNonNullMatches($pattern, $matches, 'replaceCallback')); + }, $subject, $limit, $count, $flags); + } + + /** + * @param array): string> $pattern + * @param string $subject + * @param int $count Set by method + * @param int-mask $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set + * + * @param-out int<0, max> $count + */ + public static function replaceCallbackArray(array $pattern, $subject, int $limit = -1, int &$count = null, int $flags = 0): string + { + if (!is_scalar($subject)) { + if (is_array($subject)) { + throw new \InvalidArgumentException(static::ARRAY_MSG); + } + + throw new \TypeError(sprintf(static::INVALID_TYPE_MSG, gettype($subject))); + } + + $result = preg_replace_callback_array($pattern, $subject, $limit, $count, $flags | PREG_UNMATCHED_AS_NULL); + if ($result === null) { + $pattern = array_keys($pattern); + throw PcreException::fromFunction('preg_replace_callback_array', $pattern); + } + + return $result; + } + + /** + * @param int-mask $flags PREG_SPLIT_NO_EMPTY or PREG_SPLIT_DELIM_CAPTURE + * @return list + */ + public static function split(string $pattern, string $subject, int $limit = -1, int $flags = 0): array + { + if (($flags & PREG_SPLIT_OFFSET_CAPTURE) !== 0) { + throw new \InvalidArgumentException('PREG_SPLIT_OFFSET_CAPTURE is not supported as it changes the type of $matches, use splitWithOffsets() instead'); + } + + $result = preg_split($pattern, $subject, $limit, $flags); + if ($result === false) { + throw PcreException::fromFunction('preg_split', $pattern); + } + + return $result; + } + + /** + * @param int-mask $flags PREG_SPLIT_NO_EMPTY or PREG_SPLIT_DELIM_CAPTURE, PREG_SPLIT_OFFSET_CAPTURE is always set + * @return list + * @phpstan-return list}> + */ + public static function splitWithOffsets(string $pattern, string $subject, int $limit = -1, int $flags = 0): array + { + $result = preg_split($pattern, $subject, $limit, $flags | PREG_SPLIT_OFFSET_CAPTURE); + if ($result === false) { + throw PcreException::fromFunction('preg_split', $pattern); + } + + return $result; + } + + /** + * @template T of string|\Stringable + * @param string $pattern + * @param array $array + * @param int-mask $flags PREG_GREP_INVERT + * @return array + */ + public static function grep(string $pattern, array $array, int $flags = 0): array + { + $result = preg_grep($pattern, $array, $flags); + if ($result === false) { + throw PcreException::fromFunction('preg_grep', $pattern); + } + + return $result; + } + + /** + * Variant of match() which returns a bool instead of int + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * + * @param-out array $matches + */ + public static function isMatch(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): bool + { + return (bool) static::match($pattern, $subject, $matches, $flags, $offset); + } + + /** + * Variant of `isMatch()` which outputs non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @throws UnexpectedNullMatchException + * + * @param-out array $matches + */ + public static function isMatchStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): bool + { + return (bool) self::matchStrictGroups($pattern, $subject, $matches, $flags, $offset); + } + + /** + * Variant of matchAll() which returns a bool instead of int + * + * @param non-empty-string $pattern + * @param array> $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * + * @param-out array> $matches + */ + public static function isMatchAll(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): bool + { + return (bool) static::matchAll($pattern, $subject, $matches, $flags, $offset); + } + + /** + * Variant of `isMatchAll()` which outputs non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param array> $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * + * @param-out array> $matches + */ + public static function isMatchAllStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): bool + { + return (bool) self::matchAllStrictGroups($pattern, $subject, $matches, $flags, $offset); + } + + /** + * Variant of matchWithOffsets() which returns a bool instead of int + * + * Runs preg_match with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * + * @param-out array}> $matches + */ + public static function isMatchWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0): bool + { + return (bool) static::matchWithOffsets($pattern, $subject, $matches, $flags, $offset); + } + + /** + * Variant of matchAllWithOffsets() which returns a bool instead of int + * + * Runs preg_match_all with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param array> $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * + * @param-out array}>> $matches + */ + public static function isMatchAllWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0): bool + { + return (bool) static::matchAllWithOffsets($pattern, $subject, $matches, $flags, $offset); + } + + private static function checkOffsetCapture(int $flags, string $useFunctionName): void + { + if (($flags & PREG_OFFSET_CAPTURE) !== 0) { + throw new \InvalidArgumentException('PREG_OFFSET_CAPTURE is not supported as it changes the type of $matches, use ' . $useFunctionName . '() instead'); + } + } + + private static function checkSetOrder(int $flags): void + { + if (($flags & PREG_SET_ORDER) !== 0) { + throw new \InvalidArgumentException('PREG_SET_ORDER is not supported as it changes the type of $matches'); + } + } + + /** + * @param array $matches + * @return array + * @throws UnexpectedNullMatchException + */ + private static function enforceNonNullMatches(string $pattern, array $matches, string $variantMethod) + { + foreach ($matches as $group => $match) { + if (null === $match) { + throw new UnexpectedNullMatchException('Pattern "'.$pattern.'" had an unexpected unmatched group "'.$group.'", make sure the pattern always matches or use '.$variantMethod.'() instead.'); + } + } + + /** @var array */ + return $matches; + } + + /** + * @param array> $matches + * @return array> + * @throws UnexpectedNullMatchException + */ + private static function enforceNonNullMatchAll(string $pattern, array $matches, string $variantMethod) + { + foreach ($matches as $group => $groupMatches) { + foreach ($groupMatches as $match) { + if (null === $match) { + throw new UnexpectedNullMatchException('Pattern "'.$pattern.'" had an unexpected unmatched group "'.$group.'", make sure the pattern always matches or use '.$variantMethod.'() instead.'); + } + } + } + + /** @var array> */ + return $matches; + } +} diff --git a/tools/php-cs-fixer/vendor/composer/pcre/src/Regex.php b/tools/php-cs-fixer/vendor/composer/pcre/src/Regex.php new file mode 100644 index 00000000..112fa325 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/pcre/src/Regex.php @@ -0,0 +1,174 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +class Regex +{ + /** + * @param non-empty-string $pattern + */ + public static function isMatch(string $pattern, string $subject, int $offset = 0): bool + { + return (bool) Preg::match($pattern, $subject, $matches, 0, $offset); + } + + /** + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + */ + public static function match(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchResult + { + self::checkOffsetCapture($flags, 'matchWithOffsets'); + + $count = Preg::match($pattern, $subject, $matches, $flags, $offset); + + return new MatchResult($count, $matches); + } + + /** + * Variant of `match()` which returns non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @throws UnexpectedNullMatchException + */ + public static function matchStrictGroups(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchStrictGroupsResult + { + $count = Preg::matchStrictGroups($pattern, $subject, $matches, $flags, $offset); + + return new MatchStrictGroupsResult($count, $matches); + } + + /** + * Runs preg_match with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL and PREG_MATCH_OFFSET are always set, no other flags are supported + */ + public static function matchWithOffsets(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchWithOffsetsResult + { + $count = Preg::matchWithOffsets($pattern, $subject, $matches, $flags, $offset); + + return new MatchWithOffsetsResult($count, $matches); + } + + /** + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + */ + public static function matchAll(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchAllResult + { + self::checkOffsetCapture($flags, 'matchAllWithOffsets'); + self::checkSetOrder($flags); + + $count = Preg::matchAll($pattern, $subject, $matches, $flags, $offset); + + return new MatchAllResult($count, $matches); + } + + /** + * Variant of `matchAll()` which returns non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @throws UnexpectedNullMatchException + */ + public static function matchAllStrictGroups(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchAllStrictGroupsResult + { + self::checkOffsetCapture($flags, 'matchAllWithOffsets'); + self::checkSetOrder($flags); + + $count = Preg::matchAllStrictGroups($pattern, $subject, $matches, $flags, $offset); + + return new MatchAllStrictGroupsResult($count, $matches); + } + + /** + * Runs preg_match_all with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL and PREG_MATCH_OFFSET are always set, no other flags are supported + */ + public static function matchAllWithOffsets(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchAllWithOffsetsResult + { + self::checkSetOrder($flags); + + $count = Preg::matchAllWithOffsets($pattern, $subject, $matches, $flags, $offset); + + return new MatchAllWithOffsetsResult($count, $matches); + } + /** + * @param string|string[] $pattern + * @param string|string[] $replacement + * @param string $subject + */ + public static function replace($pattern, $replacement, $subject, int $limit = -1): ReplaceResult + { + $result = Preg::replace($pattern, $replacement, $subject, $limit, $count); + + return new ReplaceResult($count, $result); + } + + /** + * @param string|string[] $pattern + * @param callable(array): string $replacement + * @param string $subject + * @param int-mask $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set + */ + public static function replaceCallback($pattern, callable $replacement, $subject, int $limit = -1, int $flags = 0): ReplaceResult + { + $result = Preg::replaceCallback($pattern, $replacement, $subject, $limit, $count, $flags); + + return new ReplaceResult($count, $result); + } + + /** + * Variant of `replaceCallback()` which outputs non-null matches (or throws) + * + * @param string $pattern + * @param callable(array): string $replacement + * @param string $subject + * @param int-mask $flags PREG_OFFSET_CAPTURE or PREG_UNMATCHED_AS_NULL, only available on PHP 7.4+ + */ + public static function replaceCallbackStrictGroups($pattern, callable $replacement, $subject, int $limit = -1, int $flags = 0): ReplaceResult + { + $result = Preg::replaceCallbackStrictGroups($pattern, $replacement, $subject, $limit, $count, $flags); + + return new ReplaceResult($count, $result); + } + + /** + * @param array): string> $pattern + * @param string $subject + * @param int-mask $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set + */ + public static function replaceCallbackArray(array $pattern, $subject, int $limit = -1, int $flags = 0): ReplaceResult + { + $result = Preg::replaceCallbackArray($pattern, $subject, $limit, $count, $flags); + + return new ReplaceResult($count, $result); + } + + private static function checkOffsetCapture(int $flags, string $useFunctionName): void + { + if (($flags & PREG_OFFSET_CAPTURE) !== 0) { + throw new \InvalidArgumentException('PREG_OFFSET_CAPTURE is not supported as it changes the return type, use '.$useFunctionName.'() instead'); + } + } + + private static function checkSetOrder(int $flags): void + { + if (($flags & PREG_SET_ORDER) !== 0) { + throw new \InvalidArgumentException('PREG_SET_ORDER is not supported as it changes the return type'); + } + } +} diff --git a/tools/php-cs-fixer/vendor/composer/pcre/src/ReplaceResult.php b/tools/php-cs-fixer/vendor/composer/pcre/src/ReplaceResult.php new file mode 100644 index 00000000..33847712 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/pcre/src/ReplaceResult.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +final class ReplaceResult +{ + /** + * @readonly + * @var string + */ + public $result; + + /** + * @readonly + * @var 0|positive-int + */ + public $count; + + /** + * @readonly + * @var bool + */ + public $matched; + + /** + * @param 0|positive-int $count + */ + public function __construct(int $count, string $result) + { + $this->count = $count; + $this->matched = (bool) $count; + $this->result = $result; + } +} diff --git a/tools/php-cs-fixer/vendor/composer/pcre/src/UnexpectedNullMatchException.php b/tools/php-cs-fixer/vendor/composer/pcre/src/UnexpectedNullMatchException.php new file mode 100644 index 00000000..f123828b --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/pcre/src/UnexpectedNullMatchException.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +class UnexpectedNullMatchException extends PcreException +{ + public static function fromFunction($function, $pattern) + { + throw new \LogicException('fromFunction should not be called on '.self::class.', use '.PcreException::class); + } +} diff --git a/tools/php-cs-fixer/vendor/composer/platform_check.php b/tools/php-cs-fixer/vendor/composer/platform_check.php new file mode 100644 index 00000000..d32d90c6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/platform_check.php @@ -0,0 +1,26 @@ += 80200)) { + $issues[] = 'Your Composer dependencies require a PHP version ">= 8.2.0". You are running ' . PHP_VERSION . '.'; +} + +if ($issues) { + if (!headers_sent()) { + header('HTTP/1.1 500 Internal Server Error'); + } + if (!ini_get('display_errors')) { + if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { + fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); + } elseif (!headers_sent()) { + echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; + } + } + trigger_error( + 'Composer detected issues in your platform: ' . implode(' ', $issues), + E_USER_ERROR + ); +} diff --git a/tools/php-cs-fixer/vendor/composer/semver/CHANGELOG.md b/tools/php-cs-fixer/vendor/composer/semver/CHANGELOG.md new file mode 100644 index 00000000..3b111612 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/CHANGELOG.md @@ -0,0 +1,214 @@ +# Change Log + +All notable changes to this project will be documented in this file. +This project adheres to [Semantic Versioning](http://semver.org/). + +### [3.4.0] 2023-08-31 + + * Support larger major version numbers (#149) + +### [3.3.2] 2022-04-01 + + * Fixed handling of non-string values (#134) + +### [3.3.1] 2022-03-16 + + * Fixed possible cache key clash in the CompilingMatcher memoization (#132) + +### [3.3.0] 2022-03-15 + + * Improved performance of CompilingMatcher by memoizing more (#131) + * Added CompilingMatcher::clear to clear all memoization caches + +### [3.2.9] 2022-02-04 + + * Revert #129 (Fixed MultiConstraint with MatchAllConstraint) which caused regressions + +### [3.2.8] 2022-02-04 + + * Updates to latest phpstan / CI by @Seldaek in https://github.com/composer/semver/pull/130 + * Fixed MultiConstraint with MatchAllConstraint by @Toflar in https://github.com/composer/semver/pull/129 + +### [3.2.7] 2022-01-04 + + * Fixed: typo in type definition of Intervals class causing issues with Psalm scanning vendors + +### [3.2.6] 2021-10-25 + + * Fixed: type improvements to parseStability + +### [3.2.5] 2021-05-24 + + * Fixed: issue comparing disjunctive MultiConstraints to conjunctive ones (#127) + * Fixed: added complete type information using phpstan annotations + +### [3.2.4] 2020-11-13 + + * Fixed: code clean-up + +### [3.2.3] 2020-11-12 + + * Fixed: constraints in the form of `X || Y, >=Y.1` and other such complex constructs were in some cases being optimized into a more restrictive constraint + +### [3.2.2] 2020-10-14 + + * Fixed: internal code cleanups + +### [3.2.1] 2020-09-27 + + * Fixed: accidental validation of broken constraints combining ^/~ and wildcards, and -dev suffix allowing weird cases + * Fixed: normalization of beta0 and such which was dropping the 0 + +### [3.2.0] 2020-09-09 + + * Added: support for `x || @dev`, not very useful but seen in the wild and failed to validate with 1.5.2/1.6.0 + * Added: support for `foobar-dev` being equal to `dev-foobar`, dev-foobar is the official way to write it but we need to support the other for BC and convenience + +### [3.1.0] 2020-09-08 + + * Added: support for constraints like `^2.x-dev` and `~2.x-dev`, not very useful but seen in the wild and failed to validate with 3.0.1 + * Fixed: invalid aliases will no longer throw, unless explicitly validated by Composer in the root package + +### [3.0.1] 2020-09-08 + + * Fixed: handling of some invalid -dev versions which were seen as valid + +### [3.0.0] 2020-05-26 + + * Break: Renamed `EmptyConstraint`, replace it with `MatchAllConstraint` + * Break: Unlikely to affect anyone but strictly speaking a breaking change, `*.*` and such variants will not match all `dev-*` versions anymore, only `*` does + * Break: ConstraintInterface is now considered internal/private and not meant to be implemented by third parties anymore + * Added `Intervals` class to check if a constraint is a subsets of another one, and allow compacting complex MultiConstraints into simpler ones + * Added `CompilingMatcher` class to speed up constraint matching against simple Constraint instances + * Added `MatchAllConstraint` and `MatchNoneConstraint` which match everything and nothing + * Added more advanced optimization of contiguous constraints inside MultiConstraint + * Added tentative support for PHP 8 + * Fixed ConstraintInterface::matches to be commutative in all cases + +### [2.0.0] 2020-04-21 + + * Break: `dev-master`, `dev-trunk` and `dev-default` now normalize to `dev-master`, `dev-trunk` and `dev-default` instead of `9999999-dev` in 1.x + * Break: Removed the deprecated `AbstractConstraint` + * Added `getUpperBound` and `getLowerBound` to ConstraintInterface. They return `Composer\Semver\Constraint\Bound` instances + * Added `MultiConstraint::create` to create the most-optimal form of ConstraintInterface from an array of constraint strings + +### [1.7.2] 2020-12-03 + + * Fixed: Allow installing on php 8 + +### [1.7.1] 2020-09-27 + + * Fixed: accidental validation of broken constraints combining ^/~ and wildcards, and -dev suffix allowing weird cases + * Fixed: normalization of beta0 and such which was dropping the 0 + +### [1.7.0] 2020-09-09 + + * Added: support for `x || @dev`, not very useful but seen in the wild and failed to validate with 1.5.2/1.6.0 + * Added: support for `foobar-dev` being equal to `dev-foobar`, dev-foobar is the official way to write it but we need to support the other for BC and convenience + +### [1.6.0] 2020-09-08 + + * Added: support for constraints like `^2.x-dev` and `~2.x-dev`, not very useful but seen in the wild and failed to validate with 1.5.2 + * Fixed: invalid aliases will no longer throw, unless explicitly validated by Composer in the root package + +### [1.5.2] 2020-09-08 + + * Fixed: handling of some invalid -dev versions which were seen as valid + * Fixed: some doctypes + +### [1.5.1] 2020-01-13 + + * Fixed: Parsing of aliased version was not validating the alias to be a valid version + +### [1.5.0] 2019-03-19 + + * Added: some support for date versions (e.g. 201903) in `~` operator + * Fixed: support for stabilities in `~` operator was inconsistent + +### [1.4.2] 2016-08-30 + + * Fixed: collapsing of complex constraints lead to buggy constraints + +### [1.4.1] 2016-06-02 + + * Changed: branch-like requirements no longer strip build metadata - [composer/semver#38](https://github.com/composer/semver/pull/38). + +### [1.4.0] 2016-03-30 + + * Added: getters on MultiConstraint - [composer/semver#35](https://github.com/composer/semver/pull/35). + +### [1.3.0] 2016-02-25 + + * Fixed: stability parsing - [composer/composer#1234](https://github.com/composer/composer/issues/4889). + * Changed: collapse contiguous constraints when possible. + +### [1.2.0] 2015-11-10 + + * Changed: allow multiple numerical identifiers in 'pre-release' version part. + * Changed: add more 'v' prefix support. + +### [1.1.0] 2015-11-03 + + * Changed: dropped redundant `test` namespace. + * Changed: minor adjustment in datetime parsing normalization. + * Changed: `ConstraintInterface` relaxed, setPrettyString is not required anymore. + * Changed: `AbstractConstraint` marked deprecated, will be removed in 2.0. + * Changed: `Constraint` is now extensible. + +### [1.0.0] 2015-09-21 + + * Break: `VersionConstraint` renamed to `Constraint`. + * Break: `SpecificConstraint` renamed to `AbstractConstraint`. + * Break: `LinkConstraintInterface` renamed to `ConstraintInterface`. + * Break: `VersionParser::parseNameVersionPairs` was removed. + * Changed: `VersionParser::parseConstraints` allows (but ignores) build metadata now. + * Changed: `VersionParser::parseConstraints` allows (but ignores) prefixing numeric versions with a 'v' now. + * Changed: Fixed namespace(s) of test files. + * Changed: `Comparator::compare` no longer throws `InvalidArgumentException`. + * Changed: `Constraint` now throws `InvalidArgumentException`. + +### [0.1.0] 2015-07-23 + + * Added: `Composer\Semver\Comparator`, various methods to compare versions. + * Added: various documents such as README.md, LICENSE, etc. + * Added: configuration files for Git, Travis, php-cs-fixer, phpunit. + * Break: the following namespaces were renamed: + - Namespace: `Composer\Package\Version` -> `Composer\Semver` + - Namespace: `Composer\Package\LinkConstraint` -> `Composer\Semver\Constraint` + - Namespace: `Composer\Test\Package\Version` -> `Composer\Test\Semver` + - Namespace: `Composer\Test\Package\LinkConstraint` -> `Composer\Test\Semver\Constraint` + * Changed: code style using php-cs-fixer. + +[3.4.0]: https://github.com/composer/semver/compare/3.3.2...3.4.0 +[3.3.2]: https://github.com/composer/semver/compare/3.3.1...3.3.2 +[3.3.1]: https://github.com/composer/semver/compare/3.3.0...3.3.1 +[3.3.0]: https://github.com/composer/semver/compare/3.2.9...3.3.0 +[3.2.9]: https://github.com/composer/semver/compare/3.2.8...3.2.9 +[3.2.8]: https://github.com/composer/semver/compare/3.2.7...3.2.8 +[3.2.7]: https://github.com/composer/semver/compare/3.2.6...3.2.7 +[3.2.6]: https://github.com/composer/semver/compare/3.2.5...3.2.6 +[3.2.5]: https://github.com/composer/semver/compare/3.2.4...3.2.5 +[3.2.4]: https://github.com/composer/semver/compare/3.2.3...3.2.4 +[3.2.3]: https://github.com/composer/semver/compare/3.2.2...3.2.3 +[3.2.2]: https://github.com/composer/semver/compare/3.2.1...3.2.2 +[3.2.1]: https://github.com/composer/semver/compare/3.2.0...3.2.1 +[3.2.0]: https://github.com/composer/semver/compare/3.1.0...3.2.0 +[3.1.0]: https://github.com/composer/semver/compare/3.0.1...3.1.0 +[3.0.1]: https://github.com/composer/semver/compare/3.0.0...3.0.1 +[3.0.0]: https://github.com/composer/semver/compare/2.0.0...3.0.0 +[2.0.0]: https://github.com/composer/semver/compare/1.5.1...2.0.0 +[1.7.2]: https://github.com/composer/semver/compare/1.7.1...1.7.2 +[1.7.1]: https://github.com/composer/semver/compare/1.7.0...1.7.1 +[1.7.0]: https://github.com/composer/semver/compare/1.6.0...1.7.0 +[1.6.0]: https://github.com/composer/semver/compare/1.5.2...1.6.0 +[1.5.2]: https://github.com/composer/semver/compare/1.5.1...1.5.2 +[1.5.1]: https://github.com/composer/semver/compare/1.5.0...1.5.1 +[1.5.0]: https://github.com/composer/semver/compare/1.4.2...1.5.0 +[1.4.2]: https://github.com/composer/semver/compare/1.4.1...1.4.2 +[1.4.1]: https://github.com/composer/semver/compare/1.4.0...1.4.1 +[1.4.0]: https://github.com/composer/semver/compare/1.3.0...1.4.0 +[1.3.0]: https://github.com/composer/semver/compare/1.2.0...1.3.0 +[1.2.0]: https://github.com/composer/semver/compare/1.1.0...1.2.0 +[1.1.0]: https://github.com/composer/semver/compare/1.0.0...1.1.0 +[1.0.0]: https://github.com/composer/semver/compare/0.1.0...1.0.0 +[0.1.0]: https://github.com/composer/semver/compare/5e0b9a4da...0.1.0 diff --git a/tools/php-cs-fixer/vendor/composer/semver/LICENSE b/tools/php-cs-fixer/vendor/composer/semver/LICENSE new file mode 100644 index 00000000..46697586 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2015 Composer + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/composer/semver/README.md b/tools/php-cs-fixer/vendor/composer/semver/README.md new file mode 100644 index 00000000..76778490 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/README.md @@ -0,0 +1,99 @@ +composer/semver +=============== + +Semver (Semantic Versioning) library that offers utilities, version constraint parsing and validation. + +Originally written as part of [composer/composer](https://github.com/composer/composer), +now extracted and made available as a stand-alone library. + +[![Continuous Integration](https://github.com/composer/semver/actions/workflows/continuous-integration.yml/badge.svg?branch=main)](https://github.com/composer/semver/actions/workflows/continuous-integration.yml) +[![PHP Lint](https://github.com/composer/semver/actions/workflows/lint.yml/badge.svg?branch=main)](https://github.com/composer/semver/actions/workflows/lint.yml) +[![PHPStan](https://github.com/composer/semver/actions/workflows/phpstan.yml/badge.svg?branch=main)](https://github.com/composer/semver/actions/workflows/phpstan.yml) + +Installation +------------ + +Install the latest version with: + +```bash +composer require composer/semver +``` + + +Requirements +------------ + +* PHP 5.3.2 is required but using the latest version of PHP is highly recommended. + + +Version Comparison +------------------ + +For details on how versions are compared, refer to the [Versions](https://getcomposer.org/doc/articles/versions.md) +article in the documentation section of the [getcomposer.org](https://getcomposer.org) website. + + +Basic usage +----------- + +### Comparator + +The [`Composer\Semver\Comparator`](https://github.com/composer/semver/blob/main/src/Comparator.php) class provides the following methods for comparing versions: + +* greaterThan($v1, $v2) +* greaterThanOrEqualTo($v1, $v2) +* lessThan($v1, $v2) +* lessThanOrEqualTo($v1, $v2) +* equalTo($v1, $v2) +* notEqualTo($v1, $v2) + +Each function takes two version strings as arguments and returns a boolean. For example: + +```php +use Composer\Semver\Comparator; + +Comparator::greaterThan('1.25.0', '1.24.0'); // 1.25.0 > 1.24.0 +``` + +### Semver + +The [`Composer\Semver\Semver`](https://github.com/composer/semver/blob/main/src/Semver.php) class provides the following methods: + +* satisfies($version, $constraints) +* satisfiedBy(array $versions, $constraint) +* sort($versions) +* rsort($versions) + +### Intervals + +The [`Composer\Semver\Intervals`](https://github.com/composer/semver/blob/main/src/Intervals.php) static class provides +a few utilities to work with complex constraints or read version intervals from a constraint: + +```php +use Composer\Semver\Intervals; + +// Checks whether $candidate is a subset of $constraint +Intervals::isSubsetOf(ConstraintInterface $candidate, ConstraintInterface $constraint); + +// Checks whether $a and $b have any intersection, equivalent to $a->matches($b) +Intervals::haveIntersections(ConstraintInterface $a, ConstraintInterface $b); + +// Optimizes a complex multi constraint by merging all intervals down to the smallest +// possible multi constraint. The drawbacks are this is not very fast, and the resulting +// multi constraint will have no human readable prettyConstraint configured on it +Intervals::compactConstraint(ConstraintInterface $constraint); + +// Creates an array of numeric intervals and branch constraints representing a given constraint +Intervals::get(ConstraintInterface $constraint); + +// Clears the memoization cache when you are done processing constraints +Intervals::clear() +``` + +See the class docblocks for more details. + + +License +------- + +composer/semver is licensed under the MIT License, see the LICENSE file for details. diff --git a/tools/php-cs-fixer/vendor/composer/semver/composer.json b/tools/php-cs-fixer/vendor/composer/semver/composer.json new file mode 100644 index 00000000..f3a6f4cc --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/composer.json @@ -0,0 +1,59 @@ +{ + "name": "composer/semver", + "description": "Semver library that offers utilities, version constraint parsing and validation.", + "type": "library", + "license": "MIT", + "keywords": [ + "semver", + "semantic", + "versioning", + "validation" + ], + "authors": [ + { + "name": "Nils Adermann", + "email": "naderman@naderman.de", + "homepage": "http://www.naderman.de" + }, + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + }, + { + "name": "Rob Bast", + "email": "rob.bast@gmail.com", + "homepage": "http://robbast.nl" + } + ], + "support": { + "irc": "ircs://irc.libera.chat:6697/composer", + "issues": "https://github.com/composer/semver/issues" + }, + "require": { + "php": "^5.3.2 || ^7.0 || ^8.0" + }, + "require-dev": { + "symfony/phpunit-bridge": "^4.2 || ^5", + "phpstan/phpstan": "^1.4" + }, + "autoload": { + "psr-4": { + "Composer\\Semver\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "Composer\\Semver\\": "tests" + } + }, + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "scripts": { + "test": "SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT=1 vendor/bin/simple-phpunit", + "phpstan": "@php vendor/bin/phpstan analyse" + } +} diff --git a/tools/php-cs-fixer/vendor/composer/semver/phpstan-baseline.neon b/tools/php-cs-fixer/vendor/composer/semver/phpstan-baseline.neon new file mode 100644 index 00000000..933cf203 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/phpstan-baseline.neon @@ -0,0 +1,11 @@ +parameters: + ignoreErrors: + - + message: "#^Parameter \\#1 \\$operator of class Composer\\\\Semver\\\\Constraint\\\\Constraint constructor expects '\\!\\='\\|'\\<'\\|'\\<\\='\\|'\\<\\>'\\|'\\='\\|'\\=\\='\\|'\\>'\\|'\\>\\=', non\\-falsy\\-string given\\.$#" + count: 1 + path: src/VersionParser.php + + - + message: "#^Strict comparison using \\=\\=\\= between null and non\\-empty\\-string will always evaluate to false\\.$#" + count: 2 + path: src/VersionParser.php diff --git a/tools/php-cs-fixer/vendor/composer/semver/src/Comparator.php b/tools/php-cs-fixer/vendor/composer/semver/src/Comparator.php new file mode 100644 index 00000000..38f483aa --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/src/Comparator.php @@ -0,0 +1,113 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver; + +use Composer\Semver\Constraint\Constraint; + +class Comparator +{ + /** + * Evaluates the expression: $version1 > $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function greaterThan($version1, $version2) + { + return self::compare($version1, '>', $version2); + } + + /** + * Evaluates the expression: $version1 >= $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function greaterThanOrEqualTo($version1, $version2) + { + return self::compare($version1, '>=', $version2); + } + + /** + * Evaluates the expression: $version1 < $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function lessThan($version1, $version2) + { + return self::compare($version1, '<', $version2); + } + + /** + * Evaluates the expression: $version1 <= $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function lessThanOrEqualTo($version1, $version2) + { + return self::compare($version1, '<=', $version2); + } + + /** + * Evaluates the expression: $version1 == $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function equalTo($version1, $version2) + { + return self::compare($version1, '==', $version2); + } + + /** + * Evaluates the expression: $version1 != $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function notEqualTo($version1, $version2) + { + return self::compare($version1, '!=', $version2); + } + + /** + * Evaluates the expression: $version1 $operator $version2. + * + * @param string $version1 + * @param string $operator + * @param string $version2 + * + * @return bool + * + * @phpstan-param Constraint::STR_OP_* $operator + */ + public static function compare($version1, $operator, $version2) + { + $constraint = new Constraint($operator, $version2); + + return $constraint->matchSpecific(new Constraint('==', $version1), true); + } +} diff --git a/tools/php-cs-fixer/vendor/composer/semver/src/CompilingMatcher.php b/tools/php-cs-fixer/vendor/composer/semver/src/CompilingMatcher.php new file mode 100644 index 00000000..45bce70a --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/src/CompilingMatcher.php @@ -0,0 +1,94 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver; + +use Composer\Semver\Constraint\Constraint; +use Composer\Semver\Constraint\ConstraintInterface; + +/** + * Helper class to evaluate constraint by compiling and reusing the code to evaluate + */ +class CompilingMatcher +{ + /** + * @var array + * @phpstan-var array + */ + private static $compiledCheckerCache = array(); + /** + * @var array + * @phpstan-var array + */ + private static $resultCache = array(); + + /** @var bool */ + private static $enabled; + + /** + * @phpstan-var array + */ + private static $transOpInt = array( + Constraint::OP_EQ => Constraint::STR_OP_EQ, + Constraint::OP_LT => Constraint::STR_OP_LT, + Constraint::OP_LE => Constraint::STR_OP_LE, + Constraint::OP_GT => Constraint::STR_OP_GT, + Constraint::OP_GE => Constraint::STR_OP_GE, + Constraint::OP_NE => Constraint::STR_OP_NE, + ); + + /** + * Clears the memoization cache once you are done + * + * @return void + */ + public static function clear() + { + self::$resultCache = array(); + self::$compiledCheckerCache = array(); + } + + /** + * Evaluates the expression: $constraint match $operator $version + * + * @param ConstraintInterface $constraint + * @param int $operator + * @phpstan-param Constraint::OP_* $operator + * @param string $version + * + * @return mixed + */ + public static function match(ConstraintInterface $constraint, $operator, $version) + { + $resultCacheKey = $operator.$constraint.';'.$version; + + if (isset(self::$resultCache[$resultCacheKey])) { + return self::$resultCache[$resultCacheKey]; + } + + if (self::$enabled === null) { + self::$enabled = !\in_array('eval', explode(',', (string) ini_get('disable_functions')), true); + } + if (!self::$enabled) { + return self::$resultCache[$resultCacheKey] = $constraint->matches(new Constraint(self::$transOpInt[$operator], $version)); + } + + $cacheKey = $operator.$constraint; + if (!isset(self::$compiledCheckerCache[$cacheKey])) { + $code = $constraint->compile($operator); + self::$compiledCheckerCache[$cacheKey] = $function = eval('return function($v, $b){return '.$code.';};'); + } else { + $function = self::$compiledCheckerCache[$cacheKey]; + } + + return self::$resultCache[$resultCacheKey] = $function($version, strpos($version, 'dev-') === 0); + } +} diff --git a/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/Bound.php b/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/Bound.php new file mode 100644 index 00000000..7effb11a --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/Bound.php @@ -0,0 +1,122 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver\Constraint; + +class Bound +{ + /** + * @var string + */ + private $version; + + /** + * @var bool + */ + private $isInclusive; + + /** + * @param string $version + * @param bool $isInclusive + */ + public function __construct($version, $isInclusive) + { + $this->version = $version; + $this->isInclusive = $isInclusive; + } + + /** + * @return string + */ + public function getVersion() + { + return $this->version; + } + + /** + * @return bool + */ + public function isInclusive() + { + return $this->isInclusive; + } + + /** + * @return bool + */ + public function isZero() + { + return $this->getVersion() === '0.0.0.0-dev' && $this->isInclusive(); + } + + /** + * @return bool + */ + public function isPositiveInfinity() + { + return $this->getVersion() === PHP_INT_MAX.'.0.0.0' && !$this->isInclusive(); + } + + /** + * Compares a bound to another with a given operator. + * + * @param Bound $other + * @param string $operator + * + * @return bool + */ + public function compareTo(Bound $other, $operator) + { + if (!\in_array($operator, array('<', '>'), true)) { + throw new \InvalidArgumentException('Does not support any other operator other than > or <.'); + } + + // If they are the same it doesn't matter + if ($this == $other) { + return false; + } + + $compareResult = version_compare($this->getVersion(), $other->getVersion()); + + // Not the same version means we don't need to check if the bounds are inclusive or not + if (0 !== $compareResult) { + return (('>' === $operator) ? 1 : -1) === $compareResult; + } + + // Question we're answering here is "am I higher than $other?" + return '>' === $operator ? $other->isInclusive() : !$other->isInclusive(); + } + + public function __toString() + { + return sprintf( + '%s [%s]', + $this->getVersion(), + $this->isInclusive() ? 'inclusive' : 'exclusive' + ); + } + + /** + * @return self + */ + public static function zero() + { + return new Bound('0.0.0.0-dev', true); + } + + /** + * @return self + */ + public static function positiveInfinity() + { + return new Bound(PHP_INT_MAX.'.0.0.0', false); + } +} diff --git a/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/Constraint.php b/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/Constraint.php new file mode 100644 index 00000000..dc394829 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/Constraint.php @@ -0,0 +1,435 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver\Constraint; + +/** + * Defines a constraint. + */ +class Constraint implements ConstraintInterface +{ + /* operator integer values */ + const OP_EQ = 0; + const OP_LT = 1; + const OP_LE = 2; + const OP_GT = 3; + const OP_GE = 4; + const OP_NE = 5; + + /* operator string values */ + const STR_OP_EQ = '=='; + const STR_OP_EQ_ALT = '='; + const STR_OP_LT = '<'; + const STR_OP_LE = '<='; + const STR_OP_GT = '>'; + const STR_OP_GE = '>='; + const STR_OP_NE = '!='; + const STR_OP_NE_ALT = '<>'; + + /** + * Operator to integer translation table. + * + * @var array + * @phpstan-var array + */ + private static $transOpStr = array( + '=' => self::OP_EQ, + '==' => self::OP_EQ, + '<' => self::OP_LT, + '<=' => self::OP_LE, + '>' => self::OP_GT, + '>=' => self::OP_GE, + '<>' => self::OP_NE, + '!=' => self::OP_NE, + ); + + /** + * Integer to operator translation table. + * + * @var array + * @phpstan-var array + */ + private static $transOpInt = array( + self::OP_EQ => '==', + self::OP_LT => '<', + self::OP_LE => '<=', + self::OP_GT => '>', + self::OP_GE => '>=', + self::OP_NE => '!=', + ); + + /** + * @var int + * @phpstan-var self::OP_* + */ + protected $operator; + + /** @var string */ + protected $version; + + /** @var string|null */ + protected $prettyString; + + /** @var Bound */ + protected $lowerBound; + + /** @var Bound */ + protected $upperBound; + + /** + * Sets operator and version to compare with. + * + * @param string $operator + * @param string $version + * + * @throws \InvalidArgumentException if invalid operator is given. + * + * @phpstan-param self::STR_OP_* $operator + */ + public function __construct($operator, $version) + { + if (!isset(self::$transOpStr[$operator])) { + throw new \InvalidArgumentException(sprintf( + 'Invalid operator "%s" given, expected one of: %s', + $operator, + implode(', ', self::getSupportedOperators()) + )); + } + + $this->operator = self::$transOpStr[$operator]; + $this->version = $version; + } + + /** + * @return string + */ + public function getVersion() + { + return $this->version; + } + + /** + * @return string + * + * @phpstan-return self::STR_OP_* + */ + public function getOperator() + { + return self::$transOpInt[$this->operator]; + } + + /** + * @param ConstraintInterface $provider + * + * @return bool + */ + public function matches(ConstraintInterface $provider) + { + if ($provider instanceof self) { + return $this->matchSpecific($provider); + } + + // turn matching around to find a match + return $provider->matches($this); + } + + /** + * {@inheritDoc} + */ + public function setPrettyString($prettyString) + { + $this->prettyString = $prettyString; + } + + /** + * {@inheritDoc} + */ + public function getPrettyString() + { + if ($this->prettyString) { + return $this->prettyString; + } + + return $this->__toString(); + } + + /** + * Get all supported comparison operators. + * + * @return array + * + * @phpstan-return list + */ + public static function getSupportedOperators() + { + return array_keys(self::$transOpStr); + } + + /** + * @param string $operator + * @return int + * + * @phpstan-param self::STR_OP_* $operator + * @phpstan-return self::OP_* + */ + public static function getOperatorConstant($operator) + { + return self::$transOpStr[$operator]; + } + + /** + * @param string $a + * @param string $b + * @param string $operator + * @param bool $compareBranches + * + * @throws \InvalidArgumentException if invalid operator is given. + * + * @return bool + * + * @phpstan-param self::STR_OP_* $operator + */ + public function versionCompare($a, $b, $operator, $compareBranches = false) + { + if (!isset(self::$transOpStr[$operator])) { + throw new \InvalidArgumentException(sprintf( + 'Invalid operator "%s" given, expected one of: %s', + $operator, + implode(', ', self::getSupportedOperators()) + )); + } + + $aIsBranch = strpos($a, 'dev-') === 0; + $bIsBranch = strpos($b, 'dev-') === 0; + + if ($operator === '!=' && ($aIsBranch || $bIsBranch)) { + return $a !== $b; + } + + if ($aIsBranch && $bIsBranch) { + return $operator === '==' && $a === $b; + } + + // when branches are not comparable, we make sure dev branches never match anything + if (!$compareBranches && ($aIsBranch || $bIsBranch)) { + return false; + } + + return \version_compare($a, $b, $operator); + } + + /** + * {@inheritDoc} + */ + public function compile($otherOperator) + { + if (strpos($this->version, 'dev-') === 0) { + if (self::OP_EQ === $this->operator) { + if (self::OP_EQ === $otherOperator) { + return sprintf('$b && $v === %s', \var_export($this->version, true)); + } + if (self::OP_NE === $otherOperator) { + return sprintf('!$b || $v !== %s', \var_export($this->version, true)); + } + return 'false'; + } + + if (self::OP_NE === $this->operator) { + if (self::OP_EQ === $otherOperator) { + return sprintf('!$b || $v !== %s', \var_export($this->version, true)); + } + if (self::OP_NE === $otherOperator) { + return 'true'; + } + return '!$b'; + } + + return 'false'; + } + + if (self::OP_EQ === $this->operator) { + if (self::OP_EQ === $otherOperator) { + return sprintf('\version_compare($v, %s, \'==\')', \var_export($this->version, true)); + } + if (self::OP_NE === $otherOperator) { + return sprintf('$b || \version_compare($v, %s, \'!=\')', \var_export($this->version, true)); + } + + return sprintf('!$b && \version_compare(%s, $v, \'%s\')', \var_export($this->version, true), self::$transOpInt[$otherOperator]); + } + + if (self::OP_NE === $this->operator) { + if (self::OP_EQ === $otherOperator) { + return sprintf('$b || (!$b && \version_compare($v, %s, \'!=\'))', \var_export($this->version, true)); + } + + if (self::OP_NE === $otherOperator) { + return 'true'; + } + return '!$b'; + } + + if (self::OP_LT === $this->operator || self::OP_LE === $this->operator) { + if (self::OP_LT === $otherOperator || self::OP_LE === $otherOperator) { + return '!$b'; + } + } else { // $this->operator must be self::OP_GT || self::OP_GE here + if (self::OP_GT === $otherOperator || self::OP_GE === $otherOperator) { + return '!$b'; + } + } + + if (self::OP_NE === $otherOperator) { + return 'true'; + } + + $codeComparison = sprintf('\version_compare($v, %s, \'%s\')', \var_export($this->version, true), self::$transOpInt[$this->operator]); + if ($this->operator === self::OP_LE) { + if ($otherOperator === self::OP_GT) { + return sprintf('!$b && \version_compare($v, %s, \'!=\') && ', \var_export($this->version, true)) . $codeComparison; + } + } elseif ($this->operator === self::OP_GE) { + if ($otherOperator === self::OP_LT) { + return sprintf('!$b && \version_compare($v, %s, \'!=\') && ', \var_export($this->version, true)) . $codeComparison; + } + } + + return sprintf('!$b && %s', $codeComparison); + } + + /** + * @param Constraint $provider + * @param bool $compareBranches + * + * @return bool + */ + public function matchSpecific(Constraint $provider, $compareBranches = false) + { + $noEqualOp = str_replace('=', '', self::$transOpInt[$this->operator]); + $providerNoEqualOp = str_replace('=', '', self::$transOpInt[$provider->operator]); + + $isEqualOp = self::OP_EQ === $this->operator; + $isNonEqualOp = self::OP_NE === $this->operator; + $isProviderEqualOp = self::OP_EQ === $provider->operator; + $isProviderNonEqualOp = self::OP_NE === $provider->operator; + + // '!=' operator is match when other operator is not '==' operator or version is not match + // these kinds of comparisons always have a solution + if ($isNonEqualOp || $isProviderNonEqualOp) { + if ($isNonEqualOp && !$isProviderNonEqualOp && !$isProviderEqualOp && strpos($provider->version, 'dev-') === 0) { + return false; + } + + if ($isProviderNonEqualOp && !$isNonEqualOp && !$isEqualOp && strpos($this->version, 'dev-') === 0) { + return false; + } + + if (!$isEqualOp && !$isProviderEqualOp) { + return true; + } + return $this->versionCompare($provider->version, $this->version, '!=', $compareBranches); + } + + // an example for the condition is <= 2.0 & < 1.0 + // these kinds of comparisons always have a solution + if ($this->operator !== self::OP_EQ && $noEqualOp === $providerNoEqualOp) { + return !(strpos($this->version, 'dev-') === 0 || strpos($provider->version, 'dev-') === 0); + } + + $version1 = $isEqualOp ? $this->version : $provider->version; + $version2 = $isEqualOp ? $provider->version : $this->version; + $operator = $isEqualOp ? $provider->operator : $this->operator; + + if ($this->versionCompare($version1, $version2, self::$transOpInt[$operator], $compareBranches)) { + // special case, e.g. require >= 1.0 and provide < 1.0 + // 1.0 >= 1.0 but 1.0 is outside of the provided interval + + return !(self::$transOpInt[$provider->operator] === $providerNoEqualOp + && self::$transOpInt[$this->operator] !== $noEqualOp + && \version_compare($provider->version, $this->version, '==')); + } + + return false; + } + + /** + * @return string + */ + public function __toString() + { + return self::$transOpInt[$this->operator] . ' ' . $this->version; + } + + /** + * {@inheritDoc} + */ + public function getLowerBound() + { + $this->extractBounds(); + + return $this->lowerBound; + } + + /** + * {@inheritDoc} + */ + public function getUpperBound() + { + $this->extractBounds(); + + return $this->upperBound; + } + + /** + * @return void + */ + private function extractBounds() + { + if (null !== $this->lowerBound) { + return; + } + + // Branches + if (strpos($this->version, 'dev-') === 0) { + $this->lowerBound = Bound::zero(); + $this->upperBound = Bound::positiveInfinity(); + + return; + } + + switch ($this->operator) { + case self::OP_EQ: + $this->lowerBound = new Bound($this->version, true); + $this->upperBound = new Bound($this->version, true); + break; + case self::OP_LT: + $this->lowerBound = Bound::zero(); + $this->upperBound = new Bound($this->version, false); + break; + case self::OP_LE: + $this->lowerBound = Bound::zero(); + $this->upperBound = new Bound($this->version, true); + break; + case self::OP_GT: + $this->lowerBound = new Bound($this->version, false); + $this->upperBound = Bound::positiveInfinity(); + break; + case self::OP_GE: + $this->lowerBound = new Bound($this->version, true); + $this->upperBound = Bound::positiveInfinity(); + break; + case self::OP_NE: + $this->lowerBound = Bound::zero(); + $this->upperBound = Bound::positiveInfinity(); + break; + } + } +} diff --git a/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/ConstraintInterface.php b/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/ConstraintInterface.php new file mode 100644 index 00000000..389b935b --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/ConstraintInterface.php @@ -0,0 +1,75 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver\Constraint; + +/** + * DO NOT IMPLEMENT this interface. It is only meant for usage as a type hint + * in libraries relying on composer/semver but creating your own constraint class + * that implements this interface is not a supported use case and will cause the + * composer/semver components to return unexpected results. + */ +interface ConstraintInterface +{ + /** + * Checks whether the given constraint intersects in any way with this constraint + * + * @param ConstraintInterface $provider + * + * @return bool + */ + public function matches(ConstraintInterface $provider); + + /** + * Provides a compiled version of the constraint for the given operator + * The compiled version must be a PHP expression. + * Executor of compile version must provide 2 variables: + * - $v = the string version to compare with + * - $b = whether or not the version is a non-comparable branch (starts with "dev-") + * + * @see Constraint::OP_* for the list of available operators. + * @example return '!$b && version_compare($v, '1.0', '>')'; + * + * @param int $otherOperator one Constraint::OP_* + * + * @return string + * + * @phpstan-param Constraint::OP_* $otherOperator + */ + public function compile($otherOperator); + + /** + * @return Bound + */ + public function getUpperBound(); + + /** + * @return Bound + */ + public function getLowerBound(); + + /** + * @return string + */ + public function getPrettyString(); + + /** + * @param string|null $prettyString + * + * @return void + */ + public function setPrettyString($prettyString); + + /** + * @return string + */ + public function __toString(); +} diff --git a/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/MatchAllConstraint.php b/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/MatchAllConstraint.php new file mode 100644 index 00000000..5e51af95 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/MatchAllConstraint.php @@ -0,0 +1,85 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver\Constraint; + +/** + * Defines the absence of a constraint. + * + * This constraint matches everything. + */ +class MatchAllConstraint implements ConstraintInterface +{ + /** @var string|null */ + protected $prettyString; + + /** + * @param ConstraintInterface $provider + * + * @return bool + */ + public function matches(ConstraintInterface $provider) + { + return true; + } + + /** + * {@inheritDoc} + */ + public function compile($otherOperator) + { + return 'true'; + } + + /** + * {@inheritDoc} + */ + public function setPrettyString($prettyString) + { + $this->prettyString = $prettyString; + } + + /** + * {@inheritDoc} + */ + public function getPrettyString() + { + if ($this->prettyString) { + return $this->prettyString; + } + + return (string) $this; + } + + /** + * {@inheritDoc} + */ + public function __toString() + { + return '*'; + } + + /** + * {@inheritDoc} + */ + public function getUpperBound() + { + return Bound::positiveInfinity(); + } + + /** + * {@inheritDoc} + */ + public function getLowerBound() + { + return Bound::zero(); + } +} diff --git a/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/MatchNoneConstraint.php b/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/MatchNoneConstraint.php new file mode 100644 index 00000000..dadcf622 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/MatchNoneConstraint.php @@ -0,0 +1,83 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver\Constraint; + +/** + * Blackhole of constraints, nothing escapes it + */ +class MatchNoneConstraint implements ConstraintInterface +{ + /** @var string|null */ + protected $prettyString; + + /** + * @param ConstraintInterface $provider + * + * @return bool + */ + public function matches(ConstraintInterface $provider) + { + return false; + } + + /** + * {@inheritDoc} + */ + public function compile($otherOperator) + { + return 'false'; + } + + /** + * {@inheritDoc} + */ + public function setPrettyString($prettyString) + { + $this->prettyString = $prettyString; + } + + /** + * {@inheritDoc} + */ + public function getPrettyString() + { + if ($this->prettyString) { + return $this->prettyString; + } + + return (string) $this; + } + + /** + * {@inheritDoc} + */ + public function __toString() + { + return '[]'; + } + + /** + * {@inheritDoc} + */ + public function getUpperBound() + { + return new Bound('0.0.0.0-dev', false); + } + + /** + * {@inheritDoc} + */ + public function getLowerBound() + { + return new Bound('0.0.0.0-dev', false); + } +} diff --git a/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/MultiConstraint.php b/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/MultiConstraint.php new file mode 100644 index 00000000..1f4c0061 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/src/Constraint/MultiConstraint.php @@ -0,0 +1,325 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver\Constraint; + +/** + * Defines a conjunctive or disjunctive set of constraints. + */ +class MultiConstraint implements ConstraintInterface +{ + /** + * @var ConstraintInterface[] + * @phpstan-var non-empty-array + */ + protected $constraints; + + /** @var string|null */ + protected $prettyString; + + /** @var string|null */ + protected $string; + + /** @var bool */ + protected $conjunctive; + + /** @var Bound|null */ + protected $lowerBound; + + /** @var Bound|null */ + protected $upperBound; + + /** + * @param ConstraintInterface[] $constraints A set of constraints + * @param bool $conjunctive Whether the constraints should be treated as conjunctive or disjunctive + * + * @throws \InvalidArgumentException If less than 2 constraints are passed + */ + public function __construct(array $constraints, $conjunctive = true) + { + if (\count($constraints) < 2) { + throw new \InvalidArgumentException( + 'Must provide at least two constraints for a MultiConstraint. Use '. + 'the regular Constraint class for one constraint only or MatchAllConstraint for none. You may use '. + 'MultiConstraint::create() which optimizes and handles those cases automatically.' + ); + } + + $this->constraints = $constraints; + $this->conjunctive = $conjunctive; + } + + /** + * @return ConstraintInterface[] + */ + public function getConstraints() + { + return $this->constraints; + } + + /** + * @return bool + */ + public function isConjunctive() + { + return $this->conjunctive; + } + + /** + * @return bool + */ + public function isDisjunctive() + { + return !$this->conjunctive; + } + + /** + * {@inheritDoc} + */ + public function compile($otherOperator) + { + $parts = array(); + foreach ($this->constraints as $constraint) { + $code = $constraint->compile($otherOperator); + if ($code === 'true') { + if (!$this->conjunctive) { + return 'true'; + } + } elseif ($code === 'false') { + if ($this->conjunctive) { + return 'false'; + } + } else { + $parts[] = '('.$code.')'; + } + } + + if (!$parts) { + return $this->conjunctive ? 'true' : 'false'; + } + + return $this->conjunctive ? implode('&&', $parts) : implode('||', $parts); + } + + /** + * @param ConstraintInterface $provider + * + * @return bool + */ + public function matches(ConstraintInterface $provider) + { + if (false === $this->conjunctive) { + foreach ($this->constraints as $constraint) { + if ($provider->matches($constraint)) { + return true; + } + } + + return false; + } + + // when matching a conjunctive and a disjunctive multi constraint we have to iterate over the disjunctive one + // otherwise we'd return true if different parts of the disjunctive constraint match the conjunctive one + // which would lead to incorrect results, e.g. [>1 and <2] would match [<1 or >2] although they do not intersect + if ($provider instanceof MultiConstraint && $provider->isDisjunctive()) { + return $provider->matches($this); + } + + foreach ($this->constraints as $constraint) { + if (!$provider->matches($constraint)) { + return false; + } + } + + return true; + } + + /** + * {@inheritDoc} + */ + public function setPrettyString($prettyString) + { + $this->prettyString = $prettyString; + } + + /** + * {@inheritDoc} + */ + public function getPrettyString() + { + if ($this->prettyString) { + return $this->prettyString; + } + + return (string) $this; + } + + /** + * {@inheritDoc} + */ + public function __toString() + { + if ($this->string !== null) { + return $this->string; + } + + $constraints = array(); + foreach ($this->constraints as $constraint) { + $constraints[] = (string) $constraint; + } + + return $this->string = '[' . implode($this->conjunctive ? ' ' : ' || ', $constraints) . ']'; + } + + /** + * {@inheritDoc} + */ + public function getLowerBound() + { + $this->extractBounds(); + + if (null === $this->lowerBound) { + throw new \LogicException('extractBounds should have populated the lowerBound property'); + } + + return $this->lowerBound; + } + + /** + * {@inheritDoc} + */ + public function getUpperBound() + { + $this->extractBounds(); + + if (null === $this->upperBound) { + throw new \LogicException('extractBounds should have populated the upperBound property'); + } + + return $this->upperBound; + } + + /** + * Tries to optimize the constraints as much as possible, meaning + * reducing/collapsing congruent constraints etc. + * Does not necessarily return a MultiConstraint instance if + * things can be reduced to a simple constraint + * + * @param ConstraintInterface[] $constraints A set of constraints + * @param bool $conjunctive Whether the constraints should be treated as conjunctive or disjunctive + * + * @return ConstraintInterface + */ + public static function create(array $constraints, $conjunctive = true) + { + if (0 === \count($constraints)) { + return new MatchAllConstraint(); + } + + if (1 === \count($constraints)) { + return $constraints[0]; + } + + $optimized = self::optimizeConstraints($constraints, $conjunctive); + if ($optimized !== null) { + list($constraints, $conjunctive) = $optimized; + if (\count($constraints) === 1) { + return $constraints[0]; + } + } + + return new self($constraints, $conjunctive); + } + + /** + * @param ConstraintInterface[] $constraints + * @param bool $conjunctive + * @return ?array + * + * @phpstan-return array{0: list, 1: bool}|null + */ + private static function optimizeConstraints(array $constraints, $conjunctive) + { + // parse the two OR groups and if they are contiguous we collapse + // them into one constraint + // [>= 1 < 2] || [>= 2 < 3] || [>= 3 < 4] => [>= 1 < 4] + if (!$conjunctive) { + $left = $constraints[0]; + $mergedConstraints = array(); + $optimized = false; + for ($i = 1, $l = \count($constraints); $i < $l; $i++) { + $right = $constraints[$i]; + if ( + $left instanceof self + && $left->conjunctive + && $right instanceof self + && $right->conjunctive + && \count($left->constraints) === 2 + && \count($right->constraints) === 2 + && ($left0 = (string) $left->constraints[0]) + && $left0[0] === '>' && $left0[1] === '=' + && ($left1 = (string) $left->constraints[1]) + && $left1[0] === '<' + && ($right0 = (string) $right->constraints[0]) + && $right0[0] === '>' && $right0[1] === '=' + && ($right1 = (string) $right->constraints[1]) + && $right1[0] === '<' + && substr($left1, 2) === substr($right0, 3) + ) { + $optimized = true; + $left = new MultiConstraint( + array( + $left->constraints[0], + $right->constraints[1], + ), + true); + } else { + $mergedConstraints[] = $left; + $left = $right; + } + } + if ($optimized) { + $mergedConstraints[] = $left; + return array($mergedConstraints, false); + } + } + + // TODO: Here's the place to put more optimizations + + return null; + } + + /** + * @return void + */ + private function extractBounds() + { + if (null !== $this->lowerBound) { + return; + } + + foreach ($this->constraints as $constraint) { + if (null === $this->lowerBound || null === $this->upperBound) { + $this->lowerBound = $constraint->getLowerBound(); + $this->upperBound = $constraint->getUpperBound(); + continue; + } + + if ($constraint->getLowerBound()->compareTo($this->lowerBound, $this->isConjunctive() ? '>' : '<')) { + $this->lowerBound = $constraint->getLowerBound(); + } + + if ($constraint->getUpperBound()->compareTo($this->upperBound, $this->isConjunctive() ? '<' : '>')) { + $this->upperBound = $constraint->getUpperBound(); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/composer/semver/src/Interval.php b/tools/php-cs-fixer/vendor/composer/semver/src/Interval.php new file mode 100644 index 00000000..43d5a4f5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/src/Interval.php @@ -0,0 +1,98 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver; + +use Composer\Semver\Constraint\Constraint; + +class Interval +{ + /** @var Constraint */ + private $start; + /** @var Constraint */ + private $end; + + public function __construct(Constraint $start, Constraint $end) + { + $this->start = $start; + $this->end = $end; + } + + /** + * @return Constraint + */ + public function getStart() + { + return $this->start; + } + + /** + * @return Constraint + */ + public function getEnd() + { + return $this->end; + } + + /** + * @return Constraint + */ + public static function fromZero() + { + static $zero; + + if (null === $zero) { + $zero = new Constraint('>=', '0.0.0.0-dev'); + } + + return $zero; + } + + /** + * @return Constraint + */ + public static function untilPositiveInfinity() + { + static $positiveInfinity; + + if (null === $positiveInfinity) { + $positiveInfinity = new Constraint('<', PHP_INT_MAX.'.0.0.0'); + } + + return $positiveInfinity; + } + + /** + * @return self + */ + public static function any() + { + return new self(self::fromZero(), self::untilPositiveInfinity()); + } + + /** + * @return array{'names': string[], 'exclude': bool} + */ + public static function anyDev() + { + // any == exclude nothing + return array('names' => array(), 'exclude' => true); + } + + /** + * @return array{'names': string[], 'exclude': bool} + */ + public static function noDev() + { + // nothing == no names included + return array('names' => array(), 'exclude' => false); + } +} diff --git a/tools/php-cs-fixer/vendor/composer/semver/src/Intervals.php b/tools/php-cs-fixer/vendor/composer/semver/src/Intervals.php new file mode 100644 index 00000000..d889d0ad --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/src/Intervals.php @@ -0,0 +1,478 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver; + +use Composer\Semver\Constraint\Constraint; +use Composer\Semver\Constraint\ConstraintInterface; +use Composer\Semver\Constraint\MatchAllConstraint; +use Composer\Semver\Constraint\MatchNoneConstraint; +use Composer\Semver\Constraint\MultiConstraint; + +/** + * Helper class generating intervals from constraints + * + * This contains utilities for: + * + * - compacting an existing constraint which can be used to combine several into one + * by creating a MultiConstraint out of the many constraints you have. + * + * - checking whether one subset is a subset of another. + * + * Note: You should call clear to free memoization memory usage when you are done using this class + */ +class Intervals +{ + /** + * @phpstan-var array + */ + private static $intervalsCache = array(); + + /** + * @phpstan-var array + */ + private static $opSortOrder = array( + '>=' => -3, + '<' => -2, + '>' => 2, + '<=' => 3, + ); + + /** + * Clears the memoization cache once you are done + * + * @return void + */ + public static function clear() + { + self::$intervalsCache = array(); + } + + /** + * Checks whether $candidate is a subset of $constraint + * + * @return bool + */ + public static function isSubsetOf(ConstraintInterface $candidate, ConstraintInterface $constraint) + { + if ($constraint instanceof MatchAllConstraint) { + return true; + } + + if ($candidate instanceof MatchNoneConstraint || $constraint instanceof MatchNoneConstraint) { + return false; + } + + $intersectionIntervals = self::get(new MultiConstraint(array($candidate, $constraint), true)); + $candidateIntervals = self::get($candidate); + if (\count($intersectionIntervals['numeric']) !== \count($candidateIntervals['numeric'])) { + return false; + } + + foreach ($intersectionIntervals['numeric'] as $index => $interval) { + if (!isset($candidateIntervals['numeric'][$index])) { + return false; + } + + if ((string) $candidateIntervals['numeric'][$index]->getStart() !== (string) $interval->getStart()) { + return false; + } + + if ((string) $candidateIntervals['numeric'][$index]->getEnd() !== (string) $interval->getEnd()) { + return false; + } + } + + if ($intersectionIntervals['branches']['exclude'] !== $candidateIntervals['branches']['exclude']) { + return false; + } + if (\count($intersectionIntervals['branches']['names']) !== \count($candidateIntervals['branches']['names'])) { + return false; + } + foreach ($intersectionIntervals['branches']['names'] as $index => $name) { + if ($name !== $candidateIntervals['branches']['names'][$index]) { + return false; + } + } + + return true; + } + + /** + * Checks whether $a and $b have any intersection, equivalent to $a->matches($b) + * + * @return bool + */ + public static function haveIntersections(ConstraintInterface $a, ConstraintInterface $b) + { + if ($a instanceof MatchAllConstraint || $b instanceof MatchAllConstraint) { + return true; + } + + if ($a instanceof MatchNoneConstraint || $b instanceof MatchNoneConstraint) { + return false; + } + + $intersectionIntervals = self::generateIntervals(new MultiConstraint(array($a, $b), true), true); + + return \count($intersectionIntervals['numeric']) > 0 || $intersectionIntervals['branches']['exclude'] || \count($intersectionIntervals['branches']['names']) > 0; + } + + /** + * Attempts to optimize a MultiConstraint + * + * When merging MultiConstraints together they can get very large, this will + * compact it by looking at the real intervals covered by all the constraints + * and then creates a new constraint containing only the smallest amount of rules + * to match the same intervals. + * + * @return ConstraintInterface + */ + public static function compactConstraint(ConstraintInterface $constraint) + { + if (!$constraint instanceof MultiConstraint) { + return $constraint; + } + + $intervals = self::generateIntervals($constraint); + $constraints = array(); + $hasNumericMatchAll = false; + + if (\count($intervals['numeric']) === 1 && (string) $intervals['numeric'][0]->getStart() === (string) Interval::fromZero() && (string) $intervals['numeric'][0]->getEnd() === (string) Interval::untilPositiveInfinity()) { + $constraints[] = $intervals['numeric'][0]->getStart(); + $hasNumericMatchAll = true; + } else { + $unEqualConstraints = array(); + for ($i = 0, $count = \count($intervals['numeric']); $i < $count; $i++) { + $interval = $intervals['numeric'][$i]; + + // if current interval ends with < N and next interval begins with > N we can swap this out for != N + // but this needs to happen as a conjunctive expression together with the start of the current interval + // and end of next interval, so [>=M, N, [>=M, !=N, getEnd()->getOperator() === '<' && $i+1 < $count) { + $nextInterval = $intervals['numeric'][$i+1]; + if ($interval->getEnd()->getVersion() === $nextInterval->getStart()->getVersion() && $nextInterval->getStart()->getOperator() === '>') { + // only add a start if we didn't already do so, can be skipped if we're looking at second + // interval in [>=M, N, P, =M, !=N] already and we only want to add !=P right now + if (\count($unEqualConstraints) === 0 && (string) $interval->getStart() !== (string) Interval::fromZero()) { + $unEqualConstraints[] = $interval->getStart(); + } + $unEqualConstraints[] = new Constraint('!=', $interval->getEnd()->getVersion()); + continue; + } + } + + if (\count($unEqualConstraints) > 0) { + // this is where the end of the following interval of a != constraint is added as explained above + if ((string) $interval->getEnd() !== (string) Interval::untilPositiveInfinity()) { + $unEqualConstraints[] = $interval->getEnd(); + } + + // count is 1 if entire constraint is just one != expression + if (\count($unEqualConstraints) > 1) { + $constraints[] = new MultiConstraint($unEqualConstraints, true); + } else { + $constraints[] = $unEqualConstraints[0]; + } + + $unEqualConstraints = array(); + continue; + } + + // convert back >= x - <= x intervals to == x + if ($interval->getStart()->getVersion() === $interval->getEnd()->getVersion() && $interval->getStart()->getOperator() === '>=' && $interval->getEnd()->getOperator() === '<=') { + $constraints[] = new Constraint('==', $interval->getStart()->getVersion()); + continue; + } + + if ((string) $interval->getStart() === (string) Interval::fromZero()) { + $constraints[] = $interval->getEnd(); + } elseif ((string) $interval->getEnd() === (string) Interval::untilPositiveInfinity()) { + $constraints[] = $interval->getStart(); + } else { + $constraints[] = new MultiConstraint(array($interval->getStart(), $interval->getEnd()), true); + } + } + } + + $devConstraints = array(); + + if (0 === \count($intervals['branches']['names'])) { + if ($intervals['branches']['exclude']) { + if ($hasNumericMatchAll) { + return new MatchAllConstraint; + } + // otherwise constraint should contain a != operator and already cover this + } + } else { + foreach ($intervals['branches']['names'] as $branchName) { + if ($intervals['branches']['exclude']) { + $devConstraints[] = new Constraint('!=', $branchName); + } else { + $devConstraints[] = new Constraint('==', $branchName); + } + } + + // excluded branches, e.g. != dev-foo are conjunctive with the interval, so + // > 2.0 != dev-foo must return a conjunctive constraint + if ($intervals['branches']['exclude']) { + if (\count($constraints) > 1) { + return new MultiConstraint(array_merge( + array(new MultiConstraint($constraints, false)), + $devConstraints + ), true); + } + + if (\count($constraints) === 1 && (string)$constraints[0] === (string)Interval::fromZero()) { + if (\count($devConstraints) > 1) { + return new MultiConstraint($devConstraints, true); + } + return $devConstraints[0]; + } + + return new MultiConstraint(array_merge($constraints, $devConstraints), true); + } + + // otherwise devConstraints contains a list of == operators for branches which are disjunctive with the + // rest of the constraint + $constraints = array_merge($constraints, $devConstraints); + } + + if (\count($constraints) > 1) { + return new MultiConstraint($constraints, false); + } + + if (\count($constraints) === 1) { + return $constraints[0]; + } + + return new MatchNoneConstraint; + } + + /** + * Creates an array of numeric intervals and branch constraints representing a given constraint + * + * if the returned numeric array is empty it means the constraint matches nothing in the numeric range (0 - +inf) + * if the returned branches array is empty it means no dev-* versions are matched + * if a constraint matches all possible dev-* versions, branches will contain Interval::anyDev() + * + * @return array + * @phpstan-return array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}} + */ + public static function get(ConstraintInterface $constraint) + { + $key = (string) $constraint; + + if (!isset(self::$intervalsCache[$key])) { + self::$intervalsCache[$key] = self::generateIntervals($constraint); + } + + return self::$intervalsCache[$key]; + } + + /** + * @param bool $stopOnFirstValidInterval + * + * @phpstan-return array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}} + */ + private static function generateIntervals(ConstraintInterface $constraint, $stopOnFirstValidInterval = false) + { + if ($constraint instanceof MatchAllConstraint) { + return array('numeric' => array(new Interval(Interval::fromZero(), Interval::untilPositiveInfinity())), 'branches' => Interval::anyDev()); + } + + if ($constraint instanceof MatchNoneConstraint) { + return array('numeric' => array(), 'branches' => array('names' => array(), 'exclude' => false)); + } + + if ($constraint instanceof Constraint) { + return self::generateSingleConstraintIntervals($constraint); + } + + if (!$constraint instanceof MultiConstraint) { + throw new \UnexpectedValueException('The constraint passed in should be an MatchAllConstraint, Constraint or MultiConstraint instance, got '.\get_class($constraint).'.'); + } + + $constraints = $constraint->getConstraints(); + + $numericGroups = array(); + $constraintBranches = array(); + foreach ($constraints as $c) { + $res = self::get($c); + $numericGroups[] = $res['numeric']; + $constraintBranches[] = $res['branches']; + } + + if ($constraint->isDisjunctive()) { + $branches = Interval::noDev(); + foreach ($constraintBranches as $b) { + if ($b['exclude']) { + if ($branches['exclude']) { + // disjunctive constraint, so only exclude what's excluded in all constraints + // !=a,!=b || !=b,!=c => !=b + $branches['names'] = array_intersect($branches['names'], $b['names']); + } else { + // disjunctive constraint so exclude all names which are not explicitly included in the alternative + // (==b || ==c) || !=a,!=b => !=a + $branches['exclude'] = true; + $branches['names'] = array_diff($b['names'], $branches['names']); + } + } else { + if ($branches['exclude']) { + // disjunctive constraint so exclude all names which are not explicitly included in the alternative + // !=a,!=b || (==b || ==c) => !=a + $branches['names'] = array_diff($branches['names'], $b['names']); + } else { + // disjunctive constraint, so just add all the other branches + // (==a || ==b) || ==c => ==a || ==b || ==c + $branches['names'] = array_merge($branches['names'], $b['names']); + } + } + } + } else { + $branches = Interval::anyDev(); + foreach ($constraintBranches as $b) { + if ($b['exclude']) { + if ($branches['exclude']) { + // conjunctive, so just add all branch names to be excluded + // !=a && !=b => !=a,!=b + $branches['names'] = array_merge($branches['names'], $b['names']); + } else { + // conjunctive, so only keep included names which are not excluded + // (==a||==c) && !=a,!=b => ==c + $branches['names'] = array_diff($branches['names'], $b['names']); + } + } else { + if ($branches['exclude']) { + // conjunctive, so only keep included names which are not excluded + // !=a,!=b && (==a||==c) => ==c + $branches['names'] = array_diff($b['names'], $branches['names']); + $branches['exclude'] = false; + } else { + // conjunctive, so only keep names that are included in both + // (==a||==b) && (==a||==c) => ==a + $branches['names'] = array_intersect($branches['names'], $b['names']); + } + } + } + } + + $branches['names'] = array_unique($branches['names']); + + if (\count($numericGroups) === 1) { + return array('numeric' => $numericGroups[0], 'branches' => $branches); + } + + $borders = array(); + foreach ($numericGroups as $group) { + foreach ($group as $interval) { + $borders[] = array('version' => $interval->getStart()->getVersion(), 'operator' => $interval->getStart()->getOperator(), 'side' => 'start'); + $borders[] = array('version' => $interval->getEnd()->getVersion(), 'operator' => $interval->getEnd()->getOperator(), 'side' => 'end'); + } + } + + $opSortOrder = self::$opSortOrder; + usort($borders, function ($a, $b) use ($opSortOrder) { + $order = version_compare($a['version'], $b['version']); + if ($order === 0) { + return $opSortOrder[$a['operator']] - $opSortOrder[$b['operator']]; + } + + return $order; + }); + + $activeIntervals = 0; + $intervals = array(); + $index = 0; + $activationThreshold = $constraint->isConjunctive() ? \count($numericGroups) : 1; + $start = null; + foreach ($borders as $border) { + if ($border['side'] === 'start') { + $activeIntervals++; + } else { + $activeIntervals--; + } + if (!$start && $activeIntervals >= $activationThreshold) { + $start = new Constraint($border['operator'], $border['version']); + } elseif ($start && $activeIntervals < $activationThreshold) { + // filter out invalid intervals like > x - <= x, or >= x - < x + if ( + version_compare($start->getVersion(), $border['version'], '=') + && ( + ($start->getOperator() === '>' && $border['operator'] === '<=') + || ($start->getOperator() === '>=' && $border['operator'] === '<') + ) + ) { + unset($intervals[$index]); + } else { + $intervals[$index] = new Interval($start, new Constraint($border['operator'], $border['version'])); + $index++; + + if ($stopOnFirstValidInterval) { + break; + } + } + + $start = null; + } + } + + return array('numeric' => $intervals, 'branches' => $branches); + } + + /** + * @phpstan-return array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}} + */ + private static function generateSingleConstraintIntervals(Constraint $constraint) + { + $op = $constraint->getOperator(); + + // handle branch constraints first + if (strpos($constraint->getVersion(), 'dev-') === 0) { + $intervals = array(); + $branches = array('names' => array(), 'exclude' => false); + + // != dev-foo means any numeric version may match, we treat >/< like != they are not really defined for branches + if ($op === '!=') { + $intervals[] = new Interval(Interval::fromZero(), Interval::untilPositiveInfinity()); + $branches = array('names' => array($constraint->getVersion()), 'exclude' => true); + } elseif ($op === '==') { + $branches['names'][] = $constraint->getVersion(); + } + + return array( + 'numeric' => $intervals, + 'branches' => $branches, + ); + } + + if ($op[0] === '>') { // > & >= + return array('numeric' => array(new Interval($constraint, Interval::untilPositiveInfinity())), 'branches' => Interval::noDev()); + } + if ($op[0] === '<') { // < & <= + return array('numeric' => array(new Interval(Interval::fromZero(), $constraint)), 'branches' => Interval::noDev()); + } + if ($op === '!=') { + // convert !=x to intervals of 0 - x - +inf + dev* + return array('numeric' => array( + new Interval(Interval::fromZero(), new Constraint('<', $constraint->getVersion())), + new Interval(new Constraint('>', $constraint->getVersion()), Interval::untilPositiveInfinity()), + ), 'branches' => Interval::anyDev()); + } + + // convert ==x to an interval of >=x - <=x + return array('numeric' => array( + new Interval(new Constraint('>=', $constraint->getVersion()), new Constraint('<=', $constraint->getVersion())), + ), 'branches' => Interval::noDev()); + } +} diff --git a/tools/php-cs-fixer/vendor/composer/semver/src/Semver.php b/tools/php-cs-fixer/vendor/composer/semver/src/Semver.php new file mode 100644 index 00000000..4d6de3c2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/src/Semver.php @@ -0,0 +1,129 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver; + +use Composer\Semver\Constraint\Constraint; + +class Semver +{ + const SORT_ASC = 1; + const SORT_DESC = -1; + + /** @var VersionParser */ + private static $versionParser; + + /** + * Determine if given version satisfies given constraints. + * + * @param string $version + * @param string $constraints + * + * @return bool + */ + public static function satisfies($version, $constraints) + { + if (null === self::$versionParser) { + self::$versionParser = new VersionParser(); + } + + $versionParser = self::$versionParser; + $provider = new Constraint('==', $versionParser->normalize($version)); + $parsedConstraints = $versionParser->parseConstraints($constraints); + + return $parsedConstraints->matches($provider); + } + + /** + * Return all versions that satisfy given constraints. + * + * @param string[] $versions + * @param string $constraints + * + * @return string[] + */ + public static function satisfiedBy(array $versions, $constraints) + { + $versions = array_filter($versions, function ($version) use ($constraints) { + return Semver::satisfies($version, $constraints); + }); + + return array_values($versions); + } + + /** + * Sort given array of versions. + * + * @param string[] $versions + * + * @return string[] + */ + public static function sort(array $versions) + { + return self::usort($versions, self::SORT_ASC); + } + + /** + * Sort given array of versions in reverse. + * + * @param string[] $versions + * + * @return string[] + */ + public static function rsort(array $versions) + { + return self::usort($versions, self::SORT_DESC); + } + + /** + * @param string[] $versions + * @param int $direction + * + * @return string[] + */ + private static function usort(array $versions, $direction) + { + if (null === self::$versionParser) { + self::$versionParser = new VersionParser(); + } + + $versionParser = self::$versionParser; + $normalized = array(); + + // Normalize outside of usort() scope for minor performance increase. + // Creates an array of arrays: [[normalized, key], ...] + foreach ($versions as $key => $version) { + $normalizedVersion = $versionParser->normalize($version); + $normalizedVersion = $versionParser->normalizeDefaultBranch($normalizedVersion); + $normalized[] = array($normalizedVersion, $key); + } + + usort($normalized, function (array $left, array $right) use ($direction) { + if ($left[0] === $right[0]) { + return 0; + } + + if (Comparator::lessThan($left[0], $right[0])) { + return -$direction; + } + + return $direction; + }); + + // Recreate input array, using the original indexes which are now in sorted order. + $sorted = array(); + foreach ($normalized as $item) { + $sorted[] = $versions[$item[1]]; + } + + return $sorted; + } +} diff --git a/tools/php-cs-fixer/vendor/composer/semver/src/VersionParser.php b/tools/php-cs-fixer/vendor/composer/semver/src/VersionParser.php new file mode 100644 index 00000000..9318629a --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/semver/src/VersionParser.php @@ -0,0 +1,586 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver; + +use Composer\Semver\Constraint\ConstraintInterface; +use Composer\Semver\Constraint\MatchAllConstraint; +use Composer\Semver\Constraint\MultiConstraint; +use Composer\Semver\Constraint\Constraint; + +/** + * Version parser. + * + * @author Jordi Boggiano + */ +class VersionParser +{ + /** + * Regex to match pre-release data (sort of). + * + * Due to backwards compatibility: + * - Instead of enforcing hyphen, an underscore, dot or nothing at all are also accepted. + * - Only stabilities as recognized by Composer are allowed to precede a numerical identifier. + * - Numerical-only pre-release identifiers are not supported, see tests. + * + * |--------------| + * [major].[minor].[patch] -[pre-release] +[build-metadata] + * + * @var string + */ + private static $modifierRegex = '[._-]?(?:(stable|beta|b|RC|alpha|a|patch|pl|p)((?:[.-]?\d+)*+)?)?([.-]?dev)?'; + + /** @var string */ + private static $stabilitiesRegex = 'stable|RC|beta|alpha|dev'; + + /** + * Returns the stability of a version. + * + * @param string $version + * + * @return string + * @phpstan-return 'stable'|'RC'|'beta'|'alpha'|'dev' + */ + public static function parseStability($version) + { + $version = (string) preg_replace('{#.+$}', '', (string) $version); + + if (strpos($version, 'dev-') === 0 || '-dev' === substr($version, -4)) { + return 'dev'; + } + + preg_match('{' . self::$modifierRegex . '(?:\+.*)?$}i', strtolower($version), $match); + + if (!empty($match[3])) { + return 'dev'; + } + + if (!empty($match[1])) { + if ('beta' === $match[1] || 'b' === $match[1]) { + return 'beta'; + } + if ('alpha' === $match[1] || 'a' === $match[1]) { + return 'alpha'; + } + if ('rc' === $match[1]) { + return 'RC'; + } + } + + return 'stable'; + } + + /** + * @param string $stability + * + * @return string + */ + public static function normalizeStability($stability) + { + $stability = strtolower((string) $stability); + + return $stability === 'rc' ? 'RC' : $stability; + } + + /** + * Normalizes a version string to be able to perform comparisons on it. + * + * @param string $version + * @param ?string $fullVersion optional complete version string to give more context + * + * @throws \UnexpectedValueException + * + * @return string + */ + public function normalize($version, $fullVersion = null) + { + $version = trim((string) $version); + $origVersion = $version; + if (null === $fullVersion) { + $fullVersion = $version; + } + + // strip off aliasing + if (preg_match('{^([^,\s]++) ++as ++([^,\s]++)$}', $version, $match)) { + $version = $match[1]; + } + + // strip off stability flag + if (preg_match('{@(?:' . self::$stabilitiesRegex . ')$}i', $version, $match)) { + $version = substr($version, 0, strlen($version) - strlen($match[0])); + } + + // normalize master/trunk/default branches to dev-name for BC with 1.x as these used to be valid constraints + if (\in_array($version, array('master', 'trunk', 'default'), true)) { + $version = 'dev-' . $version; + } + + // if requirement is branch-like, use full name + if (stripos($version, 'dev-') === 0) { + return 'dev-' . substr($version, 4); + } + + // strip off build metadata + if (preg_match('{^([^,\s+]++)\+[^\s]++$}', $version, $match)) { + $version = $match[1]; + } + + // match classical versioning + if (preg_match('{^v?(\d{1,5}+)(\.\d++)?(\.\d++)?(\.\d++)?' . self::$modifierRegex . '$}i', $version, $matches)) { + $version = $matches[1] + . (!empty($matches[2]) ? $matches[2] : '.0') + . (!empty($matches[3]) ? $matches[3] : '.0') + . (!empty($matches[4]) ? $matches[4] : '.0'); + $index = 5; + // match date(time) based versioning + } elseif (preg_match('{^v?(\d{4}(?:[.:-]?\d{2}){1,6}(?:[.:-]?\d{1,3}){0,2})' . self::$modifierRegex . '$}i', $version, $matches)) { + $version = (string) preg_replace('{\D}', '.', $matches[1]); + $index = 2; + } + + // add version modifiers if a version was matched + if (isset($index)) { + if (!empty($matches[$index])) { + if ('stable' === $matches[$index]) { + return $version; + } + $version .= '-' . $this->expandStability($matches[$index]) . (isset($matches[$index + 1]) && '' !== $matches[$index + 1] ? ltrim($matches[$index + 1], '.-') : ''); + } + + if (!empty($matches[$index + 2])) { + $version .= '-dev'; + } + + return $version; + } + + // match dev branches + if (preg_match('{(.*?)[.-]?dev$}i', $version, $match)) { + try { + $normalized = $this->normalizeBranch($match[1]); + // a branch ending with -dev is only valid if it is numeric + // if it gets prefixed with dev- it means the branch name should + // have had a dev- prefix already when passed to normalize + if (strpos($normalized, 'dev-') === false) { + return $normalized; + } + } catch (\Exception $e) { + } + } + + $extraMessage = ''; + if (preg_match('{ +as +' . preg_quote($version) . '(?:@(?:'.self::$stabilitiesRegex.'))?$}', $fullVersion)) { + $extraMessage = ' in "' . $fullVersion . '", the alias must be an exact version'; + } elseif (preg_match('{^' . preg_quote($version) . '(?:@(?:'.self::$stabilitiesRegex.'))? +as +}', $fullVersion)) { + $extraMessage = ' in "' . $fullVersion . '", the alias source must be an exact version, if it is a branch name you should prefix it with dev-'; + } + + throw new \UnexpectedValueException('Invalid version string "' . $origVersion . '"' . $extraMessage); + } + + /** + * Extract numeric prefix from alias, if it is in numeric format, suitable for version comparison. + * + * @param string $branch Branch name (e.g. 2.1.x-dev) + * + * @return string|false Numeric prefix if present (e.g. 2.1.) or false + */ + public function parseNumericAliasPrefix($branch) + { + if (preg_match('{^(?P(\d++\\.)*\d++)(?:\.x)?-dev$}i', (string) $branch, $matches)) { + return $matches['version'] . '.'; + } + + return false; + } + + /** + * Normalizes a branch name to be able to perform comparisons on it. + * + * @param string $name + * + * @return string + */ + public function normalizeBranch($name) + { + $name = trim((string) $name); + + if (preg_match('{^v?(\d++)(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?$}i', $name, $matches)) { + $version = ''; + for ($i = 1; $i < 5; ++$i) { + $version .= isset($matches[$i]) ? str_replace(array('*', 'X'), 'x', $matches[$i]) : '.x'; + } + + return str_replace('x', '9999999', $version) . '-dev'; + } + + return 'dev-' . $name; + } + + /** + * Normalizes a default branch name (i.e. master on git) to 9999999-dev. + * + * @param string $name + * + * @return string + * + * @deprecated No need to use this anymore in theory, Composer 2 does not normalize any branch names to 9999999-dev anymore + */ + public function normalizeDefaultBranch($name) + { + if ($name === 'dev-master' || $name === 'dev-default' || $name === 'dev-trunk') { + return '9999999-dev'; + } + + return (string) $name; + } + + /** + * Parses a constraint string into MultiConstraint and/or Constraint objects. + * + * @param string $constraints + * + * @return ConstraintInterface + */ + public function parseConstraints($constraints) + { + $prettyConstraint = (string) $constraints; + + $orConstraints = preg_split('{\s*\|\|?\s*}', trim((string) $constraints)); + if (false === $orConstraints) { + throw new \RuntimeException('Failed to preg_split string: '.$constraints); + } + $orGroups = array(); + + foreach ($orConstraints as $orConstraint) { + $andConstraints = preg_split('{(?< ,]) *(? 1) { + $constraintObjects = array(); + foreach ($andConstraints as $andConstraint) { + foreach ($this->parseConstraint($andConstraint) as $parsedAndConstraint) { + $constraintObjects[] = $parsedAndConstraint; + } + } + } else { + $constraintObjects = $this->parseConstraint($andConstraints[0]); + } + + if (1 === \count($constraintObjects)) { + $constraint = $constraintObjects[0]; + } else { + $constraint = new MultiConstraint($constraintObjects); + } + + $orGroups[] = $constraint; + } + + $parsedConstraint = MultiConstraint::create($orGroups, false); + + $parsedConstraint->setPrettyString($prettyConstraint); + + return $parsedConstraint; + } + + /** + * @param string $constraint + * + * @throws \UnexpectedValueException + * + * @return array + * + * @phpstan-return non-empty-array + */ + private function parseConstraint($constraint) + { + // strip off aliasing + if (preg_match('{^([^,\s]++) ++as ++([^,\s]++)$}', $constraint, $match)) { + $constraint = $match[1]; + } + + // strip @stability flags, and keep it for later use + if (preg_match('{^([^,\s]*?)@(' . self::$stabilitiesRegex . ')$}i', $constraint, $match)) { + $constraint = '' !== $match[1] ? $match[1] : '*'; + if ($match[2] !== 'stable') { + $stabilityModifier = $match[2]; + } + } + + // get rid of #refs as those are used by composer only + if (preg_match('{^(dev-[^,\s@]+?|[^,\s@]+?\.x-dev)#.+$}i', $constraint, $match)) { + $constraint = $match[1]; + } + + if (preg_match('{^(v)?[xX*](\.[xX*])*$}i', $constraint, $match)) { + if (!empty($match[1]) || !empty($match[2])) { + return array(new Constraint('>=', '0.0.0.0-dev')); + } + + return array(new MatchAllConstraint()); + } + + $versionRegex = 'v?(\d++)(?:\.(\d++))?(?:\.(\d++))?(?:\.(\d++))?(?:' . self::$modifierRegex . '|\.([xX*][.-]?dev))(?:\+[^\s]+)?'; + + // Tilde Range + // + // Like wildcard constraints, unsuffixed tilde constraints say that they must be greater than the previous + // version, to ensure that unstable instances of the current version are allowed. However, if a stability + // suffix is added to the constraint, then a >= match on the current version is used instead. + if (preg_match('{^~>?' . $versionRegex . '$}i', $constraint, $matches)) { + if (strpos($constraint, '~>') === 0) { + throw new \UnexpectedValueException( + 'Could not parse version constraint ' . $constraint . ': ' . + 'Invalid operator "~>", you probably meant to use the "~" operator' + ); + } + + // Work out which position in the version we are operating at + if (isset($matches[4]) && '' !== $matches[4] && null !== $matches[4]) { + $position = 4; + } elseif (isset($matches[3]) && '' !== $matches[3] && null !== $matches[3]) { + $position = 3; + } elseif (isset($matches[2]) && '' !== $matches[2] && null !== $matches[2]) { + $position = 2; + } else { + $position = 1; + } + + // when matching 2.x-dev or 3.0.x-dev we have to shift the second or third number, despite no second/third number matching above + if (!empty($matches[8])) { + $position++; + } + + // Calculate the stability suffix + $stabilitySuffix = ''; + if (empty($matches[5]) && empty($matches[7]) && empty($matches[8])) { + $stabilitySuffix .= '-dev'; + } + + $lowVersion = $this->normalize(substr($constraint . $stabilitySuffix, 1)); + $lowerBound = new Constraint('>=', $lowVersion); + + // For upper bound, we increment the position of one more significance, + // but highPosition = 0 would be illegal + $highPosition = max(1, $position - 1); + $highVersion = $this->manipulateVersionString($matches, $highPosition, 1) . '-dev'; + $upperBound = new Constraint('<', $highVersion); + + return array( + $lowerBound, + $upperBound, + ); + } + + // Caret Range + // + // Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple. + // In other words, this allows patch and minor updates for versions 1.0.0 and above, patch updates for + // versions 0.X >=0.1.0, and no updates for versions 0.0.X + if (preg_match('{^\^' . $versionRegex . '($)}i', $constraint, $matches)) { + // Work out which position in the version we are operating at + if ('0' !== $matches[1] || '' === $matches[2] || null === $matches[2]) { + $position = 1; + } elseif ('0' !== $matches[2] || '' === $matches[3] || null === $matches[3]) { + $position = 2; + } else { + $position = 3; + } + + // Calculate the stability suffix + $stabilitySuffix = ''; + if (empty($matches[5]) && empty($matches[7]) && empty($matches[8])) { + $stabilitySuffix .= '-dev'; + } + + $lowVersion = $this->normalize(substr($constraint . $stabilitySuffix, 1)); + $lowerBound = new Constraint('>=', $lowVersion); + + // For upper bound, we increment the position of one more significance, + // but highPosition = 0 would be illegal + $highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev'; + $upperBound = new Constraint('<', $highVersion); + + return array( + $lowerBound, + $upperBound, + ); + } + + // X Range + // + // Any of X, x, or * may be used to "stand in" for one of the numeric values in the [major, minor, patch] tuple. + // A partial version range is treated as an X-Range, so the special character is in fact optional. + if (preg_match('{^v?(\d++)(?:\.(\d++))?(?:\.(\d++))?(?:\.[xX*])++$}', $constraint, $matches)) { + if (isset($matches[3]) && '' !== $matches[3] && null !== $matches[3]) { + $position = 3; + } elseif (isset($matches[2]) && '' !== $matches[2] && null !== $matches[2]) { + $position = 2; + } else { + $position = 1; + } + + $lowVersion = $this->manipulateVersionString($matches, $position) . '-dev'; + $highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev'; + + if ($lowVersion === '0.0.0.0-dev') { + return array(new Constraint('<', $highVersion)); + } + + return array( + new Constraint('>=', $lowVersion), + new Constraint('<', $highVersion), + ); + } + + // Hyphen Range + // + // Specifies an inclusive set. If a partial version is provided as the first version in the inclusive range, + // then the missing pieces are replaced with zeroes. If a partial version is provided as the second version in + // the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but + // nothing that would be greater than the provided tuple parts. + if (preg_match('{^(?P' . $versionRegex . ') +- +(?P' . $versionRegex . ')($)}i', $constraint, $matches)) { + // Calculate the stability suffix + $lowStabilitySuffix = ''; + if (empty($matches[6]) && empty($matches[8]) && empty($matches[9])) { + $lowStabilitySuffix = '-dev'; + } + + $lowVersion = $this->normalize($matches['from']); + $lowerBound = new Constraint('>=', $lowVersion . $lowStabilitySuffix); + + $empty = function ($x) { + return ($x === 0 || $x === '0') ? false : empty($x); + }; + + if ((!$empty($matches[12]) && !$empty($matches[13])) || !empty($matches[15]) || !empty($matches[17]) || !empty($matches[18])) { + $highVersion = $this->normalize($matches['to']); + $upperBound = new Constraint('<=', $highVersion); + } else { + $highMatch = array('', $matches[11], $matches[12], $matches[13], $matches[14]); + + // validate to version + $this->normalize($matches['to']); + + $highVersion = $this->manipulateVersionString($highMatch, $empty($matches[12]) ? 1 : 2, 1) . '-dev'; + $upperBound = new Constraint('<', $highVersion); + } + + return array( + $lowerBound, + $upperBound, + ); + } + + // Basic Comparators + if (preg_match('{^(<>|!=|>=?|<=?|==?)?\s*(.*)}', $constraint, $matches)) { + try { + try { + $version = $this->normalize($matches[2]); + } catch (\UnexpectedValueException $e) { + // recover from an invalid constraint like foobar-dev which should be dev-foobar + // except if the constraint uses a known operator, in which case it must be a parse error + if (substr($matches[2], -4) === '-dev' && preg_match('{^[0-9a-zA-Z-./]+$}', $matches[2])) { + $version = $this->normalize('dev-'.substr($matches[2], 0, -4)); + } else { + throw $e; + } + } + + $op = $matches[1] ?: '='; + + if ($op !== '==' && $op !== '=' && !empty($stabilityModifier) && self::parseStability($version) === 'stable') { + $version .= '-' . $stabilityModifier; + } elseif ('<' === $op || '>=' === $op) { + if (!preg_match('/-' . self::$modifierRegex . '$/', strtolower($matches[2]))) { + if (strpos($matches[2], 'dev-') !== 0) { + $version .= '-dev'; + } + } + } + + return array(new Constraint($matches[1] ?: '=', $version)); + } catch (\Exception $e) { + } + } + + $message = 'Could not parse version constraint ' . $constraint; + if (isset($e)) { + $message .= ': ' . $e->getMessage(); + } + + throw new \UnexpectedValueException($message); + } + + /** + * Increment, decrement, or simply pad a version number. + * + * Support function for {@link parseConstraint()} + * + * @param array $matches Array with version parts in array indexes 1,2,3,4 + * @param int $position 1,2,3,4 - which segment of the version to increment/decrement + * @param int $increment + * @param string $pad The string to pad version parts after $position + * + * @return string|null The new version + * + * @phpstan-param string[] $matches + */ + private function manipulateVersionString(array $matches, $position, $increment = 0, $pad = '0') + { + for ($i = 4; $i > 0; --$i) { + if ($i > $position) { + $matches[$i] = $pad; + } elseif ($i === $position && $increment) { + $matches[$i] += $increment; + // If $matches[$i] was 0, carry the decrement + if ($matches[$i] < 0) { + $matches[$i] = $pad; + --$position; + + // Return null on a carry overflow + if ($i === 1) { + return null; + } + } + } + } + + return $matches[1] . '.' . $matches[2] . '.' . $matches[3] . '.' . $matches[4]; + } + + /** + * Expand shorthand stability string to long version. + * + * @param string $stability + * + * @return string + */ + private function expandStability($stability) + { + $stability = strtolower($stability); + + switch ($stability) { + case 'a': + return 'alpha'; + case 'b': + return 'beta'; + case 'p': + case 'pl': + return 'patch'; + case 'rc': + return 'RC'; + default: + return $stability; + } + } +} diff --git a/tools/php-cs-fixer/vendor/composer/xdebug-handler/CHANGELOG.md b/tools/php-cs-fixer/vendor/composer/xdebug-handler/CHANGELOG.md new file mode 100644 index 00000000..c5b5bcf4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/xdebug-handler/CHANGELOG.md @@ -0,0 +1,134 @@ +## [Unreleased] + +## [3.0.3] - 2022-02-25 + * Added: support for composer/pcre versions 2 and 3. + +## [3.0.2] - 2022-02-24 + * Fixed: regression in 3.0.1 affecting Xdebug 2 + +## [3.0.1] - 2022-01-04 + * Fixed: error when calling `isXdebugActive` before class instantiation. + +## [3.0.0] - 2021-12-23 + * Removed: support for legacy PHP versions (< PHP 7.2.5). + * Added: type declarations to arguments and return values. + * Added: strict typing to all classes. + +## [2.0.3] - 2021-12-08 + * Added: support, type annotations and refactoring for stricter PHPStan analysis. + +## [2.0.2] - 2021-07-31 + * Added: support for `xdebug_info('mode')` in Xdebug 3.1. + * Added: support for Psr\Log versions 2 and 3. + * Fixed: remove ini directives from non-cli HOST/PATH sections. + +## [2.0.1] - 2021-05-05 + * Fixed: don't restart if the cwd is a UNC path and cmd.exe will be invoked. + +## [2.0.0] - 2021-04-09 + * Break: this is a major release, see [UPGRADE.md](UPGRADE.md) for more information. + * Break: removed optional `$colorOption` constructor param and passthru fallback. + * Break: renamed `requiresRestart` param from `$isLoaded` to `$default`. + * Break: changed `restart` param `$command` from a string to an array. + * Added: support for Xdebug3 to only restart if Xdebug is not running with `xdebug.mode=off`. + * Added: `isXdebugActive()` method to determine if Xdebug is still running in the restart. + * Added: feature to bypass the shell in PHP-7.4+ by giving `proc_open` an array of arguments. + * Added: Process utility class to the API. + +## [1.4.6] - 2021-03-25 + * Fixed: fail restart if `proc_open` has been disabled in `disable_functions`. + * Fixed: enable Windows CTRL event handling in the restarted process. + +## [1.4.5] - 2020-11-13 + * Fixed: use `proc_open` when available for correct FD forwarding to the restarted process. + +## [1.4.4] - 2020-10-24 + * Fixed: exception if 'pcntl_signal' is disabled. + +## [1.4.3] - 2020-08-19 + * Fixed: restore SIGINT to default handler in restarted process if no other handler exists. + +## [1.4.2] - 2020-06-04 + * Fixed: ignore SIGINTs to let the restarted process handle them. + +## [1.4.1] - 2020-03-01 + * Fixed: restart fails if an ini file is empty. + +## [1.4.0] - 2019-11-06 + * Added: support for `NO_COLOR` environment variable: https://no-color.org + * Added: color support for Hyper terminal: https://github.com/zeit/hyper + * Fixed: correct capitalization of Xdebug (apparently). + * Fixed: improved handling for uopz extension. + +## [1.3.3] - 2019-05-27 + * Fixed: add environment changes to `$_ENV` if it is being used. + +## [1.3.2] - 2019-01-28 + * Fixed: exit call being blocked by uopz extension, resulting in application code running twice. + +## [1.3.1] - 2018-11-29 + * Fixed: fail restart if `passthru` has been disabled in `disable_functions`. + * Fixed: fail restart if an ini file cannot be opened, otherwise settings will be missing. + +## [1.3.0] - 2018-08-31 + * Added: `setPersistent` method to use environment variables for the restart. + * Fixed: improved debugging by writing output to stderr. + * Fixed: no restart when `php_ini_scanned_files` is not functional and is needed. + +## [1.2.1] - 2018-08-23 + * Fixed: fatal error with apc, when using `apc.mmap_file_mask`. + +## [1.2.0] - 2018-08-16 + * Added: debug information using `XDEBUG_HANDLER_DEBUG`. + * Added: fluent interface for setters. + * Added: `PhpConfig` helper class for calling PHP sub-processes. + * Added: `PHPRC` original value to restart stettings, for use in a restarted process. + * Changed: internal procedure to disable ini-scanning, using `-n` command-line option. + * Fixed: replaced `escapeshellarg` usage to avoid locale problems. + * Fixed: improved color-option handling to respect double-dash delimiter. + * Fixed: color-option handling regression from main script changes. + * Fixed: improved handling when checking main script. + * Fixed: handling for standard input, that never actually did anything. + * Fixed: fatal error when ctype extension is not available. + +## [1.1.0] - 2018-04-11 + * Added: `getRestartSettings` method for calling PHP processes in a restarted process. + * Added: API definition and @internal class annotations. + * Added: protected `requiresRestart` method for extending classes. + * Added: `setMainScript` method for applications that change the working directory. + * Changed: private `tmpIni` variable to protected for extending classes. + * Fixed: environment variables not available in $_SERVER when restored in the restart. + * Fixed: relative path problems caused by Phar::interceptFileFuncs. + * Fixed: incorrect handling when script file cannot be found. + +## [1.0.0] - 2018-03-08 + * Added: PSR3 logging for optional status output. + * Added: existing ini settings are merged to catch command-line overrides. + * Added: code, tests and other artefacts to decouple from Composer. + * Break: the following class was renamed: + - `Composer\XdebugHandler` -> `Composer\XdebugHandler\XdebugHandler` + +[Unreleased]: https://github.com/composer/xdebug-handler/compare/3.0.3...HEAD +[3.0.2]: https://github.com/composer/xdebug-handler/compare/3.0.2...3.0.3 +[3.0.2]: https://github.com/composer/xdebug-handler/compare/3.0.1...3.0.2 +[3.0.1]: https://github.com/composer/xdebug-handler/compare/3.0.0...3.0.1 +[3.0.0]: https://github.com/composer/xdebug-handler/compare/2.0.3...3.0.0 +[2.0.3]: https://github.com/composer/xdebug-handler/compare/2.0.2...2.0.3 +[2.0.2]: https://github.com/composer/xdebug-handler/compare/2.0.1...2.0.2 +[2.0.1]: https://github.com/composer/xdebug-handler/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/composer/xdebug-handler/compare/1.4.6...2.0.0 +[1.4.6]: https://github.com/composer/xdebug-handler/compare/1.4.5...1.4.6 +[1.4.5]: https://github.com/composer/xdebug-handler/compare/1.4.4...1.4.5 +[1.4.4]: https://github.com/composer/xdebug-handler/compare/1.4.3...1.4.4 +[1.4.3]: https://github.com/composer/xdebug-handler/compare/1.4.2...1.4.3 +[1.4.2]: https://github.com/composer/xdebug-handler/compare/1.4.1...1.4.2 +[1.4.1]: https://github.com/composer/xdebug-handler/compare/1.4.0...1.4.1 +[1.4.0]: https://github.com/composer/xdebug-handler/compare/1.3.3...1.4.0 +[1.3.3]: https://github.com/composer/xdebug-handler/compare/1.3.2...1.3.3 +[1.3.2]: https://github.com/composer/xdebug-handler/compare/1.3.1...1.3.2 +[1.3.1]: https://github.com/composer/xdebug-handler/compare/1.3.0...1.3.1 +[1.3.0]: https://github.com/composer/xdebug-handler/compare/1.2.1...1.3.0 +[1.2.1]: https://github.com/composer/xdebug-handler/compare/1.2.0...1.2.1 +[1.2.0]: https://github.com/composer/xdebug-handler/compare/1.1.0...1.2.0 +[1.1.0]: https://github.com/composer/xdebug-handler/compare/1.0.0...1.1.0 +[1.0.0]: https://github.com/composer/xdebug-handler/compare/d66f0d15cb57...1.0.0 diff --git a/tools/php-cs-fixer/vendor/composer/xdebug-handler/LICENSE b/tools/php-cs-fixer/vendor/composer/xdebug-handler/LICENSE new file mode 100644 index 00000000..963618a1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/xdebug-handler/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Composer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/composer/xdebug-handler/README.md b/tools/php-cs-fixer/vendor/composer/xdebug-handler/README.md new file mode 100644 index 00000000..56618fc1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/xdebug-handler/README.md @@ -0,0 +1,298 @@ +# composer/xdebug-handler + +[![packagist](https://img.shields.io/packagist/v/composer/xdebug-handler)](https://packagist.org/packages/composer/xdebug-handler) +[![Continuous Integration](https://github.com/composer/xdebug-handler/actions/workflows/continuous-integration.yml/badge.svg?branch=main)](https://github.com/composer/xdebug-handler/actions?query=branch:main) +![license](https://img.shields.io/github/license/composer/xdebug-handler.svg) +![php](https://img.shields.io/packagist/php-v/composer/xdebug-handler?colorB=8892BF) + +Restart a CLI process without loading the Xdebug extension, unless `xdebug.mode=off`. + +Originally written as part of [composer/composer](https://github.com/composer/composer), +now extracted and made available as a stand-alone library. + +### Version 3 + +Removed support for legacy PHP versions and added type declarations. + +Long term support for version 2 (PHP 5.3.2 - 7.2.4) follows [Composer 2.2 LTS](https://blog.packagist.com/composer-2-2/) policy. + +## Installation + +Install the latest version with: + +```bash +$ composer require composer/xdebug-handler +``` + +## Requirements + +* PHP 7.2.5 minimum, although using the latest PHP version is highly recommended. + +## Basic Usage +```php +use Composer\XdebugHandler\XdebugHandler; + +$xdebug = new XdebugHandler('myapp'); +$xdebug->check(); +unset($xdebug); +``` + +The constructor takes a single parameter, `$envPrefix`, which is upper-cased and prepended to default base values to create two distinct environment variables. The above example enables the use of: + +- `MYAPP_ALLOW_XDEBUG=1` to override automatic restart and allow Xdebug +- `MYAPP_ORIGINAL_INIS` to obtain ini file locations in a restarted process + +## Advanced Usage + +* [How it works](#how-it-works) +* [Limitations](#limitations) +* [Helper methods](#helper-methods) +* [Setter methods](#setter-methods) +* [Process configuration](#process-configuration) +* [Troubleshooting](#troubleshooting) +* [Extending the library](#extending-the-library) + +### How it works + +A temporary ini file is created from the loaded (and scanned) ini files, with any references to the Xdebug extension commented out. Current ini settings are merged, so that most ini settings made on the command-line or by the application are included (see [Limitations](#limitations)) + +* `MYAPP_ALLOW_XDEBUG` is set with internal data to flag and use in the restart. +* The command-line and environment are [configured](#process-configuration) for the restart. +* The application is restarted in a new process. + * The restart settings are stored in the environment. + * `MYAPP_ALLOW_XDEBUG` is unset. + * The application runs and exits. +* The main process exits with the exit code from the restarted process. + +#### Signal handling +Asynchronous signal handling is automatically enabled if the pcntl extension is loaded. `SIGINT` is set to `SIG_IGN` in the parent +process and restored to `SIG_DFL` in the restarted process (if no other handler has been set). + +From PHP 7.4 on Windows, `CTRL+C` and `CTRL+BREAK` handling is automatically enabled in the restarted process and ignored in the parent process. + +### Limitations +There are a few things to be aware of when running inside a restarted process. + +* Extensions set on the command-line will not be loaded. +* Ini file locations will be reported as per the restart - see [getAllIniFiles()](#getallinifiles). +* Php sub-processes may be loaded with Xdebug enabled - see [Process configuration](#process-configuration). + +### Helper methods +These static methods provide information from the current process, regardless of whether it has been restarted or not. + +#### _getAllIniFiles(): array_ +Returns an array of the original ini file locations. Use this instead of calling `php_ini_loaded_file` and `php_ini_scanned_files`, which will report the wrong values in a restarted process. + +```php +use Composer\XdebugHandler\XdebugHandler; + +$files = XdebugHandler::getAllIniFiles(); + +# $files[0] always exists, it could be an empty string +$loadedIni = array_shift($files); +$scannedInis = $files; +``` + +These locations are also available in the `MYAPP_ORIGINAL_INIS` environment variable. This is a path-separated string comprising the location returned from `php_ini_loaded_file`, which could be empty, followed by locations parsed from calling `php_ini_scanned_files`. + +#### _getRestartSettings(): ?array_ +Returns an array of settings that can be used with PHP [sub-processes](#sub-processes), or null if the process was not restarted. + +```php +use Composer\XdebugHandler\XdebugHandler; + +$settings = XdebugHandler::getRestartSettings(); +/** + * $settings: array (if the current process was restarted, + * or called with the settings from a previous restart), or null + * + * 'tmpIni' => the temporary ini file used in the restart (string) + * 'scannedInis' => if there were any scanned inis (bool) + * 'scanDir' => the original PHP_INI_SCAN_DIR value (false|string) + * 'phprc' => the original PHPRC value (false|string) + * 'inis' => the original inis from getAllIniFiles (array) + * 'skipped' => the skipped version from getSkippedVersion (string) + */ +``` + +#### _getSkippedVersion(): string_ +Returns the Xdebug version string that was skipped by the restart, or an empty string if there was no restart (or Xdebug is still loaded, perhaps by an extending class restarting for a reason other than removing Xdebug). + +```php +use Composer\XdebugHandler\XdebugHandler; + +$version = XdebugHandler::getSkippedVersion(); +# $version: '3.1.1' (for example), or an empty string +``` + +#### _isXdebugActive(): bool_ +Returns true if Xdebug is loaded and is running in an active mode (if it supports modes). Returns false if Xdebug is not loaded, or it is running with `xdebug.mode=off`. + +### Setter methods +These methods implement a fluent interface and must be called before the main `check()` method. + +#### _setLogger(LoggerInterface $logger): self_ +Enables the output of status messages to an external PSR3 logger. All messages are reported with either `DEBUG` or `WARNING` log levels. For example (showing the level and message): + +``` +// No restart +DEBUG Checking MYAPP_ALLOW_XDEBUG +DEBUG The Xdebug extension is loaded (3.1.1) xdebug.mode=off +DEBUG No restart (APP_ALLOW_XDEBUG=0) Allowed by xdebug.mode + +// Restart overridden +DEBUG Checking MYAPP_ALLOW_XDEBUG +DEBUG The Xdebug extension is loaded (3.1.1) xdebug.mode=coverage,debug,develop +DEBUG No restart (MYAPP_ALLOW_XDEBUG=1) + +// Failed restart +DEBUG Checking MYAPP_ALLOW_XDEBUG +DEBUG The Xdebug extension is loaded (3.1.0) +WARNING No restart (Unable to create temp ini file at: ...) +``` + +Status messages can also be output with `XDEBUG_HANDLER_DEBUG`. See [Troubleshooting](#troubleshooting). + +#### _setMainScript(string $script): self_ +Sets the location of the main script to run in the restart. This is only needed in more esoteric use-cases, or if the `argv[0]` location is inaccessible. The script name `--` is supported for standard input. + +#### _setPersistent(): self_ +Configures the restart using [persistent settings](#persistent-settings), so that Xdebug is not loaded in any sub-process. + +Use this method if your application invokes one or more PHP sub-process and the Xdebug extension is not needed. This avoids the overhead of implementing specific [sub-process](#sub-processes) strategies. + +Alternatively, this method can be used to set up a default _Xdebug-free_ environment which can be changed if a sub-process requires Xdebug, then restored afterwards: + +```php +function SubProcessWithXdebug() +{ + $phpConfig = new Composer\XdebugHandler\PhpConfig(); + + # Set the environment to the original configuration + $phpConfig->useOriginal(); + + # run the process with Xdebug loaded + ... + + # Restore Xdebug-free environment + $phpConfig->usePersistent(); +} +``` + +### Process configuration +The library offers two strategies to invoke a new PHP process without loading Xdebug, using either _standard_ or _persistent_ settings. Note that this is only important if the application calls a PHP sub-process. + +#### Standard settings +Uses command-line options to remove Xdebug from the new process only. + +* The -n option is added to the command-line. This tells PHP not to scan for additional inis. +* The temporary ini is added to the command-line with the -c option. + +>_If the new process calls a PHP sub-process, Xdebug will be loaded in that sub-process (unless it implements xdebug-handler, in which case there will be another restart)._ + +This is the default strategy used in the restart. + +#### Persistent settings +Uses environment variables to remove Xdebug from the new process and persist these settings to any sub-process. + +* `PHP_INI_SCAN_DIR` is set to an empty string. This tells PHP not to scan for additional inis. +* `PHPRC` is set to the temporary ini. + +>_If the new process calls a PHP sub-process, Xdebug will not be loaded in that sub-process._ + +This strategy can be used in the restart by calling [setPersistent()](#setpersistent). + +#### Sub-processes +The `PhpConfig` helper class makes it easy to invoke a PHP sub-process (with or without Xdebug loaded), regardless of whether there has been a restart. + +Each of its methods returns an array of PHP options (to add to the command-line) and sets up the environment for the required strategy. The [getRestartSettings()](#getrestartsettings) method is used internally. + +* `useOriginal()` - Xdebug will be loaded in the new process. +* `useStandard()` - Xdebug will **not** be loaded in the new process - see [standard settings](#standard-settings). +* `userPersistent()` - Xdebug will **not** be loaded in the new process - see [persistent settings](#persistent-settings) + +If there was no restart, an empty options array is returned and the environment is not changed. + +```php +use Composer\XdebugHandler\PhpConfig; + +$config = new PhpConfig; + +$options = $config->useOriginal(); +# $options: empty array +# environment: PHPRC and PHP_INI_SCAN_DIR set to original values + +$options = $config->useStandard(); +# $options: [-n, -c, tmpIni] +# environment: PHPRC and PHP_INI_SCAN_DIR set to original values + +$options = $config->usePersistent(); +# $options: empty array +# environment: PHPRC=tmpIni, PHP_INI_SCAN_DIR='' +``` + +### Troubleshooting +The following environment settings can be used to troubleshoot unexpected behavior: + +* `XDEBUG_HANDLER_DEBUG=1` Outputs status messages to `STDERR`, if it is defined, irrespective of any PSR3 logger. Each message is prefixed `xdebug-handler[pid]`, where pid is the process identifier. + +* `XDEBUG_HANDLER_DEBUG=2` As above, but additionally saves the temporary ini file and reports its location in a status message. + +### Extending the library +The API is defined by classes and their accessible elements that are not annotated as @internal. The main class has two protected methods that can be overridden to provide additional functionality: + +#### _requiresRestart(bool $default): bool_ +By default the process will restart if Xdebug is loaded and not running with `xdebug.mode=off`. Extending this method allows an application to decide, by returning a boolean (or equivalent) value. +It is only called if `MYAPP_ALLOW_XDEBUG` is empty, so it will not be called in the restarted process (where this variable contains internal data), or if the restart has been overridden. + +Note that the [setMainScript()](#setmainscriptscript) and [setPersistent()](#setpersistent) setters can be used here, if required. + +#### _restart(array $command): void_ +An application can extend this to modify the temporary ini file, its location given in the `tmpIni` property. New settings can be safely appended to the end of the data, which is `PHP_EOL` terminated. + +The `$command` parameter is an array of unescaped command-line arguments that will be used for the new process. + +Remember to finish with `parent::restart($command)`. + +#### Example +This example demonstrates two ways to extend basic functionality: + +* To avoid the overhead of spinning up a new process, the restart is skipped if a simple help command is requested. + +* The application needs write-access to phar files, so it will force a restart if `phar.readonly` is set (regardless of whether Xdebug is loaded) and change this value in the temporary ini file. + +```php +use Composer\XdebugHandler\XdebugHandler; +use MyApp\Command; + +class MyRestarter extends XdebugHandler +{ + private $required; + + protected function requiresRestart(bool $default): bool + { + if (Command::isHelp()) { + # No need to disable Xdebug for this + return false; + } + + $this->required = (bool) ini_get('phar.readonly'); + return $this->required || $default; + } + + protected function restart(array $command): void + { + if ($this->required) { + # Add required ini setting to tmpIni + $content = file_get_contents($this->tmpIni); + $content .= 'phar.readonly=0'.PHP_EOL; + file_put_contents($this->tmpIni, $content); + } + + parent::restart($command); + } +} +``` + +## License +composer/xdebug-handler is licensed under the MIT License, see the LICENSE file for details. diff --git a/tools/php-cs-fixer/vendor/composer/xdebug-handler/composer.json b/tools/php-cs-fixer/vendor/composer/xdebug-handler/composer.json new file mode 100644 index 00000000..6b649dab --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/xdebug-handler/composer.json @@ -0,0 +1,44 @@ +{ + "name": "composer/xdebug-handler", + "description": "Restarts a process without Xdebug.", + "type": "library", + "license": "MIT", + "keywords": [ + "xdebug", + "performance" + ], + "authors": [ + { + "name": "John Stevenson", + "email": "john-stevenson@blueyonder.co.uk" + } + ], + "support": { + "irc": "irc://irc.freenode.org/composer", + "issues": "https://github.com/composer/xdebug-handler/issues" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "psr/log": "^1 || ^2 || ^3", + "composer/pcre": "^1 || ^2 || ^3" + }, + "require-dev": { + "symfony/phpunit-bridge": "^6.0", + "phpstan/phpstan": "^1.0", + "phpstan/phpstan-strict-rules": "^1.1" + }, + "autoload": { + "psr-4": { + "Composer\\XdebugHandler\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "Composer\\XdebugHandler\\Tests\\": "tests" + } + }, + "scripts": { + "test": "@php vendor/bin/simple-phpunit", + "phpstan": "@php vendor/bin/phpstan analyse" + } +} diff --git a/tools/php-cs-fixer/vendor/composer/xdebug-handler/src/PhpConfig.php b/tools/php-cs-fixer/vendor/composer/xdebug-handler/src/PhpConfig.php new file mode 100644 index 00000000..7edac888 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/xdebug-handler/src/PhpConfig.php @@ -0,0 +1,91 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\XdebugHandler; + +/** + * @author John Stevenson + * + * @phpstan-type restartData array{tmpIni: string, scannedInis: bool, scanDir: false|string, phprc: false|string, inis: string[], skipped: string} + */ +class PhpConfig +{ + /** + * Use the original PHP configuration + * + * @return string[] Empty array of PHP cli options + */ + public function useOriginal(): array + { + $this->getDataAndReset(); + return []; + } + + /** + * Use standard restart settings + * + * @return string[] PHP cli options + */ + public function useStandard(): array + { + $data = $this->getDataAndReset(); + if ($data !== null) { + return ['-n', '-c', $data['tmpIni']]; + } + + return []; + } + + /** + * Use environment variables to persist settings + * + * @return string[] Empty array of PHP cli options + */ + public function usePersistent(): array + { + $data = $this->getDataAndReset(); + if ($data !== null) { + $this->updateEnv('PHPRC', $data['tmpIni']); + $this->updateEnv('PHP_INI_SCAN_DIR', ''); + } + + return []; + } + + /** + * Returns restart data if available and resets the environment + * + * @phpstan-return restartData|null + */ + private function getDataAndReset(): ?array + { + $data = XdebugHandler::getRestartSettings(); + if ($data !== null) { + $this->updateEnv('PHPRC', $data['phprc']); + $this->updateEnv('PHP_INI_SCAN_DIR', $data['scanDir']); + } + + return $data; + } + + /** + * Updates a restart settings value in the environment + * + * @param string $name + * @param string|false $value + */ + private function updateEnv(string $name, $value): void + { + Process::setEnv($name, false !== $value ? $value : null); + } +} diff --git a/tools/php-cs-fixer/vendor/composer/xdebug-handler/src/Process.php b/tools/php-cs-fixer/vendor/composer/xdebug-handler/src/Process.php new file mode 100644 index 00000000..c612200b --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/xdebug-handler/src/Process.php @@ -0,0 +1,118 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Composer\XdebugHandler; + +use Composer\Pcre\Preg; + +/** + * Process utility functions + * + * @author John Stevenson + */ +class Process +{ + /** + * Escapes a string to be used as a shell argument. + * + * From https://github.com/johnstevenson/winbox-args + * MIT Licensed (c) John Stevenson + * + * @param string $arg The argument to be escaped + * @param bool $meta Additionally escape cmd.exe meta characters + * @param bool $module The argument is the module to invoke + */ + public static function escape(string $arg, bool $meta = true, bool $module = false): string + { + if (!defined('PHP_WINDOWS_VERSION_BUILD')) { + return "'".str_replace("'", "'\\''", $arg)."'"; + } + + $quote = strpbrk($arg, " \t") !== false || $arg === ''; + + $arg = Preg::replace('/(\\\\*)"/', '$1$1\\"', $arg, -1, $dquotes); + + if ($meta) { + $meta = $dquotes || Preg::isMatch('/%[^%]+%/', $arg); + + if (!$meta) { + $quote = $quote || strpbrk($arg, '^&|<>()') !== false; + } elseif ($module && !$dquotes && $quote) { + $meta = false; + } + } + + if ($quote) { + $arg = '"'.(Preg::replace('/(\\\\*)$/', '$1$1', $arg)).'"'; + } + + if ($meta) { + $arg = Preg::replace('/(["^&|<>()%])/', '^$1', $arg); + } + + return $arg; + } + + /** + * Escapes an array of arguments that make up a shell command + * + * @param string[] $args Argument list, with the module name first + */ + public static function escapeShellCommand(array $args): string + { + $command = ''; + $module = array_shift($args); + + if ($module !== null) { + $command = self::escape($module, true, true); + + foreach ($args as $arg) { + $command .= ' '.self::escape($arg); + } + } + + return $command; + } + + /** + * Makes putenv environment changes available in $_SERVER and $_ENV + * + * @param string $name + * @param ?string $value A null value unsets the variable + */ + public static function setEnv(string $name, ?string $value = null): bool + { + $unset = null === $value; + + if (!putenv($unset ? $name : $name.'='.$value)) { + return false; + } + + if ($unset) { + unset($_SERVER[$name]); + } else { + $_SERVER[$name] = $value; + } + + // Update $_ENV if it is being used + if (false !== stripos((string) ini_get('variables_order'), 'E')) { + if ($unset) { + unset($_ENV[$name]); + } else { + $_ENV[$name] = $value; + } + } + + return true; + } +} diff --git a/tools/php-cs-fixer/vendor/composer/xdebug-handler/src/Status.php b/tools/php-cs-fixer/vendor/composer/xdebug-handler/src/Status.php new file mode 100644 index 00000000..b434f859 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/xdebug-handler/src/Status.php @@ -0,0 +1,203 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Composer\XdebugHandler; + +use Psr\Log\LoggerInterface; +use Psr\Log\LogLevel; + +/** + * @author John Stevenson + * @internal + */ +class Status +{ + const ENV_RESTART = 'XDEBUG_HANDLER_RESTART'; + const CHECK = 'Check'; + const ERROR = 'Error'; + const INFO = 'Info'; + const NORESTART = 'NoRestart'; + const RESTART = 'Restart'; + const RESTARTING = 'Restarting'; + const RESTARTED = 'Restarted'; + + /** @var bool */ + private $debug; + + /** @var string */ + private $envAllowXdebug; + + /** @var string|null */ + private $loaded; + + /** @var LoggerInterface|null */ + private $logger; + + /** @var bool */ + private $modeOff; + + /** @var float */ + private $time; + + /** + * @param string $envAllowXdebug Prefixed _ALLOW_XDEBUG name + * @param bool $debug Whether debug output is required + */ + public function __construct(string $envAllowXdebug, bool $debug) + { + $start = getenv(self::ENV_RESTART); + Process::setEnv(self::ENV_RESTART); + $this->time = is_numeric($start) ? round((microtime(true) - $start) * 1000) : 0; + + $this->envAllowXdebug = $envAllowXdebug; + $this->debug = $debug && defined('STDERR'); + $this->modeOff = false; + } + + /** + * Activates status message output to a PSR3 logger + * + * @return void + */ + public function setLogger(LoggerInterface $logger): void + { + $this->logger = $logger; + } + + /** + * Calls a handler method to report a message + * + * @throws \InvalidArgumentException If $op is not known + */ + public function report(string $op, ?string $data): void + { + if ($this->logger !== null || $this->debug) { + $callable = [$this, 'report'.$op]; + + if (!is_callable($callable)) { + throw new \InvalidArgumentException('Unknown op handler: '.$op); + } + + $params = $data !== null ? [$data] : []; + call_user_func_array($callable, $params); + } + } + + /** + * Outputs a status message + */ + private function output(string $text, ?string $level = null): void + { + if ($this->logger !== null) { + $this->logger->log($level !== null ? $level: LogLevel::DEBUG, $text); + } + + if ($this->debug) { + fwrite(STDERR, sprintf('xdebug-handler[%d] %s', getmypid(), $text.PHP_EOL)); + } + } + + /** + * Checking status message + */ + private function reportCheck(string $loaded): void + { + list($version, $mode) = explode('|', $loaded); + + if ($version !== '') { + $this->loaded = '('.$version.')'.($mode !== '' ? ' xdebug.mode='.$mode : ''); + } + $this->modeOff = $mode === 'off'; + $this->output('Checking '.$this->envAllowXdebug); + } + + /** + * Error status message + */ + private function reportError(string $error): void + { + $this->output(sprintf('No restart (%s)', $error), LogLevel::WARNING); + } + + /** + * Info status message + */ + private function reportInfo(string $info): void + { + $this->output($info); + } + + /** + * No restart status message + */ + private function reportNoRestart(): void + { + $this->output($this->getLoadedMessage()); + + if ($this->loaded !== null) { + $text = sprintf('No restart (%s)', $this->getEnvAllow()); + if (!((bool) getenv($this->envAllowXdebug))) { + $text .= ' Allowed by '.($this->modeOff ? 'xdebug.mode' : 'application'); + } + $this->output($text); + } + } + + /** + * Restart status message + */ + private function reportRestart(): void + { + $this->output($this->getLoadedMessage()); + Process::setEnv(self::ENV_RESTART, (string) microtime(true)); + } + + /** + * Restarted status message + */ + private function reportRestarted(): void + { + $loaded = $this->getLoadedMessage(); + $text = sprintf('Restarted (%d ms). %s', $this->time, $loaded); + $level = $this->loaded !== null ? LogLevel::WARNING : null; + $this->output($text, $level); + } + + /** + * Restarting status message + */ + private function reportRestarting(string $command): void + { + $text = sprintf('Process restarting (%s)', $this->getEnvAllow()); + $this->output($text); + $text = 'Running '.$command; + $this->output($text); + } + + /** + * Returns the _ALLOW_XDEBUG environment variable as name=value + */ + private function getEnvAllow(): string + { + return $this->envAllowXdebug.'='.getenv($this->envAllowXdebug); + } + + /** + * Returns the Xdebug status and version + */ + private function getLoadedMessage(): string + { + $loaded = $this->loaded !== null ? sprintf('loaded %s', $this->loaded) : 'not loaded'; + return 'The Xdebug extension is '.$loaded; + } +} diff --git a/tools/php-cs-fixer/vendor/composer/xdebug-handler/src/XdebugHandler.php b/tools/php-cs-fixer/vendor/composer/xdebug-handler/src/XdebugHandler.php new file mode 100644 index 00000000..9052bfa4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/composer/xdebug-handler/src/XdebugHandler.php @@ -0,0 +1,668 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Composer\XdebugHandler; + +use Composer\Pcre\Preg; +use Psr\Log\LoggerInterface; + +/** + * @author John Stevenson + * + * @phpstan-import-type restartData from PhpConfig + */ +class XdebugHandler +{ + const SUFFIX_ALLOW = '_ALLOW_XDEBUG'; + const SUFFIX_INIS = '_ORIGINAL_INIS'; + const RESTART_ID = 'internal'; + const RESTART_SETTINGS = 'XDEBUG_HANDLER_SETTINGS'; + const DEBUG = 'XDEBUG_HANDLER_DEBUG'; + + /** @var string|null */ + protected $tmpIni; + + /** @var bool */ + private static $inRestart; + + /** @var string */ + private static $name; + + /** @var string|null */ + private static $skipped; + + /** @var bool */ + private static $xdebugActive; + + /** @var string|null */ + private static $xdebugMode; + + /** @var string|null */ + private static $xdebugVersion; + + /** @var bool */ + private $cli; + + /** @var string|null */ + private $debug; + + /** @var string */ + private $envAllowXdebug; + + /** @var string */ + private $envOriginalInis; + + /** @var bool */ + private $persistent; + + /** @var string|null */ + private $script; + + /** @var Status */ + private $statusWriter; + + /** + * Constructor + * + * The $envPrefix is used to create distinct environment variables. It is + * uppercased and prepended to the default base values. For example 'myapp' + * would result in MYAPP_ALLOW_XDEBUG and MYAPP_ORIGINAL_INIS. + * + * @param string $envPrefix Value used in environment variables + * @throws \RuntimeException If the parameter is invalid + */ + public function __construct(string $envPrefix) + { + if ($envPrefix === '') { + throw new \RuntimeException('Invalid constructor parameter'); + } + + self::$name = strtoupper($envPrefix); + $this->envAllowXdebug = self::$name.self::SUFFIX_ALLOW; + $this->envOriginalInis = self::$name.self::SUFFIX_INIS; + + self::setXdebugDetails(); + self::$inRestart = false; + + if ($this->cli = PHP_SAPI === 'cli') { + $this->debug = (string) getenv(self::DEBUG); + } + + $this->statusWriter = new Status($this->envAllowXdebug, (bool) $this->debug); + } + + /** + * Activates status message output to a PSR3 logger + */ + public function setLogger(LoggerInterface $logger): self + { + $this->statusWriter->setLogger($logger); + return $this; + } + + /** + * Sets the main script location if it cannot be called from argv + */ + public function setMainScript(string $script): self + { + $this->script = $script; + return $this; + } + + /** + * Persist the settings to keep Xdebug out of sub-processes + */ + public function setPersistent(): self + { + $this->persistent = true; + return $this; + } + + /** + * Checks if Xdebug is loaded and the process needs to be restarted + * + * This behaviour can be disabled by setting the MYAPP_ALLOW_XDEBUG + * environment variable to 1. This variable is used internally so that + * the restarted process is created only once. + */ + public function check(): void + { + $this->notify(Status::CHECK, self::$xdebugVersion.'|'.self::$xdebugMode); + $envArgs = explode('|', (string) getenv($this->envAllowXdebug)); + + if (!((bool) $envArgs[0]) && $this->requiresRestart(self::$xdebugActive)) { + // Restart required + $this->notify(Status::RESTART); + + if ($this->prepareRestart()) { + $command = $this->getCommand(); + $this->restart($command); + } + return; + } + + if (self::RESTART_ID === $envArgs[0] && count($envArgs) === 5) { + // Restarted, so unset environment variable and use saved values + $this->notify(Status::RESTARTED); + + Process::setEnv($this->envAllowXdebug); + self::$inRestart = true; + + if (self::$xdebugVersion === null) { + // Skipped version is only set if Xdebug is not loaded + self::$skipped = $envArgs[1]; + } + + $this->tryEnableSignals(); + + // Put restart settings in the environment + $this->setEnvRestartSettings($envArgs); + return; + } + + $this->notify(Status::NORESTART); + $settings = self::getRestartSettings(); + + if ($settings !== null) { + // Called with existing settings, so sync our settings + $this->syncSettings($settings); + } + } + + /** + * Returns an array of php.ini locations with at least one entry + * + * The equivalent of calling php_ini_loaded_file then php_ini_scanned_files. + * The loaded ini location is the first entry and may be empty. + * + * @return string[] + */ + public static function getAllIniFiles(): array + { + if (self::$name !== null) { + $env = getenv(self::$name.self::SUFFIX_INIS); + + if (false !== $env) { + return explode(PATH_SEPARATOR, $env); + } + } + + $paths = [(string) php_ini_loaded_file()]; + $scanned = php_ini_scanned_files(); + + if ($scanned !== false) { + $paths = array_merge($paths, array_map('trim', explode(',', $scanned))); + } + + return $paths; + } + + /** + * Returns an array of restart settings or null + * + * Settings will be available if the current process was restarted, or + * called with the settings from an existing restart. + * + * @phpstan-return restartData|null + */ + public static function getRestartSettings(): ?array + { + $envArgs = explode('|', (string) getenv(self::RESTART_SETTINGS)); + + if (count($envArgs) !== 6 + || (!self::$inRestart && php_ini_loaded_file() !== $envArgs[0])) { + return null; + } + + return [ + 'tmpIni' => $envArgs[0], + 'scannedInis' => (bool) $envArgs[1], + 'scanDir' => '*' === $envArgs[2] ? false : $envArgs[2], + 'phprc' => '*' === $envArgs[3] ? false : $envArgs[3], + 'inis' => explode(PATH_SEPARATOR, $envArgs[4]), + 'skipped' => $envArgs[5], + ]; + } + + /** + * Returns the Xdebug version that triggered a successful restart + */ + public static function getSkippedVersion(): string + { + return (string) self::$skipped; + } + + /** + * Returns whether Xdebug is loaded and active + * + * true: if Xdebug is loaded and is running in an active mode. + * false: if Xdebug is not loaded, or it is running with xdebug.mode=off. + */ + public static function isXdebugActive(): bool + { + self::setXdebugDetails(); + return self::$xdebugActive; + } + + /** + * Allows an extending class to decide if there should be a restart + * + * The default is to restart if Xdebug is loaded and its mode is not "off". + */ + protected function requiresRestart(bool $default): bool + { + return $default; + } + + /** + * Allows an extending class to access the tmpIni + * + * @param string[] $command * + */ + protected function restart(array $command): void + { + $this->doRestart($command); + } + + /** + * Executes the restarted command then deletes the tmp ini + * + * @param string[] $command + * @phpstan-return never + */ + private function doRestart(array $command): void + { + $this->tryEnableSignals(); + $this->notify(Status::RESTARTING, implode(' ', $command)); + + if (PHP_VERSION_ID >= 70400) { + $cmd = $command; + } else { + $cmd = Process::escapeShellCommand($command); + if (defined('PHP_WINDOWS_VERSION_BUILD')) { + // Outer quotes required on cmd string below PHP 8 + $cmd = '"'.$cmd.'"'; + } + } + + $process = proc_open($cmd, [], $pipes); + if (is_resource($process)) { + $exitCode = proc_close($process); + } + + if (!isset($exitCode)) { + // Unlikely that php or the default shell cannot be invoked + $this->notify(Status::ERROR, 'Unable to restart process'); + $exitCode = -1; + } else { + $this->notify(Status::INFO, 'Restarted process exited '.$exitCode); + } + + if ($this->debug === '2') { + $this->notify(Status::INFO, 'Temp ini saved: '.$this->tmpIni); + } else { + @unlink((string) $this->tmpIni); + } + + exit($exitCode); + } + + /** + * Returns true if everything was written for the restart + * + * If any of the following fails (however unlikely) we must return false to + * stop potential recursion: + * - tmp ini file creation + * - environment variable creation + */ + private function prepareRestart(): bool + { + $error = null; + $iniFiles = self::getAllIniFiles(); + $scannedInis = count($iniFiles) > 1; + $tmpDir = sys_get_temp_dir(); + + if (!$this->cli) { + $error = 'Unsupported SAPI: '.PHP_SAPI; + } elseif (!$this->checkConfiguration($info)) { + $error = $info; + } elseif (!$this->checkMainScript()) { + $error = 'Unable to access main script: '.$this->script; + } elseif (!$this->writeTmpIni($iniFiles, $tmpDir, $error)) { + $error = $error !== null ? $error : 'Unable to create temp ini file at: '.$tmpDir; + } elseif (!$this->setEnvironment($scannedInis, $iniFiles)) { + $error = 'Unable to set environment variables'; + } + + if ($error !== null) { + $this->notify(Status::ERROR, $error); + } + + return $error === null; + } + + /** + * Returns true if the tmp ini file was written + * + * @param string[] $iniFiles All ini files used in the current process + */ + private function writeTmpIni(array $iniFiles, string $tmpDir, ?string &$error): bool + { + if (($tmpfile = @tempnam($tmpDir, '')) === false) { + return false; + } + + $this->tmpIni = $tmpfile; + + // $iniFiles has at least one item and it may be empty + if ($iniFiles[0] === '') { + array_shift($iniFiles); + } + + $content = ''; + $sectionRegex = '/^\s*\[(?:PATH|HOST)\s*=/mi'; + $xdebugRegex = '/^\s*(zend_extension\s*=.*xdebug.*)$/mi'; + + foreach ($iniFiles as $file) { + // Check for inaccessible ini files + if (($data = @file_get_contents($file)) === false) { + $error = 'Unable to read ini: '.$file; + return false; + } + // Check and remove directives after HOST and PATH sections + if (Preg::isMatchWithOffsets($sectionRegex, $data, $matches, PREG_OFFSET_CAPTURE)) { + $data = substr($data, 0, $matches[0][1]); + } + $content .= Preg::replace($xdebugRegex, ';$1', $data).PHP_EOL; + } + + // Merge loaded settings into our ini content, if it is valid + $config = parse_ini_string($content); + $loaded = ini_get_all(null, false); + + if (false === $config || false === $loaded) { + $error = 'Unable to parse ini data'; + return false; + } + + $content .= $this->mergeLoadedConfig($loaded, $config); + + // Work-around for https://bugs.php.net/bug.php?id=75932 + $content .= 'opcache.enable_cli=0'.PHP_EOL; + + return (bool) @file_put_contents($this->tmpIni, $content); + } + + /** + * Returns the command line arguments for the restart + * + * @return string[] + */ + private function getCommand(): array + { + $php = [PHP_BINARY]; + $args = array_slice($_SERVER['argv'], 1); + + if (!$this->persistent) { + // Use command-line options + array_push($php, '-n', '-c', $this->tmpIni); + } + + return array_merge($php, [$this->script], $args); + } + + /** + * Returns true if the restart environment variables were set + * + * No need to update $_SERVER since this is set in the restarted process. + * + * @param string[] $iniFiles All ini files used in the current process + */ + private function setEnvironment(bool $scannedInis, array $iniFiles): bool + { + $scanDir = getenv('PHP_INI_SCAN_DIR'); + $phprc = getenv('PHPRC'); + + // Make original inis available to restarted process + if (!putenv($this->envOriginalInis.'='.implode(PATH_SEPARATOR, $iniFiles))) { + return false; + } + + if ($this->persistent) { + // Use the environment to persist the settings + if (!putenv('PHP_INI_SCAN_DIR=') || !putenv('PHPRC='.$this->tmpIni)) { + return false; + } + } + + // Flag restarted process and save values for it to use + $envArgs = [ + self::RESTART_ID, + self::$xdebugVersion, + (int) $scannedInis, + false === $scanDir ? '*' : $scanDir, + false === $phprc ? '*' : $phprc, + ]; + + return putenv($this->envAllowXdebug.'='.implode('|', $envArgs)); + } + + /** + * Logs status messages + */ + private function notify(string $op, ?string $data = null): void + { + $this->statusWriter->report($op, $data); + } + + /** + * Returns default, changed and command-line ini settings + * + * @param mixed[] $loadedConfig All current ini settings + * @param mixed[] $iniConfig Settings from user ini files + * + */ + private function mergeLoadedConfig(array $loadedConfig, array $iniConfig): string + { + $content = ''; + + foreach ($loadedConfig as $name => $value) { + // Value will either be null, string or array (HHVM only) + if (!is_string($value) + || strpos($name, 'xdebug') === 0 + || $name === 'apc.mmap_file_mask') { + continue; + } + + if (!isset($iniConfig[$name]) || $iniConfig[$name] !== $value) { + // Double-quote escape each value + $content .= $name.'="'.addcslashes($value, '\\"').'"'.PHP_EOL; + } + } + + return $content; + } + + /** + * Returns true if the script name can be used + */ + private function checkMainScript(): bool + { + if ($this->script !== null) { + // Allow an application to set -- for standard input + return file_exists($this->script) || '--' === $this->script; + } + + if (file_exists($this->script = $_SERVER['argv'][0])) { + return true; + } + + // Use a backtrace to resolve Phar and chdir issues. + $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + $main = end($trace); + + if ($main !== false && isset($main['file'])) { + return file_exists($this->script = $main['file']); + } + + return false; + } + + /** + * Adds restart settings to the environment + * + * @param string[] $envArgs + */ + private function setEnvRestartSettings(array $envArgs): void + { + $settings = [ + php_ini_loaded_file(), + $envArgs[2], + $envArgs[3], + $envArgs[4], + getenv($this->envOriginalInis), + self::$skipped, + ]; + + Process::setEnv(self::RESTART_SETTINGS, implode('|', $settings)); + } + + /** + * Syncs settings and the environment if called with existing settings + * + * @phpstan-param restartData $settings + */ + private function syncSettings(array $settings): void + { + if (false === getenv($this->envOriginalInis)) { + // Called by another app, so make original inis available + Process::setEnv($this->envOriginalInis, implode(PATH_SEPARATOR, $settings['inis'])); + } + + self::$skipped = $settings['skipped']; + $this->notify(Status::INFO, 'Process called with existing restart settings'); + } + + /** + * Returns true if there are no known configuration issues + */ + private function checkConfiguration(?string &$info): bool + { + if (!function_exists('proc_open')) { + $info = 'proc_open function is disabled'; + return false; + } + + if (extension_loaded('uopz') && !((bool) ini_get('uopz.disable'))) { + // uopz works at opcode level and disables exit calls + if (function_exists('uopz_allow_exit')) { + @uopz_allow_exit(true); + } else { + $info = 'uopz extension is not compatible'; + return false; + } + } + + // Check UNC paths when using cmd.exe + if (defined('PHP_WINDOWS_VERSION_BUILD') && PHP_VERSION_ID < 70400) { + $workingDir = getcwd(); + + if ($workingDir === false) { + $info = 'unable to determine working directory'; + return false; + } + + if (0 === strpos($workingDir, '\\\\')) { + $info = 'cmd.exe does not support UNC paths: '.$workingDir; + return false; + } + } + + return true; + } + + /** + * Enables async signals and control interrupts in the restarted process + * + * Available on Unix PHP 7.1+ with the pcntl extension and Windows PHP 7.4+. + */ + private function tryEnableSignals(): void + { + if (function_exists('pcntl_async_signals') && function_exists('pcntl_signal')) { + pcntl_async_signals(true); + $message = 'Async signals enabled'; + + if (!self::$inRestart) { + // Restarting, so ignore SIGINT in parent + pcntl_signal(SIGINT, SIG_IGN); + } elseif (is_int(pcntl_signal_get_handler(SIGINT))) { + // Restarted, no handler set so force default action + pcntl_signal(SIGINT, SIG_DFL); + } + } + + if (!self::$inRestart && function_exists('sapi_windows_set_ctrl_handler')) { + // Restarting, so set a handler to ignore CTRL events in the parent. + // This ensures that CTRL+C events will be available in the child + // process without having to enable them there, which is unreliable. + sapi_windows_set_ctrl_handler(function ($evt) {}); + } + } + + /** + * Sets static properties $xdebugActive, $xdebugVersion and $xdebugMode + */ + private static function setXdebugDetails(): void + { + if (self::$xdebugActive !== null) { + return; + } + + self::$xdebugActive = false; + if (!extension_loaded('xdebug')) { + return; + } + + $version = phpversion('xdebug'); + self::$xdebugVersion = $version !== false ? $version : 'unknown'; + + if (version_compare(self::$xdebugVersion, '3.1', '>=')) { + $modes = xdebug_info('mode'); + self::$xdebugMode = count($modes) === 0 ? 'off' : implode(',', $modes); + self::$xdebugActive = self::$xdebugMode !== 'off'; + return; + } + + // See if xdebug.mode is supported in this version + $iniMode = ini_get('xdebug.mode'); + if ($iniMode === false) { + self::$xdebugActive = true; + return; + } + + // Environment value wins but cannot be empty + $envMode = (string) getenv('XDEBUG_MODE'); + if ($envMode !== '') { + self::$xdebugMode = $envMode; + } else { + self::$xdebugMode = $iniMode !== '' ? $iniMode : 'off'; + } + + // An empty comma-separated list is treated as mode 'off' + if (Preg::isMatch('/^,+$/', str_replace(' ', '', self::$xdebugMode))) { + self::$xdebugMode = 'off'; + } + + self::$xdebugActive = self::$xdebugMode !== 'off'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/CHANGELOG.md b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/CHANGELOG.md new file mode 100644 index 00000000..07d819e2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/CHANGELOG.md @@ -0,0 +1,5114 @@ +CHANGELOG for PHP CS Fixer +========================== + +This file contains changelogs for stable releases only. + +Changelog for v3.40.2 +--------------------- + +* docs: fix link to source classes (#7493) + +Changelog for v3.40.1 +--------------------- + +* chore: Delete stray file x (#7473) +* chore: Fix editorconfig (#7478) +* chore: Fix typos (#7474) +* chore: Fix YAML line length (#7476) +* chore: Indent JSON files with 4 spaces (#7480) +* chore: Make YAML workflow git-based (#7477) +* chore: Use stable XDebug (#7489) +* CI: Lint docs (#7479) +* CI: Use PHPStan's native Github error formatter (#7487) +* DX: fix PHPStan error (#7488) +* DX: PsrAutoloadingFixerTest - do not build mock in data provider (#7491) +* DX: PsrAutoloadingFixerTest - merge all data providers into one (#7492) +* DX: Update PHPStan to 1.10.46 (#7486) +* fix: `NoSpacesAfterFunctionNameFixer` - do not remove space if the opening parenthesis part of an expression (#7430) + +Changelog for v3.40.0 +--------------------- + +* chore: officially support PHP 8.3 (#7466) +* chore: update deps (#7471) +* CI: add --no-update while dropping non-compat `facile-it/paraunit` (#7470) +* CI: automate --ignore-platform-req=PHP (#7467) +* CI: bump actions/github-script to v7 (#7468) +* CI: move humbug/box out of dev-tools/composer.json (#7472) + +Changelog for v3.39.1 +--------------------- + +* DX: introduce SwitchAnalyzer (#7456) +* fix: NoExtraBlankLinesFixer - do not remove blank line after `? : throw` (#7457) +* fix: OrderedInterfacesFixer - do not comment out interface (#7464) +* test: Improve `ExplicitIndirectVariableFixerTest` (#7451) + +Changelog for v3.39.0 +--------------------- + +* chore: Add support for Symfony 7 (#7453) +* chore: IntegrationTest - move support of php< requirement to main Integration classes (#7448) +* CI: drop Symfony ^7 incompat exceptions of php-coveralls and cli-executor (#7455) +* CI: early compatibility checks with Symfony 7 (#7431) +* docs: drop list.rst and code behind it (#7436) +* docs: remove Gitter mentions (#7441) +* DX: Ability to run Fixer on PHP8.3 for development (#7449) +* DX: describe command - for rules, list also sets that are including them (#7419) +* DX: Docker clean up (#7450) +* DX: more usage of spaceship operator (#7438) +* DX: Put `Preg`'s last error message in exception message (#7443) +* feat: Introduce `@PHP83Migration` ruleset and PHP 8.3 integration test (#7439) +* test: Improve `AbstractIntegrationTestCase` description (#7452) + +Changelog for v3.38.2 +--------------------- + +* docs: fix 'Could not lex literal_block as "php". Highlighting skipped.' (#7433) +* docs: small unification between FixerDocumentGenerator and ListDocumentGenerator (#7435) +* docs: unify ../ <> ./../ (#7434) + +Changelog for v3.38.1 +--------------------- + +* chore: ListSetsCommand::execute - add missing return type (#7432) +* chore: PHPStan - add counter to dataProvider exception, so we do not increase the tech debt on it (#7425) +* CI: Use `actions/checkout` v4 (#7423) +* fix: ClassAttributesSeparationFixer - handle Disjunctive Normal Form types parentheses (#7428) +* fix: Remove all variable names in `@var` callable signature (#7429) +* fix: Satisfy `composer normalize` (#7424) + +Changelog for v3.38.0 +--------------------- + +* chore: upgrade phpstan (#7421) +* CI: add curl and mbstring to build php (#7409) +* CI: cache dev-tools/bin (#7416) +* CI: Composer - move prefer-stable to file config (#7406) +* CI: conditionally install flex (#7412) +* CI: dev-tools/build.sh - no need to repeat 'prefer-stable', but let's use '--no-scripts' (#7408) +* CI: Do not run post-autoload-dump on Composer install (#7403) +* CI: general restructure (#7407) +* CI: GitHub Actions - use actions/cache for Composer in composite action (#7415) +* CI: Improve QA process - suplement (#7411) +* CI: prevent Infection plugins during build time, as we do not use it (#7422) +* CI: simplify setup-php config (#7404) +* DX: Do not mark as stale issues/PRs with milestone assigned (#7398) +* DX: Improve QA process (#7366) +* feat: phpDoc to property/return/param Fixer - allow fixing mixed on PHP >= 8 (#6356) +* feat: phpDoc to property/return/param Fixer - allow fixing union types on PHP >= 8 (#6359) +* feat: Support for array destructuring in `array_indentation` (#7405) +* feat: `@Symfony` - keep Annotation,NamedArgumentConstructor,Target annotations as single group (#7399) +* fix(SelfAccessorFixer): do not touch references inside lambda and/or arrow function (#7349) +* fix: long_to_shorthand_operator - mark as risky fixer (#7418) +* fix: OrderedImportsFixer - handle non-grouped list of const/function imports (#7397) + +Changelog for v3.37.1 +--------------------- + +* docs: config file - provide better examples (#7396) +* docs: config file - provide better link to Finder docs (#6992) + +Changelog for v3.37.0 +--------------------- + +* feat: add parallel cache support (#7131) + +Changelog for v3.36.0 +--------------------- + +* chore: disable `infection-installer` plugin, as we do not use `infection/*` yet (#7391) +* chore: Run dev-tools on PHP 8.2 (#7389) +* CI: Run Symfony 6 compat check on PHP 8.1 (#7383) +* CI: use fast-linter when calculating code coverage (#7390) +* docs: extend example for nullable_type_declaration (#7381) +* DX: FixerFactoryTest - make assertion failing msg more descriptive (#7387) +* feat: PhpdocSummaryFixer - support lists in description (#7385) +* feat: PSR12 - configure unary_operator_spaces (#7388) +* feat: StatementIndentationFixer - support comment for continuous control statement (#7384) + +Changelog for v3.35.1 +--------------------- + +* fix: Mark `PhpdocReadonlyClassCommentToKeywordFixer` as risky (#7372) + +Changelog for v3.35.0 +--------------------- + +* chore: Autoreview: test all formats are listed in `usage.rst` (#7357) +* chore: no need for `phpunitgoodpractices/traits` anymore (#7362) +* chore: Rename `indexes` to `indices` (#7368) +* chore: stop using `phpunitgoodpractices/traits` (#7363) +* chore: typo (#7367) +* docs: Sort options in documentation (#7345) +* feat(PhpdocReadonlyClassCommentToKeywordFixer): Introduction (#7353) +* feat: Ability to keep/enforce leading `\` when in global namespace (#7186) +* feat: Update `@PER-CS2.0` to match short closure space (#6970) +* feat: use `ordered_types` in `@PhpCsFixer` (#7361) +* fix(SingleLineThrowFixer): fixer goes out of range on close tag (#7369) + +Changelog for v3.34.1 +--------------------- + +* deps: revert "prevent using PHPCSFixer along with unfinalize package (#7343)" (#7348) + +Changelog for v3.34.0 +--------------------- + +* feat: Introduce `check` command (alias for `fix --dry-run`) (#7322) + +Changelog for v3.33.0 +--------------------- + +* feat: Introduce `native_type_declaration_casing` fixer (#7330) + +Changelog for v3.32.0 +--------------------- + +* deps: Prevent using PHPCSFixer along with `unfinalize` package (#7343) +* feat: Deprecate `CompactNullableTypehintFixer` and proxy to `CompactNullableTypeDeclarationFixer` (#7339) +* feat: Deprecate `CurlyBracesPositionFixer` and proxy to `BracesPositionFixer` (#7334) +* feat: Deprecate `NewWithBracesFixer` and proxy to `NewWithParenthesesFixer` (#7331) +* feat: Deprecate `NoUnneededCurlyBracesFixer` and proxy to `NoUnneededBracesFixer` (#7335) +* feat: Rename `CurlyBraceTransformer` to `BraceTransformer` (#7333) + +Changelog for v3.31.0 +--------------------- + +* chore: Use type declaration instead of type hint (#7338) +* feat: Introduce `attribute_placement` option for `MethodArgumentSpaceFixer` (#7320) +* fix: Adjust wording related to deprecations (#7332) +* fix: Correct deprecation header in rules' docs (#7337) +* fix: Replace mention of bracket with parenthesis (#7336) +* fix: `FunctionToConstantFixer` should run before `NativeConstantInvocationFixer` (#7344) + +Changelog for v3.30.0 +--------------------- + +* feat: Introduce `AttributeEmptyParenthesesFixer` (#7284) +* fix(method_argument_space): inject new line after trailing space on current line (#7327) +* fix(`YodaStyleFixer`): do not touch `require(_once)`, `include(_once)` and `yield from` statements (#7325) +* fix: illegal offset type on file-wide return in `ReturnToYieldFromFixer` (#7318) + +Changelog for v3.29.0 +--------------------- + +* chore: fix TODO tasks about T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG support (#7316) +* feat(`@PhpCsFixer:risky`): use newest `@PER-CS:risky` instead of locked `@PER-CS2.0:risky` (#7323) +* feat: Introduce `@PER-CS` ruleset (#7321) +* fix: priority issue between array_syntax and space after rules (#7324) + +Changelog for v3.28.0 +--------------------- + +* chore(prlint): allow for 'deps' type (#7304) +* CI(prlint): allow for special chars in parentheses (#7308) +* deps(dev-tools): update dev-tools (#7309) +* DX: Bump XDebug version in Docker services (#7300) +* feat(`@PER-CS2.0`): Add `concat_space` to the ruleset (#7302) + +Changelog for v3.27.0 +--------------------- + +* docs: cleanup old mention of `--show-progress=estimating` in docs (#7287) +* DX: add Composer script for applying CS fixes in parallel (#7274) +* feat: Clone PER-CS1.0 to PER-CS2.0 to prepare for adding new rules (#7249) +* feat: Introduce `LongToShorthandOperatorFixer` (#7295) +* feat: Mark PER-CS v1 as deprecated (#7283) +* feat: Move `single_line_empty_body` to `@PER-CS2.0` (#7282) +* fix: Priorities for fixers related to curly braces, empty lines and trailing whitespace (#7296) +* fix: `OrderedTraitsFixer` - better support for multiple traits in one `use` statement (#7289) + +Changelog for v3.26.1 +--------------------- + +* fix: Handle superfluous asterisk in `no_superfluous_phpdoc_tags` (#7279) + +Changelog for v3.26.0 +--------------------- + +* chore(checkbashisms): update to 2.23.6 (#7276) +* chore(phpstan): reduce baseline (#7275) +* feat: Add `single_line_empty_body` to `@PhpCsFixer` (#7266) +* fix(YieldFromArrayToYieldsFixer): mark as Risky (#7272) +* fix(YieldFromArrayToYieldsFixer): skip touching empty array (#7273) +* test: Introduce common way of creating fake Composer project in `InstallViaComposerTest` (#7265) + +Changelog for v3.25.1 +--------------------- + +* fix: PhpdocTypesFixer - do not crash for type followed by braces/brackets/chevrons/parentheses (#7268) + +Changelog for v3.25.0 +--------------------- + +* feat: Remove Doctrine dependencies (#7263) + +Changelog for v3.24.0 +--------------------- + +* chore: apply CS (#7240) +* chore: apply static_lambda rule (#7239) +* chore: Improve template for creating new issue (#7255) +* CI: Conventional Commits support in PRLint config (#7037) +* CI: Remove Travis leftovers (#7259) +* docs: Add information about installing Fixer as dev dependency (#7129) +* docs: document composer script aliases (#7230) +* DX: Add script for running Composer Require Checker (#7252) +* DX: composer script aliases - ensure templated description (#7235) +* DX: composer-script - count PHPMD as static-analysis (#7231) +* DX: do not allow version specific code sample with minimum PHP version lower than the lowest supported one (#7207) +* DX: ensure version specific code samples are suitable for at least 1 supported PHP version (#7212) +* DX: Improve contributing guide (#7241) +* DX: More descriptive stale messages (#7236) +* feat(@PhpCsFixer:risky): add static_lambda rule (#7237) +* feat: Add literal separator support for `integer_literal_case` (#7081) +* feat: Configurable case sensitivity for more ordering fixers (#7021) +* feat: Support for attributes in `method_argument_space` (#7242) +* fix: import detection for attributes at `NoUnusedImportsFixer` (#7246) +* fix: `no_superfluous_phpdoc_tags` with `null` phpdoc (#7234) +* fix: `phpdoc_types` must not lowercase literal types (#7108) +* test: Add static methods from PHPUnit 9.6.11 (#7243) + +Changelog for v3.23.0 +--------------------- + +* bug: BlankLineBeforeStatementFixer - do not enforce/add a blank line when there is a blank line between the comment and the statement already (#7190) +* bug: Fix detecting classy invocation in catch (#7191) +* bug: Fix names resolving in `no_superfluous_phpdoc_tags` fixer (#7189) +* bug: Fix various bugs in `FullyQualifiedStrictTypesFixer` fixer (#7188) +* bug: Fixed line between general script documentation and require (#7177) +* bug: Support annotations with arguments in `FinalInternalClassFixer` (#7160) +* bug: YieldFromArrayToYieldsFixer - fix for `yield from` after `}` (#7169) +* bug: YieldFromArrayToYieldsFixer - fix handling the comment before the first array element (#7193) +* bug: `HeaderCommentFixer` must run before `BlankLinesBeforeNamespaceFixer` (#7205) +* bug: `NoUselessReturnFixer` must run before `SingleLineEmptyBodyFixer` (#7226) +* bug: `PhpdocInlineTagNormalizerFixer` - do not break tags (#7227) +* docs: Add allowed values of tags in the `phpdoc_align` (#7120) +* docs: Add extra information for GitLab reporter's integration with GitLab Code Quality (#7172) +* docs: Change the single backticks to double in description of the rules option (#7173) +* docs: Condensed output for rule sets' list that fixer is included in (#7182) +* docs: Improve contributing guide (#7204) +* docs: `MethodArgumentSpaceFixer` - mention PSR in Fixer definition (#7157) +* DX: add first auto-review tests for composer.json file (#7210) +* DX: add `YieldFromArrayToYieldsFixer` to `PhpCsFixer` set (#7115) +* DX: Allow OS conditions for integration tests (#7161) +* DX: Apply current CS rules (#7178) +* DX: Apply suggestions from PR 7210 (#7213) +* DX: apply `ReturnToYieldFromFixer` (#7181) +* DX: Do not mark "long term ideas" as stale (#7206) +* DX: enable `HeredocIndentationFixer` for the codebase (#7195) +* DX: enable `UseArrowFunctionsFixer` for the codebase (#7194) +* DX: few phpstan fixes (#7208) +* DX: fix contravariant types in PHPDocs (#7167) +* DX: Fix detecting trailing spaces (#7216) +* DX: Fix some PHPStan issues (#7180) +* DX: Get rid of deprecation warnings in Mess Detector (#7215) +* DX: Improve Composer scripts (#7214) +* DX: Improve Mess Detector Integration (#7224) +* DX: Introduce Composer scripts as common DX (#6839) +* DX: refactor `ErrorOutputTest` (#7183) +* DX: remove unnecessary arrays from data providers (#7170) +* DX: update `CurlyBracesPositionFixer` code samples (#7198) +* DX: update `HeredocIndentationFixer` code samples (#7197) +* DX: update `PhpdocToReturnTypeFixer` code samples (#7199) +* feature: add at least one space around binary operators (#7175) +* feature: BlankLineBeforeStatementFixer - take into account comment before statement (#7166) +* feature: Introduce `ReturnToYieldFromFixer` (#7168) +* feature: Introduce `SpacesInsideParenthesesFixer` (#5709) +* feature: Support array destructuring in `trim_array_spaces` (#7218) +* feature: `BlankLineBeforeStatementFixer` - skip enum cases (#7203) +* minor: more arrow function usage (#7223) +* minor: PhpdocAlignFixerTest - convert CUSTOM tags test to not rely on non-custom tag from TAGS_WITH_NAME (#7209) +* minor: use JSON_THROW_ON_ERROR for trivial cases (#7221) +* minor: use more spread operator (#7222) + +Changelog for v3.22.0 +--------------------- + +* DX: add proper test for `SelfAccessorFixer` must run before `SelfAccessorFixer` (#7153) +* DX: FixerFactoryTest - apply CS (#7154) +* feature: Introduce `PhpUnitDataProviderReturnTypeFixer` (#7156) +* feature: Introduce `YieldFromArrayToYieldsFixer` (#7114) + +Changelog for v3.21.3 +--------------------- + +* Revert "DX: encourage to provide wider description" (#7155) + +Changelog for v3.21.2 +--------------------- + +* docs: check format of FixerDefinition::getDescription() (#7127) +* DX: add phpstan/phpstan-strict-rules (#7143) +* DX: allow for progressive cache (#7132) +* DX: Copy-pasteable `class::getPriority` for phpDoc diffs (#7148) +* DX: do not allow linebreak at the beginning of code sample (#7126) +* DX: encourage to provide wider description (#7128) +* DX: fix function calls (#7136) +* DX: fix PHPDoc types issues (#7135) +* DX: improve `Tokens` checking for found tokens (#7139) +* DX: Make `AbstractFixerTestCase::getTestFile()` final (#7116) +* DX: make `array_search` call strict (#7145) +* DX: remove `empty` calls (#7138) +* DX: store cache to file only if content will get modified (#7151) +* DX: unify Preg:match in logical conditions (#7146) +* DX: use booleans in conditions (#7149) +* DX: Use ParaUnit to speed up tests (#6883) +* DX: Use relative fixture path as integration test case's name (#7147) +* DX: use strict assertions (#7144) +* DX: `AbstractIntegrationTestCase::provideIntegrationCases` - yield over array, better typehinting (#7150) + +Changelog for v3.21.1 +--------------------- + +experimental release + +* Require PHP ^8.0.1 + +Changelog for v3.21.0 +--------------------- + +* bug: Fix and enhance Gitlab reporter (#7089) +* bug: Import with different case must not be removed by non-risky fixer (#7095) +* bug: ordered imports fixer top group only (#7023) +* bug: `FinalPublicMethodForAbstractClassFixer` - fix for readonly classes (#7123) +* DX: do not nest ".editorconfig" files (#7112) +* DX: exclude Dockerfile from dist (#7113) +* DX: fix checkbashisms installation (#7102) +* DX: fix Smoke tests for various git default branch name (#7119) +* DX: Fix `FileRemovalTest` (do not fail when running it standalone) (#7104) +* DX: Progress output refactor (#6848) +* DX: Rename abstract test classes to `*TestCase` convention (#7100) +* DX: test all PHPUnit migration sets (#7107) +* DX: [Docker] Distinguish Alpine version between PHP versions (#7105) +* feature: Create cache path if it does not exist (#7109) +* feature: Introduce `NullableTypeDeclarationFixer` (#7002) +* feature: Introduce `TypeDeclarationSpacesFixer` (#7001) +* feature: `BlankLineBetweenImportGroupsFixer` - keep indent (#7122) +* minor: Parse callable using full phpdoc grammar (#7094) +* minor: PHP8.3 const type tokenizing (#7055) + +Changelog for v3.20.0 +--------------------- + +* DX: fix priority of `FinalClassFixer` (#7091) +* DX: use FAST_LINT_TEST_CASES=1 for CI run on macOS (#7092) +* feature: SingleLineEmptyBodyFixer - support interfaces, traits and enums (#7096) +* feature: `NullableTypeDeclarationForDefaultNullValue` - support for nullability in union types (#5819) + +Changelog for v3.19.2 +--------------------- + +* bug: NoMultipleStatementsPerLineFixer must run before CurlyBracesPositionFixer (#7087) +* bug: PhpdocAddMissingParamAnnotationFixer - fix for promoted properties (#7090) +* DX: fix priority of SingleBlankLineBeforeNamespaceFixer (#7088) +* minor: Parse all phpdoc types using full grammar (#7010) + +Changelog for v3.19.1 +--------------------- + +* bug: CurlyBracesPositionFixer must run before StatementIndentationFixer (#7085) + +Changelog for v3.19.0 +--------------------- + +* bug: SelfAccessorFixer - fix for union types (#7080) +* DX: add `php_unit_data_provider_name` to `@PhpCsFixer:risky` set (#7069) +* DX: make data providers return type "iterable" (#7072) +* DX: rename tests and data providers (#7070) +* feature: Introduce `PhpUnitDataProviderNameFixer` (#7057) + +Changelog for v3.18.0 +--------------------- + +* bug: Fix tokenizing of type hints (#7054) +* bug: CompactNullableTypehintFixer - fix for whitespace between `?` and `static` (#6993) +* bug: consider function modifiers for `statement_indentation` (#6978) +* bug: Exclude `$this` from `TernaryToNullCoalescingFixer` (#7052) +* bug: False positive on used imports when docblock includes it with mismatching case (#6909) +* bug: Fix chained calls semicolon indent in switch case (#7045) +* bug: Fix multiline_whitespace_before_semicolons for echo tags (#7019) +* bug: Fix phpDoc align when there is inconsistent spacing after comment star (#7012) +* bug: Fix phpDoc parsing without PCRE JIT (#7031) +* bug: Fix PhpdocVarWithoutNameFixer with Closure with $this (#6979) +* bug: Fix `return_assignment` not formatting when variables are used in `catch` and `finally` (#6960) +* bug: Fix `TypeExpression::allowsNull()` with nullable (#7000) +* bug: Improve definition of conflicting fixers (#7066) +* bug: LambdaNotUsedImportFixer - fix for anonymous class with a string argument (#6972) +* bug: ListFilesCommand - fix computing of relative path (#7028) +* bug: make `php_unit_namespaced` less greedy (#6952) +* bug: PhpdocToCommentFixer - fix for PHPDoc before fn (#6973) +* bug: Restructure PER-CS rule sets (#6707) +* bug: SelfStaticAccessor - fix static access inside enums (#7024) +* bug: SingleSpaceAroundConstructFixer - fix more cases involving `static` (#6995) +* bug: `FullyQualifiedStrictTypesFixer` - fix shortening when namespace is not empty and import exists (#7027) +* bug: `NoUnneededControlParenthesesFixer` PHP8.0 null-safe operator (#7056) +* bug: `PhpdocToCommentFixer` support for enum cases (#7040) +* DX: add more tests to CommentsAnalyzer (#7041) +* DX: Cleanup duplicate files in finder (#7042) +* DX: ControlCaseStructuresAnalyzerTest - cleanup (#6874) +* DX: Fix warning when running test on PHP<8 (#7008) +* DX: handle `@` in PR title (#6982) +* DX: officially deprecate internal Utils anti-pattern class (#7039) +* DX: Remove Fabbot.io conditional configuration (#7038) +* DX: rename data providers (#7058) +* DX: Use `actions/stale` to handle stale issues and pull requests (#5085) +* DX: Use `Utils::naturalLanguageJoin()` in implode calls (#7032) +* feature: Add support for custom method placement in `ordered_class_elements` (#6360) +* feature: Allow case sensitive order for OrderedClassElementsFixer (#7020) +* feature: PHP8.3 - Add CT and block type for `Dynamic class constant fetch` (#7004) +* feature: Support attributes in `FinalClassFixer` (#6893) +* minor: "Callback" must not be fixed to "callback" by default (#7011) +* minor: Add `Util::naturalLanguageJoin()` (#7022) +* minor: ClassDefinitionFixer - handle attributes and `readonly` in anonymous class definitions (#7014) +* minor: FixerFactory::getFixersConflicts - better type hinting (#7044) +* minor: PHP8.3 - Fix TokensAnalyzer::isAnonymousClass support for `readonly` (#7013) +* minor: PHP8.3 - Typed class constants - handle nullable by transformer (#7009) +* minor: Reduce phpDoc type parser complexity from O(n^2) to O(nlog(n)) (#6988) +* minor: ReturnAssignmentFixer - Better handling of anonymous classes (#7015) +* minor: Transfer `HelpCommand::toString()` to `Utils` (#7034) +* minor: Unify "blank lines before namespace" fixers (#7053) +* minor: `SelfStaticAccessorFixer` improvements for enums (#7026) +* minor: `SingleSpaceAroundConstructFixer` - support space before `as` (#7029) +* minor: `UseArrowFunctionsFixer` - run before `FunctionDeclarationFixer` (#7065) + +Changelog for v3.17.0 +--------------------- + +* bug: Allow string quote to be escaped within phpdoc constant (#6798) +* bug: ConfigurationResolver - fix running without cache (#6915) +* bug: Fix array/object shape phpdoc type parse (#6962) +* bug: Fix FullyQualifiedStrictTypesFixer common prefix bug (#6898) +* bug: Fix non-parenthesized callable return type parse (#6961) +* bug: Fix parsing of edge cases phpdoc types (#6977) +* bug: FullyQualifiedStrictTypesFixer - fix for FQCN type with class with the same name being imported (#6923) +* bug: GroupImportFixer - support for aliased imports (#6951) +* bug: MultilineWhitespaceBeforeSemicolonsFixer - fix chained calls (#6926) +* bug: MultilineWhitespaceBeforeSemicolonsFixer - fix for discovering multi line calls (#6938) +* bug: NoBreakCommentFixer - fix for nested match (#6899) +* bug: NoExtraBlankLinesFixer - fix for attribute in abstract function (#6920) +* bug: PhpdocTypesFixer - handle types with no space between type and variable (#6922) +* bug: PhpUnitMockShortWillReturnFixer - fix for trailing commas (#6900) +* bug: StatementIndentationFixer - fix comments at the end of if/elseif/else blocks (#6918) +* bug: StatementIndentationFixer - fix for multiline arguments starting with "new" keyword (#6913) +* bug: StatementIndentationFixer - fix for multiline arguments starting with "new" keyword preceded by class instantiation (#6914) +* bug: VoidReturnFixer - fix for intervening attributes (#6863) +* docs: improve code samples for MultilineWhitespaceBeforeSemicolonsFixer (#6919) +* docs: improve cookbook (#6880) +* DX: add cache related tests (#6916) +* DX: Apply `self_static_accessor` fixer to the project (again) (#6927) +* DX: cancel running builds on subsequent pushes in CI (#6940) +* DX: convert more `static` to `self` assert calls (#6931) +* DX: fix GitHub Actions errors and warnings (#6917) +* DX: fix Unsafe call to private method errors reported by PHPStan (#6879) +* DX: Improve performance of FunctionsAnalyzer (#6939) +* DX: improve test method names to avoid confusion (#6974) +* DX: Include self_static_accessor fixer in PhpCsFixer set (#6882) +* DX: make data providers static with straight-forward changes (#6907) +* DX: Mark Tokens::getNamespaceDeclarations as @internal (#6949) +* DX: PHPStan improvements (#6868) +* DX: refactor PhpdocAlignFixerTest (#6925) +* DX: Remove @inheritdoc PHPDoc (#6955) +* DX: Run AutoReview tests only once (#6889) +* DX: simplify EncodingFixer (#6956) +* DX: update Symfony rule set (#6958) +* DX: Use $tokens->getNamespaceDeclarations() to improve performance (#6942) +* DX: use force option for php_unit_data_provider_static in PHPUnit 10.0 migration set (#6908) +* DX: use only PHP modules that are required (#6954) +* DX: use PHPUnit's "requires" instead of "if" condition (#6975) +* feature: Add align_multiline_comment rule to @Symfony (#6875) +* feature: Add no_null_property_initialization rule to @Symfony (#6876) +* feature: Add operator_linebreak rule to @Symfony (#6877) +* feature: add SingleLineEmptyBodyFixer (#6933) +* feature: DescribeCommand - allow describing custom fixers (#6957) +* feature: Introduce `OrderedTypesFixer` (#6571) +* feature: Order of PHPDoc @param annotations (#3909) +* feature: Parse parenthesized & conditional phpdoc type (#6796) +* feature: PhpUnitInternalClassFixer - add empty line before PHPDoc (#6924) +* feature: [PhpdocAlignFixer] Add support for every tag (#6564) +* minor: align NoSuperfluousPhpdocTagsFixer with actual Symfony configuration (#6953) +* minor: do not add empty line in PHPDoc when adding annotation in PHPUnit class (#6928) +* minor: PhpdocAlignFixer - support cases with type and variable separated with no space (#6921) +* minor: PhpdocSeparationFixer - add integration tests (#6929) +* minor: update PHPStan (to fix CI on master branch) (#6901) +* minor: Use single Dockerfile with multiple build targets (#6840) + +Changelog for v3.16.0 +--------------------- + +* bug: ControlStructureBracesFixer - handle closing tag (#6873) +* bug: CurlyBracesPositionFixer - fix for callable return type (#6855) +* bug: CurlyBracesPositionFixer - fix for DNF types (#6859) +* bug: Fix MultilineWhitespaceBeforeSemicolonsFixer (#5126) +* docs: Fix rule description (#6844) +* DX: fix checkbashisms installation (#6843) +* DX: make data providers static for fixer's tests (#6860) +* DX: refactor PHPUnit fixers adding class-level annotation to use shared code (#6756) +* DX: unify option's descriptions (#6856) +* feature: AbstractPhpUnitFixer - support attribute detection in docblock insertion (#6858) +* feature: add "force" option to PhpUnitDataProviderStaticFixer (#6757) +* feature: introduce single_space_around_construct, deprecate single_space_after_construct (#6857) +* feature: PhpUnitTestClassRequiresCoversFixer - support single-line PHPDocs (#6847) +* minor: Deprecate BracesFixer (#4885) +* minor: Fix autocompletion for `Tokens::offsetGet()` (#6838) +* minor: PHP8.2 Docker runtime (#6833) +* minor: Use Composer binary-only images instead of installer script (#6834) + +Changelog for v3.15.1 +--------------------- + +* bug: BinaryOperatorSpacesFixer - fix for static in type (#6835) +* bug: BinaryOperatorSpacesFixer - fix parameters with union types passed by reference (#6826) +* bug: NoUnusedImportsFixer - fix for splat operator (#6836) +* DX: fix CI (#6837) +* feature: Support for type casing in arrow functions (#6831) +* minor: fix CI on PHP 8.3 (#6827) + +Changelog for v3.15.0 +--------------------- + +* bug: VisibilityRequiredFixer - handle DNF types (#6806) +* DX: officially enable 8.2 support (#6825) + +Changelog for v3.14.5 +--------------------- + +* bug: EmptyLoopBodyFixer must keep comments inside (#6800) +* bug: FunctionsAnalyzer - fix detecting global function (#6792) +* bug: NativeFunctionTypeDeclarationCasingFixer - do not require T_STRING present in code (#6812) +* bug: PhpdocTypesFixer - do not change case of array keys (#6810) +* bug: PhpUnitTestAnnotationFixer - do not break single line @depends (#6824) +* docs: Add supported PHP versions section to the README (#6768) +* docs: drop Atom from readme, due to it's sunsetting (#6778) +* DX: Add composer keywords (#6781) +* DX: update PHPStan to 1.10.3 (#6805) +* feature: [PHP8.2] Support for readonly classes (#6745) +* minor: add custom tokens for Disjunctive Normal Form types parentheses (#6823) +* minor: PHP8.2 - handle union and intersection types for DNF types (#6804) +* minor: PHP8.2 - support property in const expressions (#6803) + +Changelog for v3.14.4 +--------------------- + +* bug: CurlyBracesPositionFixer - fix for open brace not preceded by space and followed by a comment (#6776) +* docs: drop license end year (#6767) +* DX: use numeric_literal_separator (#6766) +* feature: Allow installation of `sebastian/diff:^5.0.0` (#6771) + +Changelog for v3.14.3 +--------------------- + +* DX: Drop doctrine/annotations 1, allow doctrine/lexer 3 (#6730) + +Changelog for v3.14.2 +--------------------- + +* DX: Drop support for doctrine/lexer 1 (#6729) + +Changelog for v3.14.1 +--------------------- + +* DX: Allow doctrine/annotations 2 (#6721) + +Changelog for v3.14.0 +--------------------- + +* bug: Fix indentation for comment at end of function followed by a comma (#6542) +* bug: Fix PHPDoc alignment fixer containing callbacks using `\Closure` (#6746) +* bug: Fix type error when using paths intersection mode (#6734) +* bug: PhpdocSeparationFixer - Make groups handling more flexible (#6668) +* docs: make bug_report.md template more explicit (#6736) +* docs: PhpUnitTestCaseIndicator - fix docs (#6727) +* DX: apply CS (#6759) +* DX: bump doctrine/annotations to prevent installing version with unintentional BC break (#6739) +* DX: update deps (#6760) +* DX: upgrade dev-tools/composer.json (#6737) +* DX: upgrade PHPStan to 1.9.7 (#6741) +* feature: Add php 7.4 types to Cookbook docs (#6763) +* feature: add PhpUnitDataProviderStaticFixer (#6702) +* feature: binary_operator_spaces - Revert change about => alignment and use option instead (#6724) +* feature: make OrderedInterfacesFixer non-risky (#6722) +* feature: OctalNotationFixer - support _ notation (#6762) +* fix: enum case "PARENT" must not be renamed (#6732) +* minor: Follow PSR12 ordered imports in Symfony ruleset (#6712) +* minor: improve rule sets order (#6738) + +Changelog for v3.13.2 +--------------------- + +* bug: Fix type error when using paths intersection mode (#6734) + +Changelog for v3.13.1 +--------------------- + +* bug: Align all the arrows inside the same array (#6590) +* bug: Fix priority between `modernize_types_casting` and `no_unneeded_control_parentheses` (#6687) +* bug: TrailingCommaInMultilineFixer - do not add trailing comma when there is no break line after last element (#6677) +* docs: Fix docs for disabled rules in rulesets (#6679) +* docs: fix the cookbook_fixers.rst (#6672) +* docs: Update installation recommended commands for `mkdir` argument (`-p` insteadof `--parents`). (#6689) +* Make static data providers that are not using dynamic calls (#6696) +* minor: displaying number of checked files (#6674) + +Changelog for v3.13.0 +--------------------- + +* bug: BracesFixer - Fix unexpected extra blank line (#6667) +* bug: fix CI on master branch (#6663) +* bug: IsNullFixer - handle casting (#6661) +* docs: feature or bug (#6652) +* docs: Use case insensitive sorting for options (#6666) +* docs: [DateTimeCreateFromFormatCallFixer] Fix typos in the code sample (#6671) +* DX: update cli-executor (#6664) +* DX: update dev-tools (#6665) +* feature: Add global_namespace_import to @Symfony ruleset (#6662) +* feature: Add separate option for closure_fn_spacing (#6658) +* feature: general_phpdoc_annotation_remove - allow add case_sensitive option (#6660) +* minor: AllowedValueSubset - possible values are sorted (#6651) +* minor: Use md5 for file hashing to reduce possible collisions (#6597) + +Changelog for v3.12.0 +--------------------- + +* bug: SingleLineThrowFixer - Handle throw expression inside block (#6653) +* DX: create TODO to change default ruleset for v4 (#6601) +* DX: Fix SCA findings (#6626) +* DX: HelpCommand - fix docblock (#6584) +* DX: Narrow some docblock types (#6581) +* DX: Remove redundant check for PHP <5.2.7 (#6620) +* DX: Restore PHPDoc to type rules workflow step (#6615) +* DX: SCA - scope down types (#6630) +* DX: Specify value type in iterables in tests (#6594) +* DX: Test on PHP 8.2 (#6558) +* DX: Update GitHub Actions (#6606) +* DX: Update PHPStan (#6616) +* feature: Add `@PHP82Migration` ruleset (#6621) +* feature: ArrayPushFixer now fix short arrays (#6639) +* feature: NoSuperfluousPhpdocTagsFixer - support untyped and empty annotations in phpdoc (#5792) +* feature: NoUselessConcatOperatorFixer - Introduction (#6447) +* feature: Support for constants in traits (#6607) +* feature: [PHP8.2] Support for new standalone types (`null`, `true`, `false`) (#6623) +* minor: GitHub Workflows security hardening (#6644) +* minor: prevent BC break in ErrorOutput (#6633) +* minor: prevent BC break in Runner (#6634) +* minor: Revert "minor: prevent BC break in Runner" (#6637) +* minor: Update dev tools (#6554) + +Changelog for v3.11.0 +--------------------- + +* bug: DateTimeCreateFromFormatCallFixer - Mark as risky (#6575) +* bug: Do not treat implements list comma as array comma (#6595) +* bug: Fix MethodChainingIndentationFixer with arrow functions and class instantiation (#5587) +* bug: MethodChainingIndentationFixer - Fix bug with attribute access (#6573) +* bug: NoMultilineWhitespaceAroundDoubleArrowFixer - fix for single line comment (#6589) +* bug: TypeAlternationTransformer - TypeIntersectionTransformer - Bug: handle attributes (#6579) +* bug: [BinaryOperatorFixer] Fix more issues with scoped operators (#6559) +* docs: Remove `$` from console command snippets (#6600) +* docs: Remove `$` from console command snippets in documentation (#6599) +* DX: AllowedValueSubset::getAllowedValues - fix method prototype (#6585) +* DX: Narrow docblock types in FixerConfiguration (#6580) +* DX: updagte @PhpCsFixer set config for phpdoc_order rule (#6555) +* DX: Update PHPUnit config (#6566) +* feature: Introduce configurability to PhpdocSeparationFixer (#6501) +* feature: Introduce PER set (#6545) +* feature: NoTrailingCommaInSinglelineFixer - Introduction (#6529) +* feature: Support removing superfluous PHPDocs involving `self` (#6583) +* minor: NoUnneededControlParenthesesFixer - Support instanceof static cases (#6587) +* minor: PhpdocToCommentFixer - allow phpdoc comments before trait use statement. Fixes #6092 (#6565) + +Changelog for v3.10.0 +--------------------- + +* bug: Fix error in `regular_callable_call` with static property (#6539) +* bug: Fix indentation for multiline class definition (#6540) +* bug: Fix indentation for switch ending with empty case (#6538) +* bug: Fix indentation of comment at end of switch case (#6493) +* bug: PhpdocAlignFixer - fix static `@method` (#6366) +* bug: SingleSpaceAfterConstructFixer - fix handling open tag (#6549) +* bug: VisibilityRequiredFixer must run before ClassAttributesSeparationFixer (#6548) +* DX: Assert dataproviders of tests of project itself return "array" or "iterable". (#6524) +* feature: Introduce configurability to PhpdocOrderFixer (#6466) +* feature: WhitespaceAfterCommaInArrayFixer - add option "ensure_single_space" (#6527) +* minor: Add test for indentation of trait conflict resolution (#6541) +* minor: Split BracesFixer (#4884) +* minor: TrailingCommaInMultilineFixer - Add comma to multiline `new static` (#6380) + +Changelog for v3.9.6 +-------------------- + +* bug: BinaryOperatorSpacesFixer: Solve issues with scoped arrow and equal alignments (#6515) +* bug: Fix 3 weird behavior about BinaryOperatorSpacesFixer (#6450) +* docs: Add intersection type to types_spaces rule description (#6479) +* DX: no need to use forked diff anymore (#6526) +* DX: remove unused FixerFileProcessedEvent::STATUS_UNKNOWN (#6516) +* Improve `statement_indentation` compatibility with `braces` (#6401) +* minor: add test: multi-line comments before else indented correctly. (#3573) +* minor: ReturnAssignmentFixer - Support for anonymous classes, lambda and match (#6391) + +Changelog for v3.9.5 +-------------------- + +* bug: AlternativeSyntaxAnalyzer - fix for nested else (#6495) +* bug: Fix cases related to binary strings (#6432) +* bug: Fix trailing whitespace after moving brace (#6489) +* bug: NoUnneededControlParenthesesFixer - Fix some curly close cases (#6502) +* bug: TypeColonTransformer - fix for backed enum types (#6494) +* DX: Add tests for type colon in backed enums (#6497) +* DX: Fix CI static analysis workflow (#6506) +* DX: Fix PHPStan errors (#6504) +* DX: Increase PHPStan level to 6 (#6468) +* DX: Narrow docblock types in Runner and Report (#6465) +* DX: Narrow docblock types in Tokenizer (#6293) +* minor: extract NoMultipleStatementsPerLineFixer from BracesFixer (#6458) +* minor: Let PhpdocLineSpan fixer detect docblocks when separator from token with attribute (#6343) + +Changelog for v3.9.4 +-------------------- + +* bug: Fix various indentation issues (#6480) +* bug: Fix wrong brace position after static return type (#6485) +* bug: Prevent breaking functions returning by reference (#6487) + +Changelog for v3.9.3 +-------------------- + +* bug: Fix BinaryOperatorSpacesFixer adding whitespace outside PHP blocks (#6476) +* bug: Fix brace location after multiline function signature (#6475) + +Changelog for v3.9.2 +-------------------- + +* bug: Fix indentation after control structure in switch (#6473) + +Changelog for v3.9.1 +-------------------- + +* bug: Add attributes support to `statement_indentation` (#6429) +* bug: BinaryOperatorSpacesFixer - Allow to align `=` inside array definitions (#6444) +* bug: BinaryOperatorSpacesFixer - Fix align of operator with function declaration (#6445) +* bug: ConstantCaseFixer - Do not touch enum case (#6367) +* bug: CurlyBracesPositionFixer - multiple elseifs (#6459) +* bug: Fix #6439 issue in `StaticLambda` fixer (#6440) +* bug: FullOpeningTagFixer - fix substr check for pre PHP8 (#6388) +* bug: IncrementStyleFixer - NoSpacesInsideParenthesisFixer - prio (#6416) +* bug: LambdaNotUsedImportFixer must run before MethodArgumentSpaceFixer (#6453) +* bug: MethodArgumentSpaceFixer - first element in same line, space before comma and inconsistent indent (#6438) +* bug: NoSuperfluousPhpdocTagsFixer - fix for promoted properties (#6403) +* bug: StatementIndentationFixer - Fix indentation for multiline traits use (#6402) +* bug: StrictComparisonFixer must rune before ModernizeStrposFixer (#6455) +* bug: TokensAnalyzer - fix intersection types considered as binary operator (#6414) +* DX: `ISSUE_TEMPLATE` hints to check applied rules (#6398) +* DX: Add more type hints (#6383) +* DX: Fix CI/CD issues (#6411) +* DX: cleanup test (#6410) +* DX: integrate PRLint (#6406) +* feature: BlankLineBetweenImportGroupsFixer - Introduction (#6365) +* feature: DateTimeCreateFromFormatCallFixer - Add DateTimeImmutable support (#6350) +* feature: Extract StatementIndentationFixer from BracesFixer (#5960) +* feature: ModernizeStrposFixer - fix leading backslash with yoda (#6377) +* feature: NoExtraBlankLinesFixer - Add `attributes` option - Fix support for `enum` `case` (#6426) +* feature: NoUnneededControlParenthesesFixer - Fix more cases (#6409) +* feature: NoUselessNullsafeOperatorFixer - Introduction (#6425) +* feature: OrderedTrait - Move Phpdoc with trait import (#6361) +* feature: PhpdocOrderByValueFixer - Allow sorting of mixin annotations by value (#6446) +* feature: TrailingCommaInMultiline - Add `match` support (#6381) +* minor: Allow Composer Normalize plugin (#6454) +* minor: ExplicitStringVariableFixer - Fix to PHP8.2 compat code (#6424) +* minor: Extract ControlStructureBracesFixer from BracesFixer (#6399) +* minor: NoBinaryStringFixer - Fix more cases (#6442) +* minor: NoSuperfluousPhpdocTagsFixer - Attribute handling (#6382) +* minor: PhpCsFixerSet - Update blank_line_before_statement config (#6389) +* minor: Remove unnecessary PHP version constraints (#6461) +* minor: SingleImportPerStatementFixer - fix PSR12 set (#6415) +* minor: SingleSpaceAfterConstructFixer - add option `type_colon` (#6434) +* minor: SymfonySet - Add SimpleToComplexStringVariableFixer (#6423) +* minor: Update PHPStan (#6467) +* minor: extract CurlyBracesPositionFixer from BracesFixer (#6452) + +Changelog for v3.8.0 +-------------------- + +* bug #6322 PhpdocTypesFixer - fix recognizing callable (kubawerlos) +* bug #6331 ClassReferenceNameCasingFixer - Fix false hits (SpacePossum) +* bug #6333 BinaryOperatorSpacesFixer - Fix for alignment in `elseif` (paulbalandan, SpacePossum) +* bug #6337 PhpdocTypesFixer - fix recognising callable without return type (kubawerlos) +* feature #6286 DateTimeCreateFromFormatCallFixer - Introduction (liquid207) +* feature #6312 TypesSpacesFixer - add option for CS of catching multiple types of exceptions (SpacePossum) +* minor #6326 Bump migration sets used to PHP7.4 (SpacePossum) +* minor #6328 DX: .gitignore ASC file (keradus) + +Changelog for v3.7.0 +-------------------- + +* bug #6112 [BinaryOperatorSpacesFixer] Fix align of `=` inside calls of methods (VincentLanglet) +* bug #6279 ClassReferenceNameCasingFixer - Fix for double arrow (SpacePossum) +* bug #6280 Fix bunch of enum issues (SpacePossum) +* bug #6283 ClassReferenceNameCasingFixer - detect imports (SpacePossum) +* feature #5892 NewWithBracesFixer - option to remove braces (jrmajor) +* feature #6081 Allow multiline constructor arguments in an anonymous classes (jrmajor, SpacePossum) +* feature #6274 SingleLineCommentSpacingFixer - Introduction (SpacePossum) +* feature #6300 OrderedClassElementsFixer - handle enums (gharlan) +* feature #6304 NoTrailingCommaInSinglelineFunctionCallFixer - Introduction (SpacePossum) +* minor #6277 Add `is_scalar`, `sizeof`, `ini_get` in list of compiled functions (jderusse) +* minor #6284 ClassReferenceNameCasingFixer - Update doc (SpacePossum) +* minor #6289 PHP7.4 - clean up tests (SpacePossum) +* minor #6290 PHP7.4 - properties types (SpacePossum) +* minor #6291 PHP7.4 - remove run time checks (SpacePossum) +* minor #6292 PhpUnitDedicateAssertFixer - Fix more count cases (SpacePossum) +* minor #6294 PhpUnitDedicateAssertFixer - add assertInstanceOf support (SpacePossum) +* minor #6295 PhpUnitTestCaseIndicator - Check if PHPUnit-test class extends anothe… (SpacePossum) +* minor #6298 Fix checkbashisms download ans SCA violations (SpacePossum) +* minor #6301 BracesFixer - handle enums (gharlan) +* minor #6302 Bump checkbashisms version (kubawerlos) +* minor #6303 PHP8 - Utilize "get_debug_type" (SpacePossum) +* minor #6316 bump xdebug-handler (SpacePossum) +* minor #6327 bump polyfills (SpacePossum) + +Changelog for v3.6.0 +-------------------- + +* bug #6063 PhpdocTypesOrderFixer - Improve nested types support (ruudk, julienfalque) +* bug #6197 FullyQualifiedStrictTypesFixer - fix same classname is imported from … (SpacePossum) +* bug #6241 NoSuperfluousPhpdocTagsFixer - fix for reference and splat operator (kubawerlos) +* bug #6243 PhpdocTypesOrderFixer - fix for intersection types (kubawerlos) +* bug #6254 PhpUnitDedicateAssertFixer - remove `is_resource`. (drupol) +* bug #6264 TokensAnalyzer - fix isConstantInvocation detection for multiple exce… (SpacePossum) +* bug #6265 NullableTypeDeclarationForDefaultNullValueFixer - handle "readonly" a… (SpacePossum) +* bug #6266 SimplifiedIfReturnFixer - handle statement in loop without braces (SpacePossum) +* feature #6262 ClassReferenceNameCasingFixer - introduction (SpacePossum) +* feature #6267 NoUnneededImportAliasFixer - Introduction (SpacePossum) +* minor #6199 HeaderCommentFixer - support monolithic files with shebang (kubawerlos, keradus) +* minor #6231 Fix priority descriptions and tests. (SpacePossum) +* minor #6237 DX: Application - better display version when displaying gitSha (keradus) +* minor #6242 Annotation - improve on recognising types with reference and splat operator (kubawerlos) +* minor #6250 Tokens - optimize cache clear (SpacePossum) +* minor #6269 Docs: redo warnings in RST docs to fix issue on website docs (keradus) +* minor #6270 ClassReferenceNameCasingFixer - Add missing test cases for catch (SpacePossum) +* minor #6273 Add priority test (SpacePossum) + +Changelog for v3.5.0 +-------------------- + +* bug #6058 Fix `Tokens::insertSlices` not moving around all affected tokens (paulbalandan, SpacePossum) +* bug #6160 NonPrintableCharacterFixer - fix for when removing non-printable character break PHP syntax (kubawerlos) +* bug #6165 DeclareEqualNormalizeFixer - fix for declare having multiple directives (kubawerlos) +* bug #6170 NonPrintableCharacterFixer - fix for string in single quotes, having non-breaking space, linebreak, and single quote inside (kubawerlos) +* bug #6181 UseTransformer - Trait import in enum fix (PHP8.1) (SpacePossum) +* bug #6188 PhpdocTo(Param|Property|Return)TypeFixer - fix for type intersections (kubawerlos) +* bug #6202 SquareBraceTransformer - fix for destructing square brace after double arrow (kubawerlos) +* bug #6209 OrderedClassElementsFixer - PHP8.0 support abstract private methods in traits (SpacePossum) +* bug #6224 ArgumentsAnalyzer - support PHP8.1 readonly (SpacePossum) +* feature #4571 BlankLineBeforeStatementFixer - can now add blank lines before doc-comments (addiks, SpacePossum) +* feature #5953 GetClassToClassKeywordFixer - introduction (paulbalandan) +* minor #6108 Drop support for Symfony v4 (keradus) +* minor #6163 CI: update used PHP version (keradus) +* minor #6167 SingleSpaceAfterConstructFixer - allow multiline const (y_ahiru, SpacePossum) +* minor #6168 indexes -> indices (SpacePossum) +* minor #6171 Fix tests and CS (SpacePossum) +* minor #6172 DX: Tokens::insertSlices - groom code and fix tests (keradus) +* minor #6174 PhpdocAlignFixer: fix property-read/property-write descriptions not getting aligned (antichris) +* minor #6177 DX: chmod +x for benchmark.sh file (keradus) +* minor #6180 gitlab reporter - add fixed severity to match format (cbourreau) +* minor #6183 Simplify DiffConsoleFormatter (kubawerlos) +* minor #6184 Do not support array of patterns in Preg methods (kubawerlos) +* minor #6185 Upgrade PHPStan (kubawerlos) +* minor #6189 Finder - fix usage of ignoreDotFiles (kubawerlos) +* minor #6190 DX: DiffConsoleFormatter - escape - (keradus) +* minor #6194 Update Docker setup (julienfalque) +* minor #6196 clean ups (SpacePossum) +* minor #6198 DX: format dot files (kubawerlos) +* minor #6200 DX: Composer's branch-alias leftovers cleanup (kubawerlos) +* minor #6203 Bump required PHP to 7.4 (keradus) +* minor #6205 DX: bump PHPUnit to v9, PHPUnit bridge to v6 and Prophecy-PHPUnit to v2 (keradus) +* minor #6210 NullableTypeDeclarationForDefaultNullValueFixer - fix tests (HypeMC) +* minor #6212 bump year 2021 -> 2022 (SpacePossum) +* minor #6215 DX: Doctrine\Annotation\Tokens - fix phpstan violations (keradus) +* minor #6216 DX: Doctrine\Annotation\Tokens - drop unused methods (keradus) +* minor #6217 DX: lock SCA tools for PR builds (keradus) +* minor #6218 Use composer/xdebug-handler v3 (gharlan) +* minor #6222 Show runtime on version command (SpacePossum) +* minor #6229 Simplify Tokens::isMonolithicPhp tests (kubawerlos) +* minor #6232 Use expectNotToPerformAssertions where applicable (SpacePossum) +* minor #6233 Update Tokens::isMonolithicPhp (kubawerlos) +* minor #6236 Annotation - improve getting variable name (kubawerlos) + +Changelog for v3.4.0 +-------------------- + +* bug #6117 SingleSpaceAfterConstruct - handle before destructuring close brace (liquid207) +* bug #6122 NoMultilineWhitespaceAroundDoubleArrowFixer - must run before MethodArgumentSpaceFixer (kubawerlos) +* bug #6130 StrictParamFixer - must run before MethodArgumentSpaceFixer (kubawerlos) +* bug #6137 NewWithBracesFixer - must run before ClassDefinitionFixer (kubawerlos) +* bug #6139 PhpdocLineSpanFixer - must run before NoSuperfluousPhpdocTagsFixer (kubawerlos) +* bug #6143 OperatorLinebreakFixer - fix for alternative syntax (kubawerlos) +* bug #6159 ImportTransformer - fix for grouped constant and function imports (kubawerlos) +* bug #6161 NoUnreachableDefaultArgumentValueFixer - fix for attributes (kubawerlos) +* feature #5776 DX: test on PHP 8.1 (kubawerlos) +* feature #6152 PHP8.1 support (SpacePossum) +* minor #6095 Allow Symfony 6 (derrabus, keradus) +* minor #6107 Drop support of PHPUnit v7 dependency (keradus) +* minor #6109 Add return type to `DummyTestSplFileInfo::getRealPath()` (derrabus) +* minor #6115 Remove PHP 7.2 polyfill (derrabus) +* minor #6116 CI: remove installation of mbstring polyfill in build script, it's required dependency now (keradus) +* minor #6119 OrderedClassElementsFixer - PHPUnit assert(Pre|Post)Conditions methods support (meyerbaptiste) +* minor #6121 Use Tokens::ensureWhitespaceAtIndex to simplify code (kubawerlos) +* minor #6127 Remove 2nd parameter to XdebugHandler constructor (phil-davis) +* minor #6129 clean ups (SpacePossum) +* minor #6138 PHP8.1 - toString cannot return type hint void (SpacePossum) +* minor #6146 PHP 8.1: add new_in_initializers to PHP 8.1 integration test (keradus) +* minor #6147 DX: update composer-normalize (keradus) +* minor #6156 DX: drop hack for Prophecy incompatibility (keradus) + +Changelog for v3.3.1 +-------------------- + +* minor #6067 Bump minimum PHP version to 7.2 (keradus) + +Changelog for v3.3.0 +-------------------- + +* bug #6054 Utils - Add multibyte and UTF-8 support (paulbalandan) +* bug #6061 ModernizeStrposFixer - fix for negated with leading slash (kubawerlos) +* bug #6064 SquareBraceTransformer - fix detect array destructing in foreach (SpacePossum) +* bug #6082 PhpUnitDedicateAssertFixer must run before NoUnusedImportsFixer (kubawerlos) +* bug #6089 TokensAnalyzer.php - Fix T_ENCAPSED_AND_WHITESPACE handling in isBina… (SpacePossum) +* feature #5123 PhpdocTypesFixer - support generic types (kubawerlos) +* minor #5775 DX: run static code analysis on PHP 8.0 (kubawerlos) +* minor #6050 DX: TypeIntersectionTransformer - prove to not touch T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG (keradus) +* minor #6051 NoExtraBlankLinesFixer - Improve deprecation message (paulbalandan) +* minor #6060 DX: Add upgrade guide link when next Major is available (keradus) +* minor #6066 Clean ups (SpacePossum, kubawerlos) +* minor #6069 DX: cleanup stub file (keradus) +* minor #6070 Update UPGRADE-v3.md with php_unit_test_annotation/case deprecation (kubawerlos) +* minor #6072 Update usage doc to reflect change to PSR12 default. (hannob, keradus) +* minor #6084 Change: Remove __constructor() from RuleSetDescriptionInterface (niklam) +* minor #6085 Dx: reuse WhitespacesAnalyzer::detectIndent (kubawerlos) +* minor #6087 AbstractProxyFixer - more tests (SpacePossum) + +Changelog for v3.2.1 +--------------------- + +experimental release + +* Require PHP 7.2 + +Changelog for v3.2.0 +-------------------- + +* bug #5809 FunctionsAnalyzer - fix for recognizing global functions in attributes (kubawerlos) +* bug #5909 NativeFunctionCasingFixer - fix for attributes and imported functions (kubawerlos) +* bug #5920 ClassAttributesSeparationFixer - fixes & enhancements (SpacePossum) +* bug #5923 TypeAlternationTransformer - fix for promoted properties (kubawerlos) +* bug #5938 NoAliasFunctionsFixer - remove dir -> getdir mapping (SpacePossum) +* bug #5941 TokensAnalyzer - isAnonymousClass bug on PHP8 (SpacePossum) +* bug #5942 TokensAnalyzer - isConstantInvocation PHP 8 issue (SpacePossum) +* bug #5943 NoUnusedImportsFixer - use in attribute (SpacePossum) +* bug #5955 Fixed `class_attributes_separation` processing class with multiple trait imports (GrahamCampbell) +* bug #5977 LowercaseStaticReference - SingleClassElementPerStatement - union types (SpacePossum) +* bug #5984 RegularCallableCallFixer must run before NativeFunctionInvocationFixer (kubawerlos) +* bug #5986 CurlyBraceTransformer - count T_CURLY_OPEN itself as level as well (SpacePossum) +* bug #5989 NoAliasFunctionsFixer - Correct mapping (weshooper) +* bug #6004 SwitchContinueToBreakFixer - Fix candidate check (SpacePossum) +* bug #6005 CommentsAnalyzer - before static call (SpacePossum) +* bug #6007 YodaStyleFixer - PHP8 named arguments support (liquid207) +* bug #6015 CommentsAnalyzer - constructor property promotion support (liquid207) +* bug #6020 RegularCallableCallFixer - case insensitive fixing (SpacePossum) +* bug #6037 PhpdocLineSpanFixer - do not crash on trait imports (SpacePossum) +* feature #4834 AssignNullCoalescingToCoalesceEqualFixer - introduction (SpacePossum) +* feature #5754 ModernizeStrposFixer - introduction (derrabus, SpacePossum, keradus) +* feature #5858 EmptyLoopConditionFixer - introduction (SpacePossum) +* feature #5967 PHP8.1 - type "never" support (SpacePossum) +* feature #5968 PHP8.1 - "readonly" property modifier support (SpacePossum) +* feature #5970 IntegerLiteralCaseFixer - introduction (SpacePossum) +* feature #5971 PHP8.1 - Explicit octal integer literal notation (SpacePossum) +* feature #5997 NoSuperfluousPhpdocTagsFixer - Add union types support (julienfalque) +* feature #6026 TypeIntersectionTransformer - introduction (kubawerlos, SpacePossum) +* feature #6031 NoSpaceAroundDoubleColonFixer - introduction (SpacePossum) +* feature #6047 StringLengthToEmptyFixer - introduction (SpacePossum) +* minor #5773 NoAlternativeSyntaxFixer - Add option to not fix non-monolithic PHP code (paulbalandan) +* minor #5887 Detect renamed rules in configuration resolver (shakaran) +* minor #5901 DX: update PHPStan (kubawerlos) +* minor #5906 Remove references to PHP 7.0 in tests (with updates) (kubawerlos) +* minor #5918 Remove PHP version specific code sample constraint when not needed (kubawerlos) +* minor #5924 PSR12 - ClassDefinition - space_before_parenthesis (SpacePossum) +* minor #5925 DX: ProjectCodeTest - fix detection by testExpectedInputOrder (keradus) +* minor #5926 DX: remove not needed requirements from fixtures (kubawerlos) +* minor #5927 Symfonyset - EmptyLoopBody (SpacePossum) +* minor #5928 PhpdocTo*TypeFixer - add more test cases (keradus) +* minor #5929 Remove not needed PHP version checks (kubawerlos) +* minor #5930 simplify code, more tests (SpacePossum) +* minor #5931 logo copyright - bump year (SpacePossum) +* minor #5932 Extract ControlStructureContinuationPositionFixer from BracesFixer (julienfalque) +* minor #5933 Consistency invalid configuration exception for test (shakaran) +* minor #5934 Add return types (SpacePossum) +* minor #5949 Removed PHP 5 exception catch (GrahamCampbell) +* minor #5952 ClassAttributesSeparationFixer - Re-add omitted `only_if_meta` option (paulbalandan) +* minor #5957 Keep PHPStan cache between Docker runs (julienfalque) +* minor #5958 Fix STDIN test when path is one level deep (julienfalque) +* minor #5959 SymfonySet - add EmptyLoopConditionFixer (SpacePossum) +* minor #5961 Remove duplicated method (julienfalque) +* minor #5962 DX: Add return types (kubawerlos) +* minor #5963 DX: extract config for special CI jobs (keradus) +* minor #5964 DX: use modernize_strpos (keradus) +* minor #5965 CI: don't try to execute jobs with Symfony:^3 (keradus) +* minor #5972 PHP8.1 - FirstClassCallable (SpacePossum) +* minor #5973 PHP8.1 - "final const" support (SpacePossum) +* minor #5975 Tree shake PHP8.1 PRs (SpacePossum) +* minor #5978 PHP8.1 - Enum (start) (SpacePossum) +* minor #5982 Fix test warning (SpacePossum) +* minor #5987 PHP8.1 - Enum (start) (SpacePossum) +* minor #5995 Fix link to Code Climate SPEC.md in GitlabReporter (astehlik) +* minor #5996 Fix URL to Doctrine Annotations documentation (astehlik) +* minor #6000 Prevent PHP CS Fixer from fixing PHPStan cache files (julienfalque) +* minor #6006 SCA/utilize PHP8.1 (SpacePossum) +* minor #6008 SCA (SpacePossum) +* minor #6010 SCA (SpacePossum) +* minor #6011 NoSuperfluousPhpdocTagsFixer - Remove superfluous annotation `@abstract` and `@final` (liquid207, SpacePossum) +* minor #6018 PhpdocLineSpan - Allow certain types to be ignored (devfrey) +* minor #6019 Improve test coverage (SpacePossum) +* minor #6021 Linter/*Exception - Tag as final (SpacePossum) +* minor #6023 OrderedClassElementsFixer - PHP8.1 readonly properties support (SpacePossum) +* minor #6027 MbStrFunctionsFixer - more details about risky (SpacePossum) +* minor #6028 BinaryOperatorSpacesFixer - list all operators in doc (SpacePossum) +* minor #6029 PhpUnitDedicateAssertFixer - add "assertStringContainsString" and "as… (SpacePossum) +* minor #6030 SingleSpaceAfterConstructFixer - Add `switch` support (SpacePossum) +* minor #6033 ArgumentsAnalyzerTest - add more tests (SpacePossum) +* minor #6034 7.0|7.1 - cleanup tests (SpacePossum) +* minor #6035 Documentation generation split up and add list. (SpacePossum) +* minor #6048 Fix "can not" spelling (mvorisek) + +Changelog for v3.1.0 +-------------------- + +* feature #5572 PhpdocToCommentFixer - Add `ignored_tags` option (VincentLanglet) +* feature #5588 NoAliasFunctionsFixer - Add more function aliases (danog) +* feature #5704 ClassAttributesSeparationFixer - Introduce `only_if_meta` spacing option (paulbalandan) +* feature #5734 TypesSpacesFixer - Introduction (kubawerlos) +* feature #5745 EmptyLoopBodyFixer - introduction (SpacePossum, keradus) +* feature #5751 Extract DeclareParenthesesFixer from BracesFixer (julienfalque, keradus) +* feature #5877 ClassDefinitionFixer - PSR12 for anonymous class (SpacePossum) +* minor #5875 EmptyLoopBodyFixer - NoTrailingWhitespaceFixer - priority test (SpacePossum) +* minor #5914 Deprecate ClassKeywordRemoveFixer (kubawerlos) + +Changelog for v3.0.3 +-------------------- + +* bug #4927 PhpdocAlignFixer - fix for whitespace in type (kubawerlos) +* bug #5720 NoUnusedImportsFixer - Fix undetected unused imports when type mismatch (julienfalque, SpacePossum) +* bug #5806 DoctrineAnnotationFixer - Add template to ignored_tags (akalineskou) +* bug #5849 PhpdocTagTypeFixer - must not remove inlined tags within other tags (boesing) +* bug #5853 BracesFixer - handle alternative short foreach with if (SpacePossum) +* bug #5855 GlobalNamespaceImportFixer - fix for attributes imported as constants (kubawerlos) +* bug #5881 SelfUpdateCommand - fix link to UPGRADE docs (keradus) +* bug #5884 CurlyBraceTransformer - fix handling dynamic property with string with variable (kubawerlos, keradus) +* bug #5912 TypeAlternationTransformer - fix for "callable" type (kubawerlos) +* bug #5913 SingleSpaceAfterConstructFixer - improve comma handling (keradus) +* minor #5829 DX: Fix SCA with PHPMD (paulbalandan) +* minor #5838 PHP7 - use spaceship (SpacePossum, keradus) +* minor #5848 Docs: update PhpStorm integration link (keradus) +* minor #5856 Add AttributeAnalyzer (kubawerlos) +* minor #5857 DX: PHPMD - exclude fixtures (keradus) +* minor #5859 Various fixes (kubawerlos) +* minor #5864 DX: update dev tools (kubawerlos) +* minor #5876 AttributeTransformerTest - add more tests (SpacePossum) +* minor #5879 Update UPGRADE-v3.md adding relative links (shakaran, keradus) +* minor #5882 Docs: don't use v2 for installation example (keradus) +* minor #5883 Docs: typo (brianteeman, keradus) +* minor #5890 DX: use PHP 8.1 polyfill (keradus) +* minor #5902 Remove references to PHP 7.0 in tests (only removing lines) (kubawerlos) +* minor #5905 DX: Use "yield from" in tests (kubawerlos, keradus) +* minor #5917 Use `@PHP71Migration` rules (kubawerlos, keradus) + +Changelog for v3.0.2 +-------------------- + +* bug #5816 FullyQualifiedStrictTypesFixer - fix for union types (kubawerlos, keradus) +* bug #5835 PhpdocTypesOrderFixer: fix for array shapes (kubawerlos) +* bug #5837 SingleImportPerStatementFixer - fix const and function imports (SpacePossum) +* bug #5844 PhpdocTypesOrderFixer: handle callable() type (Slamdunk) +* minor #5839 DX: automate checking 7.0 types on project itself (keradus) +* minor #5840 DX: drop v2 compatible config in project itself (keradus) + +Changelog for v3.0.1 +-------------------- + +* bug #5395 PhpdocTagTypeFixer: Do not modify array shapes (localheinz, julienfalque) +* bug #5678 UseArrowFunctionsFixer - fix for return without value (kubawerlos) +* bug #5679 PhpUnitNamespacedFixer - do not try to fix constant usage (kubawerlos) +* bug #5681 RegularCallableCallFixer - fix for function name with escaped slash (kubawerlos) +* bug #5687 FinalInternalClassFixer - fix for annotation with space after "@" (kubawerlos) +* bug #5688 ArrayIndentationFixer - fix for really long arrays (kubawerlos) +* bug #5690 PhpUnitNoExpectationAnnotationFixer - fix "expectedException" annotation with message below (kubawerlos) +* bug #5693 YodaStyleFixer - fix for assignment operators (kubawerlos) +* bug #5697 StrictParamFixer - fix for method definition (kubawerlos) +* bug #5702 CommentToPhpdocFixer - fix for single line comments starting with more than 2 slashes (kubawerlos) +* bug #5703 DateTimeImmutableFixer - fix for method definition (kubawerlos) +* bug #5718 VoidReturnFixer - do not break syntax with magic methods (kubawerlos) +* bug #5727 SingleSpaceAfterConstructFixer - Add support for `namespace` (julienfalque) +* bug #5730 Fix transforming deprecations into exceptions (julienfalque) +* bug #5738 TokensAnalyzer - fix for union types (kubawerlos) +* bug #5741 Fix constant invocation detection cases (kubawerlos) +* bug #5769 Fix priority between `phpdoc_to_property_type` and `no_superfluous_phpdoc_tags` (julienfalque) +* bug #5774 FunctionsAnalyzer::isTheSameClassCall - fix for $this with double colon following (kubawerlos) +* bug #5779 SingleLineThrowFixer - fix for throw in match (kubawerlos) +* bug #5781 ClassDefinition - fix for anonymous class with trailing comma (kubawerlos) +* bug #5783 StaticLambdaFixer - consider parent:: as a possible reference to $this (fancyweb) +* bug #5791 NoBlankLinesAfterPhpdoc - Add T_NAMESPACE in array of forbidden successors (paulbalandan) +* bug #5799 TypeAlternationTransformer - fix for multiple function parameters (kubawerlos) +* bug #5804 NoBreakCommentFixer - fix for "default" in "match" (kubawerlos) +* bug #5805 SingleLineCommentStyleFixer - run after HeaderCommentFixer (kubawerlos) +* bug #5817 NativeFunctionTypeDeclarationCasingFixer - fix for union types (kubawerlos) +* bug #5823 YodaStyleFixer - yield support (SpacePossum) +* minor #4914 Improve PHPDoc types support (julienfalque, keradus) +* minor #5592 Fix checking for default config used in rule sets (kubawerlos) +* minor #5675 Docs: extend Upgrade Guide (keradus) +* minor #5680 DX: benchmark.sh - ensure deps are updated to enable script working across less-similar branches (keradus) +* minor #5689 Calculate code coverage on PHP 8 (kubawerlos) +* minor #5694 DX: fail on risky tests (kubawerlos) +* minor #5695 Utils - save only unique deprecations to avoid memory issues (PetrHeinz) +* minor #5710 [typo] add correct backquotes (PhilETaylor) +* minor #5711 Fix doc, "run-in" show-progress option is no longer present (mvorisek) +* minor #5713 Upgrade-Guide: fix typo (staabm) +* minor #5717 Run migration rules on PHP 8 (kubawerlos, keradus) +* minor #5721 Fix reStructuredText markup (julienfalque) +* minor #5725 Update LICENSE (exussum12) +* minor #5731 CI - Fix checkbashisms installation (julienfalque) +* minor #5736 Remove references to PHP 5.6 (kubawerlos, keradus) +* minor #5739 DX: more typehinting (keradus) +* minor #5740 DX: more type-related docblocks (keradus) +* minor #5746 Config - Improve deprecation message with details (SpacePossum) +* minor #5747 RandomApiMigrationFixer - better docs and better "random_int" support (SpacePossum) +* minor #5748 Updated the link to netbeans plugins page (cyberguroo) +* minor #5750 Test all const are in uppercase (SpacePossum) +* minor #5752 NoNullPropertyInitializationFixer - fix static properties as well (HypeMC) +* minor #5756 Fix rule sets descriptions (kubawerlos) +* minor #5761 Fix links in custom rules documentation (julienfalque) +* minor #5771 doc(config): change set's name (Kocal) +* minor #5777 DX: update PHPStan (kubawerlos) +* minor #5789 DX: update PHPStan (kubawerlos) +* minor #5808 Update PHPStan to 0.12.92 (kubawerlos) +* minor #5813 Docs: point to v3 in installation description (Jimbolino) +* minor #5824 Deprecate v2 (keradus) +* minor #5825 DX: update checkbashisms to v2.21.3 (keradus) +* minor #5826 SCA: check both composer files (keradus) +* minor #5827 ClassAttributesSeparationFixer - Add `trait_import` support (SpacePossum) +* minor #5831 DX: fix SCA violations (keradus) + +Changelog for v3.0.0 +-------------------- + +* bug #5164 Differ - surround file name with double quotes if it contains spacing. (SpacePossum) +* bug #5560 PSR2: require visibility only for properties and methods (kubawerlos) +* bug #5576 ClassAttributesSeparationFixer: do not allow using v2 config (kubawerlos) +* feature #4979 Pass file to differ (paulhenri-l, SpacePossum) +* minor #3374 show-progress option: drop run-in and estimating, rename estimating-max to dots (keradus) +* minor #3375 Fixers - stop exposing extra properties/consts (keradus) +* minor #3376 Tokenizer - remove deprecations and legacy mode (keradus) +* minor #3377 rules - change default options (keradus) +* minor #3378 SKIP_LINT_TEST_CASES - drop env (keradus) +* minor #3379 MethodArgumentSpaceFixer - fixSpace is now private (keradus) +* minor #3380 rules - drop rootless configurations (keradus) +* minor #3381 rules - drop deprecated configurations (keradus) +* minor #3382 DefinedFixerInterface - incorporate into FixerInterface (keradus) +* minor #3383 FixerDefinitionInterface - drop getConfigurationDescription and getDefaultConfiguration (keradus) +* minor #3384 diff-format option: drop sbd diff, use udiffer by default, drop SebastianBergmannDiffer and SebastianBergmannShortDiffer classes (keradus) +* minor #3385 ConfigurableFixerInterface::configure - param is now not nullable and not optional (keradus) +* minor #3386 ConfigurationDefinitionFixerInterface - incorporate into ConfigurableFixerInterface (keradus) +* minor #3387 FixCommand - forbid passing 'config' and 'rules' options together (keradus) +* minor #3388 Remove Helpers (keradus) +* minor #3389 AccessibleObject - drop class (keradus) +* minor #3390 Drop deprecated rules: blank_line_before_return, hash_to_slash_comment, method_separation, no_extra_consecutive_blank_lines, no_multiline_whitespace_before_semicolons and pre_increment (keradus) +* minor #3456 AutoReview - drop references to removed rule (keradus) +* minor #3659 use php-cs-fixer/diff ^2.0 (SpacePossum) +* minor #3681 CiIntegrationTest - fix incompatibility from 2.x line (keradus) +* minor #3740 NoUnusedImportsFixer - remove SF exception (SpacePossum) +* minor #3771 UX: always set error_reporting in entry file, not Application (keradus) +* minor #3922 Make some more classes final (ntzm, SpacePossum) +* minor #3995 Change default config of native_function_invocation (dunglas, SpacePossum) +* minor #4432 DX: remove empty sets from RuleSet (kubawerlos) +* minor #4489 Fix ruleset @PHPUnit50Migration:risky (kubawerlos) +* minor #4620 DX: cleanup additional, not used parameters (keradus) +* minor #4666 Remove deprecated rules: lowercase_constants, php_unit_ordered_covers, silenced_deprecation_error (keradus) +* minor #4697 Remove deprecated no_short_echo_tag rule (julienfalque) +* minor #4851 fix phpstan on 3.0 (SpacePossum) +* minor #4901 Fix SCA (SpacePossum) +* minor #5069 Fixed failing tests on 3.0 due to unused import after merge (GrahamCampbell) +* minor #5096 NativeFunctionInvocationFixer - BacktickToShellExecFixer - fix integration test (SpacePossum) +* minor #5171 Fix test (SpacePossum) +* minor #5245 Fix CI for 3.0 line (keradus) +* minor #5351 clean ups (SpacePossum) +* minor #5364 DX: Do not display runtime twice on 3.0 line (keradus) +* minor #5412 3.0 - cleanup (SpacePossum, keradus) +* minor #5417 Further BC cleanup for 3.0 (keradus) +* minor #5418 Drop src/Test namespace (keradus) +* minor #5436 Drop mapping of strings to boolean option other than yes/no (keradus) +* minor #5440 Change default ruleset to PSR-12 (keradus) +* minor #5477 Drop diff-format (keradus) +* minor #5478 Docs: Cleanup UPGRADE markdown files (keradus) +* minor #5479 ArraySyntaxFixer, ListSyntaxFixer - change default syntax to short (keradus) +* minor #5480 Tokens::findBlockEnd - drop deprecated argument (keradus) +* minor #5485 ClassAttributesSeparationFixer - drop deprecated flat list configuration (keradus) +* minor #5486 CI: drop unused env variables (keradus) +* minor #5488 Do not distribute documentation (szepeviktor) +* minor #5513 DX: Tokens::warnPhp8SplFixerArrayChange - drop unused method (keradus) +* minor #5520 DX: Drop IsIdenticalConstraint (keradus) +* minor #5521 DX: apply rules configuration cleanups for PHP 7.1+ (keradus) +* minor #5524 DX: drop support of very old deps (keradus) +* minor #5525 Drop phpunit-legacy-adapter (keradus) +* minor #5527 Bump required PHP to 7.1 (keradus) +* minor #5529 DX: bump required PHPUnit to v7+ (keradus) +* minor #5532 Apply PHP 7.1 typing (keradus) +* minor #5541 RuleSet - disallow null usage to disable the rule (keradus) +* minor #5555 DX: further typing improvements (keradus) +* minor #5562 Fix table row rendering for default values of array_syntax and list_syntax (derrabus) +* minor #5608 DX: new cache filename (keradus) +* minor #5609 Forbid old config filename usage (keradus) +* minor #5638 DX: remove Utils::calculateBitmask (keradus) +* minor #5641 DX: use constants for PHPUnit version on 3.0 line (keradus) +* minor #5643 FixCommand - simplify help (keradus) +* minor #5644 Token::toJson() - remove parameter (keradus) +* minor #5645 DX: YodaStyleFixerTest - fix CI (keradus) +* minor #5649 DX: YodaStyleFixerTest - fix 8.0 compat (keradus) +* minor #5650 DX: FixCommand - drop outdated/duplicated docs (keradus) +* minor #5656 DX: mark some constants as internal or private (keradus) +* minor #5657 DX: convert some properties to constants (keradus) +* minor #5669 Remove TrailingCommaInMultilineArrayFixer (kubawerlos, keradus) + +Changelog for v2.19.3 +--------------------- + +* minor #6060 DX: Add upgrade guide link when next Major is available (keradus) + +Changelog for v2.19.2 +--------------------- + +* bug #5881 SelfUpdateCommand - fix link to UPGRADE docs (keradus) + +Changelog for v2.19.1 +--------------------- + +* bug #5395 PhpdocTagTypeFixer: Do not modify array shapes (localheinz, julienfalque) +* bug #5678 UseArrowFunctionsFixer - fix for return without value (kubawerlos) +* bug #5679 PhpUnitNamespacedFixer - do not try to fix constant usage (kubawerlos) +* bug #5681 RegularCallableCallFixer - fix for function name with escaped slash (kubawerlos) +* bug #5687 FinalInternalClassFixer - fix for annotation with space after "@" (kubawerlos) +* bug #5688 ArrayIndentationFixer - fix for really long arrays (kubawerlos) +* bug #5690 PhpUnitNoExpectationAnnotationFixer - fix "expectedException" annotation with message below (kubawerlos) +* bug #5693 YodaStyleFixer - fix for assignment operators (kubawerlos) +* bug #5697 StrictParamFixer - fix for method definition (kubawerlos) +* bug #5702 CommentToPhpdocFixer - fix for single line comments starting with more than 2 slashes (kubawerlos) +* bug #5703 DateTimeImmutableFixer - fix for method definition (kubawerlos) +* bug #5718 VoidReturnFixer - do not break syntax with magic methods (kubawerlos) +* bug #5727 SingleSpaceAfterConstructFixer - Add support for `namespace` (julienfalque) +* bug #5730 Fix transforming deprecations into exceptions (julienfalque) +* bug #5738 TokensAnalyzer - fix for union types (kubawerlos) +* bug #5741 Fix constant invocation detection cases (kubawerlos) +* bug #5769 Fix priority between `phpdoc_to_property_type` and `no_superfluous_phpdoc_tags` (julienfalque) +* bug #5774 FunctionsAnalyzer::isTheSameClassCall - fix for $this with double colon following (kubawerlos) +* bug #5779 SingleLineThrowFixer - fix for throw in match (kubawerlos) +* bug #5781 ClassDefinition - fix for anonymous class with trailing comma (kubawerlos) +* bug #5783 StaticLambdaFixer - consider parent:: as a possible reference to $this (fancyweb) +* bug #5791 NoBlankLinesAfterPhpdoc - Add T_NAMESPACE in array of forbidden successors (paulbalandan) +* bug #5799 TypeAlternationTransformer - fix for multiple function parameters (kubawerlos) +* bug #5804 NoBreakCommentFixer - fix for "default" in "match" (kubawerlos) +* bug #5805 SingleLineCommentStyleFixer - run after HeaderCommentFixer (kubawerlos) +* bug #5817 NativeFunctionTypeDeclarationCasingFixer - fix for union types (kubawerlos) +* bug #5823 YodaStyleFixer - yield support (SpacePossum) +* minor #4914 Improve PHPDoc types support (julienfalque, keradus) +* minor #5680 DX: benchmark.sh - ensure deps are updated to enable script working across less-similar branches (keradus) +* minor #5689 Calculate code coverage on PHP 8 (kubawerlos) +* minor #5694 DX: fail on risky tests (kubawerlos) +* minor #5695 Utils - save only unique deprecations to avoid memory issues (PetrHeinz) +* minor #5710 [typo] add correct backquotes (PhilETaylor) +* minor #5717 Run migration rules on PHP 8 (kubawerlos, keradus) +* minor #5721 Fix reStructuredText markup (julienfalque) +* minor #5725 Update LICENSE (exussum12) +* minor #5731 CI - Fix checkbashisms installation (julienfalque) +* minor #5740 DX: more type-related docblocks (keradus) +* minor #5746 Config - Improve deprecation message with details (SpacePossum) +* minor #5747 RandomApiMigrationFixer - better docs and better "random_int" support (SpacePossum) +* minor #5748 Updated the link to netbeans plugins page (cyberguroo) +* minor #5750 Test all const are in uppercase (SpacePossum) +* minor #5752 NoNullPropertyInitializationFixer - fix static properties as well (HypeMC) +* minor #5756 Fix rule sets descriptions (kubawerlos) +* minor #5761 Fix links in custom rules documentation (julienfalque) +* minor #5777 DX: update PHPStan (kubawerlos) +* minor #5789 DX: update PHPStan (kubawerlos) +* minor #5808 Update PHPStan to 0.12.92 (kubawerlos) +* minor #5824 Deprecate v2 (keradus) +* minor #5825 DX: update checkbashisms to v2.21.3 (keradus) +* minor #5826 SCA: check both composer files (keradus) +* minor #5827 ClassAttributesSeparationFixer - Add `trait_import` support (SpacePossum) + +Changelog for v2.19.0 +--------------------- + +* feature #4238 TrailingCommaInMultilineFixer - introduction (kubawerlos) +* feature #4592 PhpdocToPropertyTypeFixer - introduction (julienfalque) +* feature #5390 feature #4024 added a `list-files` command (clxmstaab, keradus) +* feature #5635 Add list-sets command (keradus) +* feature #5674 UX: Display deprecations to end-user (keradus) +* minor #5601 Always stop when "PHP_CS_FIXER_FUTURE_MODE" is used (kubawerlos) +* minor #5607 DX: new config filename (keradus) +* minor #5613 DX: UtilsTest - add missing teardown (keradus) +* minor #5631 DX: config deduplication (keradus) +* minor #5633 fix typos (staabm) +* minor #5642 Deprecate parameter of Token::toJson() (keradus) +* minor #5672 DX: do not test deprecated fixer (kubawerlos) + +Changelog for v2.18.7 +--------------------- + +* bug #5593 SingleLineThrowFixer - fix handling anonymous classes (kubawerlos) +* bug #5654 SingleLineThrowFixer - fix for match expression (kubawerlos) +* bug #5660 TypeAlternationTransformer - fix for "array" type in type alternation (kubawerlos) +* bug #5665 NullableTypeDeclarationForDefaultNullValueFixer - fix for nullable with attribute (kubawerlos) +* bug #5670 PhpUnitNamespacedFixer - do not try to fix constant (kubawerlos) +* bug #5671 PhpdocToParamTypeFixer - do not change function call (kubawerlos) +* bug #5673 GroupImportFixer - Fix failing case (julienfalque) +* minor #4591 Refactor conversion of PHPDoc to type declarations (julienfalque, keradus) +* minor #5611 DX: use method expectDeprecation from Symfony Bridge instead of annotation (kubawerlos) +* minor #5658 DX: use constants in tests for Fixer configuration (keradus) +* minor #5661 DX: remove PHPStan exceptions for "tests" from phpstan.neon (kubawerlos) +* minor #5662 Change wording from "merge" to "intersect" (jschaedl) +* minor #5663 DX: do not abuse "inheritdoc" tag (kubawerlos) +* minor #5664 DX: code grooming (keradus) + +Changelog for v2.18.6 +--------------------- + +* bug #5586 Add support for nullsafe object operator ("?->") (kubawerlos) +* bug #5597 Tokens - fix for checking block edges (kubawerlos) +* bug #5604 Custom annotations @type changed into @var (Leprechaunz) +* bug #5606 DoctrineAnnotationBracesFixer false positive (Leprechaunz) +* bug #5610 BracesFixer - fix braces of match expression (Leprechaunz) +* bug #5615 GroupImportFixer severely broken (Leprechaunz) +* bug #5617 ClassAttributesSeparationFixer - fix for using visibility for class elements (kubawerlos) +* bug #5618 GroupImportFixer - fix removal of import type when mixing multiple types (Leprechaunz) +* bug #5622 Exclude Doctrine documents from final fixer (ossinkine) +* bug #5630 PhpdocTypesOrderFixer - handle complex keys (Leprechaunz) +* minor #5554 DX: use tmp file in sys_temp_dir for integration tests (keradus) +* minor #5564 DX: make integration tests matching entries in FixerFactoryTest (kubawerlos) +* minor #5603 DX: DocumentationGenerator - no need to re-configure Differ (keradus) +* minor #5612 DX: use ::class whenever possible (kubawerlos) +* minor #5619 DX: allow XDebugHandler v2 (keradus) +* minor #5623 DX: when displaying app version, don't put extra space if there is no CODENAME available (keradus) +* minor #5626 DX: update PHPStan and way of ignoring flickering PHPStan exception (keradus) +* minor #5629 DX: fix CiIntegrationTest (keradus) +* minor #5636 DX: remove 'create' method in internal classes (keradus) +* minor #5637 DX: do not calculate bitmap via helper anymore (keradus) +* minor #5639 Move fix reports (classes and schemas) (keradus) +* minor #5640 DX: use constants for PHPUnit version (keradus) +* minor #5646 Cleanup YodaStyleFixerTest (kubawerlos) + +Changelog for v2.18.5 +--------------------- + +* bug #5561 NoMixedEchoPrintFixer: fix for conditions without curly brackets (kubawerlos) +* bug #5563 Priority fix: SingleSpaceAfterConstructFixer must run before BracesFixer (kubawerlos) +* bug #5567 Fix order of BracesFixer and ClassDefinitionFixer (Daeroni) +* bug #5596 NullableTypeTransformer - fix for attributes (kubawerlos, jrmajor) +* bug #5598 GroupImportFixer - fix breaking code when fixing root classes (Leprechaunz) +* minor #5571 DX: add test to make sure SingleSpaceAfterConstructFixer runs before FunctionDeclarationFixer (kubawerlos) +* minor #5577 Extend priority test for "class_definition" vs "braces" (kubawerlos) +* minor #5585 DX: make doc examples prettier (kubawerlos) +* minor #5590 Docs: HeaderCommentFixer - document example how to remove header comment (keradus) +* minor #5602 DX: regenerate docs (keradus) + +Changelog for v2.18.4 +--------------------- + +* bug #4085 Priority: AlignMultilineComment should run before every PhpdocFixer (dmvdbrugge) +* bug #5421 PsrAutoloadingFixer - Fix PSR autoloading outside configured directory (kelunik, keradus) +* bug #5464 NativeFunctionInvocationFixer - PHP 8 attributes (HypeMC, keradus) +* bug #5548 NullableTypeDeclarationForDefaultNullValueFixer - fix handling promoted properties (jrmajor, keradus) +* bug #5550 TypeAlternationTransformer - fix for typed static properties (kubawerlos) +* bug #5551 ClassAttributesSeparationFixer - fix for properties with type alternation (kubawerlos, keradus) +* bug #5552 DX: test relation between function_declaration and method_argument_space (keradus) +* minor #5540 DX: RuleSet - convert null handling to soft-warning (keradus) +* minor #5545 DX: update checkbashisms (keradus) + +Changelog for v2.18.3 +--------------------- + +* bug #5484 NullableTypeDeclarationForDefaultNullValueFixer - handle mixed pseudotype (keradus) +* minor #5470 Disable CI fail-fast (mvorisek) +* minor #5491 Support php8 static return type for NoSuperfluousPhpdocTagsFixer (tigitz) +* minor #5494 BinaryOperatorSpacesFixer - extend examples (keradus) +* minor #5499 DX: add TODOs for PHP requirements cleanup (keradus) +* minor #5500 DX: Test that Transformers are adding only CustomTokens that they define and nothing else (keradus) +* minor #5507 Fix quoting in exception message (gquemener) +* minor #5514 DX: PHP 7.0 integration test - solve TODO for random_api_migration usage (keradus) +* minor #5515 DX: do not override getConfigurationDefinition (keradus) +* minor #5516 DX: AbstractDoctrineAnnotationFixer - no need for import aliases (keradus) +* minor #5518 DX: minor typing and validation fixes (keradus) +* minor #5522 Token - add handling json_encode crash (keradus) +* minor #5523 DX: EregToPregFixer - fix sorting (keradus) +* minor #5528 DX: code cleanup (keradus) + +Changelog for v2.18.2 +--------------------- + +* bug #5466 Fix runtime check of PHP version (keradus) +* minor #4250 POC Tokens::insertSlices (keradus) + +Changelog for v2.18.1 +--------------------- + +* bug #5447 switch_case_semicolon_to_colon should skip match/default statements (derrabus) +* bug #5453 SingleSpaceAfterConstructFixer - better handling of closing parenthesis and brace (keradus) +* bug #5454 NullableTypeDeclarationForDefaultNullValueFixer - support property promotion via constructor (keradus) +* bug #5455 PhpdocToCommentFixer - add support for attributes (keradus) +* bug #5462 NullableTypeDeclarationForDefaultNullValueFixer - support union types (keradus) +* minor #5444 Fix PHP version number in PHP54MigrationSet description (jdreesen, keradus) +* minor #5445 DX: update usage of old TraversableContains in tests (keradus) +* minor #5456 DX: Fix CiIntegrationTest (keradus) +* minor #5457 CI: fix params order (keradus) +* minor #5458 CI: fix migration workflow (keradus) +* minor #5459 DX: cleanup PHP Migration rulesets (keradus) + +Changelog for v2.18.0 +--------------------- + +* feature #4943 Add PSR12 ruleset (julienfalque, keradus) +* feature #5426 Update Symfony ruleset (keradus) +* feature #5428 Add/Change PHP.MigrationSet to update array/list syntax to short one (keradus) +* minor #5441 Allow execution under PHP 8 (keradus) + +Changelog for v2.17.5 +--------------------- + +* bug #5447 switch_case_semicolon_to_colon should skip match/default statements (derrabus) +* bug #5453 SingleSpaceAfterConstructFixer - better handling of closing parenthesis and brace (keradus) +* bug #5454 NullableTypeDeclarationForDefaultNullValueFixer - support property promotion via constructor (keradus) +* bug #5455 PhpdocToCommentFixer - add support for attributes (keradus) +* bug #5462 NullableTypeDeclarationForDefaultNullValueFixer - support union types (keradus) +* minor #5445 DX: update usage of old TraversableContains in tests (keradus) +* minor #5456 DX: Fix CiIntegrationTest (keradus) +* minor #5457 CI: fix params order (keradus) +* minor #5459 DX: cleanup PHP Migration rulesets (keradus) + +Changelog for v2.17.4 +--------------------- + +* bug #5379 PhpUnitMethodCasingFixer - Do not modify class name (localheinz) +* bug #5404 NullableTypeTransformer - constructor property promotion support (Wirone) +* bug #5433 PhpUnitTestCaseStaticMethodCallsFixer - fix for abstract static method (kubawerlos) +* minor #5234 DX: Add Docker dev setup (julienfalque, keradus) +* minor #5391 PhpdocOrderByValueFixer - Add additional annotations to sort (localheinz) +* minor #5392 PhpdocScalarFixer - Fix description (localheinz) +* minor #5397 NoExtraBlankLinesFixer - PHP8 throw support (SpacePossum) +* minor #5399 Add PHP8 integration test (keradus) +* minor #5405 TypeAlternationTransformer - add support for PHP8 (SpacePossum) +* minor #5406 SingleSpaceAfterConstructFixer - Attributes, comments and PHPDoc support (SpacePossum) +* minor #5407 TokensAnalyzer::getClassyElements - return trait imports (SpacePossum) +* minor #5410 minors (SpacePossum) +* minor #5411 bump year in LICENSE file (SpacePossum) +* minor #5414 TypeAlternationTransformer - T_FN support (SpacePossum) +* minor #5415 Forbid execution under PHP 8.0.0 (keradus) +* minor #5416 Drop Travis CI (keradus) +* minor #5419 CI: separate SCA checks to dedicated jobs (keradus) +* minor #5420 DX: unblock PHPUnit 9.5 (keradus) +* minor #5423 DX: PHPUnit - disable verbose by default (keradus) +* minor #5425 Cleanup 3.0 todos (keradus) +* minor #5427 Plan changing defaults for array_syntax and list_syntax in 3.0 release (keradus) +* minor #5429 DX: Drop speedtrap PHPUnit listener (keradus) +* minor #5432 Don't allow unserializing classes with a destructor (jderusse) +* minor #5435 DX: PHPUnit - groom configuration of time limits (keradus) +* minor #5439 VisibilityRequiredFixer - support type alternation for properties (keradus) +* minor #5442 DX: FunctionsAnalyzerTest - add missing 7.0 requirement (keradus) + +Changelog for v2.17.3 +--------------------- + +* bug #5384 PsrAutoloadingFixer - do not remove directory structure from the Class name (kubawerlos, keradus) +* bug #5385 SingleLineCommentStyleFixer- run before NoUselessReturnFixer (kubawerlos) +* bug #5387 SingleSpaceAfterConstructFixer - do not touch multi line implements (SpacePossum) +* minor #5329 DX: collect coverage with Github Actions (kubawerlos) +* minor #5380 PhpdocOrderByValueFixer - Allow sorting of throws annotations by value (localheinz, keradus) +* minor #5383 DX: fail PHPUnit tests on warning (kubawerlos) +* minor #5386 DX: remove incorrect priority relations (kubawerlos) + +Changelog for v2.17.2 +--------------------- + +* bug #5345 CleanNamespaceFixer - preserve trailing comments (SpacePossum) +* bug #5348 PsrAutoloadingFixer - fix for class without namespace (kubawerlos) +* bug #5362 SingleSpaceAfterConstructFixer: Do not adjust whitespace before multiple multi-line extends (localheinz, SpacePossum) +* minor #5314 Enable testing with PHPUnit 9.x (sanmai) +* minor #5319 Clean ups (SpacePossum) +* minor #5338 clean ups (SpacePossum) +* minor #5339 NoEmptyStatementFixer - fix more cases (SpacePossum) +* minor #5340 NamedArgumentTransformer - Introduction (SpacePossum) +* minor #5344 Update docs: do not use deprecated create method (SpacePossum) +* minor #5353 Fix typo in issue template (stof) +* minor #5355 OrderedTraitsFixer - mark as risky (SpacePossum) +* minor #5356 RuleSet description fixes (SpacePossum) +* minor #5359 Add application version to "fix" out put when verbosity flag is set (SpacePossum) +* minor #5360 DX: clean up detectIndent methods (kubawerlos) +* minor #5363 Added missing self return type to ConfigInterface::registerCustomFixers() (vudaltsov) +* minor #5366 PhpUnitDedicateAssertInternalTypeFixer - recover target option (keradus) +* minor #5368 DX: PHPUnit 9 compatibility for 2.17 (keradus) +* minor #5370 DX: update PHPUnit usage to use external Prophecy trait and solve warning (keradus) +* minor #5371 Update documentation about PHP_CS_FIXER_IGNORE_ENV (SanderSander, keradus) +* minor #5373 DX: MagicMethodCasingFixerTest - fix test case description (keradus) +* minor #5374 DX: PhpUnitDedicateAssertInternalTypeFixer - add code sample for non-default config (keradus) + +Changelog for v2.17.1 +--------------------- + +* bug #5325 NoBreakCommentFixer - better throw handling (SpacePossum) +* bug #5327 StaticLambdaFixer - fix for arrow function used in class with $this (kubawerlos, SpacePossum) +* bug #5332 Fix file missing for php8 (jderusse) +* bug #5333 Fix file missing for php8 (jderusse) +* minor #5328 Fixed deprecation message version (GrahamCampbell) +* minor #5330 DX: cleanup Github Actions configs (kubawerlos) + +Changelog for v2.17.0 +--------------------- + +* bug #4752 SimpleLambdaCallFixer - bug fixes (SpacePossum) +* bug #4794 TernaryToElvisOperatorFixer - fix open tag with echo (SpacePossum) +* bug #5084 Fix for variables within string interpolation in lambda_not_used_import (GrahamCampbell) +* bug #5094 SwitchContinueToBreakFixer - do not support alternative syntax (SpacePossum) +* feature #2619 PSR-5 @inheritDoc support (julienfalque) +* feature #3253 Add SimplifiedIfReturnFixer (Slamdunk, SpacePossum) +* feature #4005 GroupImportFixer - introduction (greeflas) +* feature #4012 BracesFixer - add "allow_single_line_anonymous_class_with_empty_body" option (kubawerlos) +* feature #4021 OperatorLinebreakFixer - Introduction (kubawerlos, SpacePossum) +* feature #4259 PsrAutoloadingFixer - introduction (kubawerlos) +* feature #4375 extend ruleset "@PHP73Migration" (gharlan) +* feature #4435 SingleSpaceAfterConstructFixer - Introduction (localheinz) +* feature #4493 Add echo_tag_syntax rule (mlocati, kubawerlos) +* feature #4544 SimpleLambdaCallFixer - introduction (keradus) +* feature #4569 PhpdocOrderByValueFixer - Introduction (localheinz) +* feature #4590 SwitchContinueToBreakFixer - Introduction (SpacePossum) +* feature #4679 NativeConstantInvocationFixer - add "strict" flag (kubawerlos) +* feature #4701 OrderedTraitsFixer - introduction (julienfalque) +* feature #4704 LambdaNotUsedImportFixer - introduction (SpacePossum) +* feature #4740 NoAliasLanguageConstructCallFixer - introduction (SpacePossum) +* feature #4741 TernaryToElvisOperatorFixer - introduction (SpacePossum) +* feature #4778 UseArrowFunctionsFixer - introduction (gharlan) +* feature #4790 ArrayPushFixer - introduction (SpacePossum) +* feature #4800 NoUnneededFinalMethodFixer - Add "private_methods" option (SpacePossum) +* feature #4831 BlankLineBeforeStatementFixer - add yield from (SpacePossum) +* feature #4832 NoUnneededControlParenthesesFixer - add yield from (SpacePossum) +* feature #4863 NoTrailingWhitespaceInStringFixer - introduction (gharlan) +* feature #4875 ClassAttributesSeparationFixer - add option for no new lines between properties (adri, ruudk) +* feature #4880 HeredocIndentationFixer - config option for indentation level (gharlan) +* feature #4908 PhpUnitExpectationFixer - update for Phpunit 8.4 (ktomk) +* feature #4942 OrderedClassElementsFixer - added support for abstract method sorting (carlalexander, SpacePossum) +* feature #4947 NativeConstantInvocation - Add "PHP_INT_SIZE" to SF rule set (kubawerlos) +* feature #4953 Add support for custom differ (paulhenri-l, SpacePossum) +* feature #5264 CleanNamespaceFixer - Introduction (SpacePossum) +* feature #5280 NoUselessSprintfFixer - Introduction (SpacePossum) +* minor #4634 Make all options snake_case (kubawerlos) +* minor #4667 PhpUnitOrderedCoversFixer - stop using deprecated fixer (keradus) +* minor #4673 FinalStaticAccessFixer - deprecate (julienfalque) +* minor #4762 Rename simple_lambda_call to regular_callable_call (julienfalque) +* minor #4782 Update RuleSets (SpacePossum) +* minor #4802 Master cleanup (SpacePossum) +* minor #4828 Deprecate Config::create() (DocFX) +* minor #4872 Update RuleSet SF and PHP-CS-Fixer with new config for `no_extra_blan… (SpacePossum) +* minor #4900 Move "no_trailing_whitespace_in_string" to SF ruleset. (SpacePossum) +* minor #4903 Docs: extend regular_callable_call rule docs (keradus, SpacePossum) +* minor #4910 Add use_arrow_functions rule to PHP74Migration:risky set (keradus) +* minor #5025 PhpUnitDedicateAssertInternalTypeFixer - deprecate "target" option (kubawerlos) +* minor #5037 FinalInternalClassFixer- Rename option (SpacePossum) +* minor #5093 LambdaNotUsedImportFixer - add heredoc test (SpacePossum) +* minor #5163 Fix CS (SpacePossum) +* minor #5169 PHP8 care package master (SpacePossum) +* minor #5186 Fix tests (SpacePossum) +* minor #5192 GotoLabelAnalyzer - introduction (SpacePossum) +* minor #5230 Fix: Reference (localheinz) +* minor #5240 PHP8 - Allow trailing comma in parameter list support (SpacePossum) +* minor #5244 Fix 2.17 build (keradus) +* minor #5251 PHP8 - match support (SpacePossum) +* minor #5252 Update RuleSets (SpacePossum) +* minor #5278 PHP8 constructor property promotion support (SpacePossum) +* minor #5284 PHP8 - Attribute support (SpacePossum) +* minor #5323 NoUselessSprintfFixer - Fix test on PHP5.6 (SpacePossum) +* minor #5326 DX: relax composer requirements to not block installation under PHP v8, support for PHP v8 is not yet ready (keradus) + + +Changelog for v2.16.10 +---------------------- + +* minor #5314 Enable testing with PHPUnit 9.x (sanmai) +* minor #5338 clean ups (SpacePossum) +* minor #5339 NoEmptyStatementFixer - fix more cases (SpacePossum) +* minor #5340 NamedArgumentTransformer - Introduction (SpacePossum) +* minor #5344 Update docs: do not use deprecated create method (SpacePossum) +* minor #5356 RuleSet description fixes (SpacePossum) +* minor #5360 DX: clean up detectIndent methods (kubawerlos) +* minor #5370 DX: update PHPUnit usage to use external Prophecy trait and solve warning (keradus) +* minor #5373 DX: MagicMethodCasingFixerTest - fix test case description (keradus) +* minor #5374 DX: PhpUnitDedicateAssertInternalTypeFixer - add code sample for non-default config (keradus) + +Changelog for v2.16.9 +--------------------- + +* bug #5095 Annotation - fix for Windows line endings (SpacePossum) +* bug #5221 NoSuperfluousPhpdocTagsFixer - fix for single line PHPDoc (kubawerlos) +* bug #5225 TernaryOperatorSpacesFixer - fix for alternative control structures (kubawerlos) +* bug #5235 ArrayIndentationFixer - fix for nested arrays (kubawerlos) +* bug #5248 NoBreakCommentFixer - fix throw detect (SpacePossum) +* bug #5250 SwitchAnalyzer - fix for semicolon after case/default (kubawerlos) +* bug #5253 IO - fix cache info message (SpacePossum) +* bug #5273 Fix PHPDoc line span fixer when property has array typehint (ossinkine) +* bug #5274 TernaryToNullCoalescingFixer - concat precedence fix (SpacePossum) +* feature #5216 Add RuleSets to docs (SpacePossum) +* minor #5226 Applied CS fixes from 2.17-dev (GrahamCampbell) +* minor #5229 Fixed incorrect phpdoc (GrahamCampbell) +* minor #5231 CS: unify styling with younger branches (keradus) +* minor #5232 PHP8 - throw expression support (SpacePossum) +* minor #5233 DX: simplify check_file_permissions.sh (kubawerlos) +* minor #5236 Improve handling of unavailable code samples (julienfalque, keradus) +* minor #5239 PHP8 - Allow trailing comma in parameter list support (SpacePossum) +* minor #5254 PHP8 - mixed type support (SpacePossum) +* minor #5255 Tests: do not skip documentation test (keradus) +* minor #5256 Docs: phpdoc_to_return_type - add new example in docs (keradus) +* minor #5261 Do not update Composer twice (sanmai) +* minor #5263 PHP8 support (SpacePossum) +* minor #5266 PhpUnitTestCaseStaticMethodCallsFixer - PHPUnit 9.x support (sanmai) +* minor #5267 Improve InstallViaComposerTest (sanmai) +* minor #5268 Add GitHub Workflows CI, including testing on PHP 8 and on macOS/Windows/Ubuntu (sanmai) +* minor #5269 Prep work to migrate to PHPUnit 9.x (sanmai, keradus) +* minor #5275 remove not supported verbose options (SpacePossum) +* minor #5276 PHP8 - add NoUnreachableDefaultArgumentValueFixer to risky set (SpacePossum) +* minor #5277 PHP8 - Constructor Property Promotion support (SpacePossum) +* minor #5292 Disable blank issue template and expose community chat (keradus) +* minor #5293 Add documentation to "yoda_style" sniff to convert Yoda style to non-Yoda style (Luc45) +* minor #5295 Run static code analysis off GitHub Actions (sanmai) +* minor #5298 Add yamllint workflow, validates .yaml files (sanmai) +* minor #5302 SingleLineCommentStyleFixer - do not fix possible attributes (PHP8) (SpacePossum) +* minor #5303 Drop CircleCI and AppVeyor (keradus) +* minor #5304 DX: rename TravisTest, as we no longer test only Travis there (keradus) +* minor #5305 Groom GitHub CI and move some checks from TravisCI to GitHub CI (keradus) +* minor #5308 Only run yamllint when a YAML file is changed (julienfalque, keradus) +* minor #5309 CICD: create yamllint config file (keradus) +* minor #5311 OrderedClassElementsFixer - PHPUnit Bridge support (ktomk) +* minor #5316 PHP8 - Attribute support (SpacePossum) +* minor #5321 DX: little code grooming (keradus) + +Changelog for v2.16.8 +--------------------- + +* bug #5325 NoBreakCommentFixer - better throw handling (SpacePossum) +* bug #5327 StaticLambdaFixer - fix for arrow function used in class with $this (kubawerlos, SpacePossum) +* bug #5333 Fix file missing for php8 (jderusse) +* minor #5328 Fixed deprecation message version (GrahamCampbell) +* minor #5330 DX: cleanup Github Actions configs (kubawerlos) + +Changelog for v2.16.5 +--------------------- + +* bug #4378 PhpUnitNoExpectationAnnotationFixer - annotation in single line doc comment (kubawerlos) +* bug #4936 HeaderCommentFixer - Fix unexpected removal of regular comments (julienfalque) +* bug #5006 PhpdocToParamTypeFixer - fix for breaking PHP syntax for type having reserved name (kubawerlos) +* bug #5016 NoSuperfluousPhpdocTagsFixer - fix for @return with @inheritDoc in description (kubawerlos) +* bug #5017 PhpdocTrimConsecutiveBlankLineSeparationFixer - must run after AlignMultilineCommentFixer (kubawerlos) +* bug #5032 SingleLineAfterImportsFixer - fix for line after import (and before another import) already added using CRLF (kubawerlos) +* bug #5033 VoidReturnFixer - must run after NoSuperfluousPhpdocTagsFixer (kubawerlos) +* bug #5038 HelpCommandTest - toString nested array (SpacePossum) +* bug #5040 LinebreakAfterOpeningTagFixer - do not change code if linebreak already present (kubawerlos) +* bug #5044 StandardizeIncrementFixer - fix handling static properties (kubawerlos) +* bug #5045 BacktickToShellExecFixer - add priority relation to NativeFunctionInvocationFixer and SingleQuoteFixer (kubawerlos) +* bug #5054 PhpdocTypesFixer - fix for multidimensional array (kubawerlos) +* bug #5065 TernaryOperatorSpacesFixer - fix for discovering ":" correctly (kubawerlos) +* bug #5068 Fixed php-cs-fixer crashes on input file syntax error (GrahamCampbell) +* bug #5087 NoAlternativeSyntaxFixer - add support for switch and declare (SpacePossum) +* bug #5092 PhpdocToParamTypeFixer - remove not used option (SpacePossum) +* bug #5105 ClassKeywordRemoveFixer - fix for fully qualified class (kubawerlos) +* bug #5113 TernaryOperatorSpacesFixer - handle goto labels (SpacePossum) +* bug #5124 Fix TernaryToNullCoalescingFixer when dealing with object properties (HypeMC) +* bug #5137 DoctrineAnnotationSpacesFixer - fix for typed properties (kubawerlos) +* bug #5180 Always lint test cases with the stricter process linter (GrahamCampbell) +* bug #5190 PhpUnit*Fixers - Only fix in unit test class scope (SpacePossum) +* bug #5195 YodaStyle - statements in braces should be treated as variables in strict … (SpacePossum) +* bug #5220 NoUnneededFinalMethodFixer - do not fix private constructors (SpacePossum) +* feature #3475 Rework documentation (julienfalque, SpacePossum) +* feature #5166 PHP8 (SpacePossum) +* minor #4878 ArrayIndentationFixer - refactor (julienfalque) +* minor #5031 CI: skip_cleanup: true (keradus) +* minor #5035 PhpdocToParamTypeFixer - Rename attribute (SpacePossum) +* minor #5048 Allow composer/semver ^2.0 and ^3.0 (thomasvargiu) +* minor #5050 DX: moving integration test for braces, indentation_type and no_break_comment into right place (kubawerlos) +* minor #5051 DX: move all tests from AutoReview\FixerTest to Test\AbstractFixerTestCase (kubawerlos) +* minor #5053 DX: cleanup FunctionTypehintSpaceFixer (kubawerlos) +* minor #5056 DX: add missing priority test for indentation_type and phpdoc_indent (kubawerlos) +* minor #5077 DX: add missing priority test between NoUnsetCastFixer and BinaryOperatorSpacesFixer (kubawerlos) +* minor #5083 Update composer.json to prevent issue #5030 (mvorisek) +* minor #5088 NoBreakCommentFixer - NoUselessElseFixer - priority test (SpacePossum) +* minor #5100 Fixed invalid PHP 5.6 syntax (GrahamCampbell) +* minor #5106 Symfony's finder already ignores vcs and dot files by default (GrahamCampbell) +* minor #5112 DX: check file permissions (kubawerlos, SpacePossum) +* minor #5122 Show runtime PHP version (kubawerlos) +* minor #5132 Do not allow assignments in if statements (SpacePossum) +* minor #5133 RuleSetTest - Early return for boolean and detect more defaults (SpacePossum) +* minor #5139 revert some unneeded exclusions (SpacePossum) +* minor #5148 Upgrade Xcode (kubawerlos) +* minor #5149 NoUnsetOnPropertyFixer - risky description tweaks (SpacePossum) +* minor #5161 minors (SpacePossum) +* minor #5170 Fix test on PHP8 (SpacePossum) +* minor #5172 Remove accidentally inserted newlines (GrahamCampbell) +* minor #5173 Fix PHP8 RuleSet inherit (SpacePossum) +* minor #5174 Corrected linting error messages (GrahamCampbell) +* minor #5177 PHP8 (SpacePossum) +* minor #5178 Fix tests (SpacePossum) +* minor #5184 [FinalStaticAccessFixer] Handle new static() in final class (localheinz) +* minor #5188 DX: Update sibling debs to version supporting PHP8/PHPUnit9 (keradus) +* minor #5189 Create temporary linting file in system temp dir (keradus) +* minor #5191 MethodArgumentSpaceFixer - support use/import of anonymous functions. (undefinedor) +* minor #5193 DX: add AbstractPhpUnitFixer (kubawerlos) +* minor #5204 DX: cleanup NullableTypeTransformerTest (kubawerlos) +* minor #5207 Add © for logo (keradus) +* minor #5208 DX: cleanup php-cs-fixer entry file (keradus) +* minor #5210 CICD - temporarily disable problematic test (keradus) +* minor #5211 CICD: fix file permissions (keradus) +* minor #5213 DX: move report schemas to dedicated dir (keradus) +* minor #5214 CICD: fix file permissions (keradus) +* minor #5215 CICD: update checkbashisms (keradus) +* minor #5217 CICD: use Composer v2 and drop hirak/prestissimo plugin (keradus) +* minor #5218 DX: .gitignore - add .phpunit.result.cache (keradus) +* minor #5222 Upgrade Xcode (kubawerlos) +* minor #5223 Docs: regenerate docs on 2.16 line (keradus) + +Changelog for v2.16.4 +--------------------- + +* bug #3893 Fix handling /** and */ on the same line as the first and/or last annotation (dmvdbrugge) +* bug #4919 PhpUnitTestAnnotationFixer - fix function starting with "test" and having lowercase letter after (kubawerlos) +* bug #4929 YodaStyleFixer - handling equals empty array (kubawerlos) +* bug #4934 YodaStyleFixer - fix for conditions weird are (kubawerlos) +* bug #4958 OrderedImportsFixer - fix for trailing comma in group (kubawerlos) +* bug #4959 BlankLineBeforeStatementFixer - handle comment case (SpacePossum) +* bug #4962 MethodArgumentSpaceFixer - must run after MethodChainingIndentationFixer (kubawerlos) +* bug #4963 PhpdocToReturnTypeFixer - fix for breaking PHP syntax for type having reserved name (kubawerlos, Slamdunk) +* bug #4978 ArrayIndentationFixer - must run after MethodArgumentSpaceFixer (kubawerlos) +* bug #4994 FinalInternalClassFixer - must run before ProtectedToPrivateFixer (kubawerlos) +* bug #4996 NoEmptyCommentFixer - handle multiline comments (kubawerlos) +* bug #4999 BlankLineBeforeStatementFixer - better comment handling (SpacePossum) +* bug #5009 NoEmptyCommentFixer - better handle comments sequence (kubawerlos) +* bug #5010 SimplifiedNullReturnFixer - must run before VoidReturnFixer (kubawerlos) +* bug #5011 SingleClassElementPerStatementFixer - must run before ClassAttributesSeparationFixer (kubawerlos) +* bug #5012 StrictParamFixer - must run before NativeFunctionInvocationFixer (kubawerlos) +* bug #5014 PhpdocToParamTypeFixer - fix for void as param (kubawerlos) +* bug #5018 PhpdocScalarFixer - fix for comment with Windows line endings (kubawerlos) +* bug #5029 SingleLineAfterImportsFixer - fix for line after import already added using CRLF (kubawerlos) +* minor #4904 Increase PHPStan level to 8 with strict rules (julienfalque) +* minor #4920 Enhancement: Use DocBlock itself to make it multi-line (localheinz) +* minor #4930 DX: ensure PhpUnitNamespacedFixer handles all classes (kubawerlos) +* minor #4931 DX: add test to ensure each target version in PhpUnitTargetVersion has its set in RuleSet (kubawerlos) +* minor #4932 DX: Travis CI config - fix warnings and infos (kubawerlos) +* minor #4940 Reject empty path (julienfalque) +* minor #4944 Fix grammar (julienfalque) +* minor #4946 Allow "const" option on PHP <7.1 (julienfalque) +* minor #4948 Added describe command to readme (david, 8ctopus) +* minor #4949 Fixed build readme on Windows fails if using Git Bash (Mintty) (8ctopus) +* minor #4954 Config - Trim path (julienfalque) +* minor #4957 DX: Check trailing spaces in project files only (ktomk) +* minor #4961 Assert all project source files are monolithic. (SpacePossum) +* minor #4964 Fix PHPStan baseline (julienfalque) +* minor #4965 Fix PHPStan baseline (julienfalque) +* minor #4973 DX: test "isRisky" method in fixer tests, not as auto review (kubawerlos) +* minor #4974 Minor: Fix typo (ktomk) +* minor #4975 Revert PHPStan level to 5 (julienfalque) +* minor #4976 Add instructions for PHPStan (julienfalque) +* minor #4980 Introduce new issue templates (julienfalque) +* minor #4981 Prevent error in CTTest::testConstants (for PHP8) (guilliamxavier) +* minor #4982 Remove PHIVE (kubawerlos) +* minor #4985 Fix tests with Symfony 5.1 (julienfalque) +* minor #4987 PhpdocAnnotationWithoutDotFixer - handle unicode characters using mb_* (SpacePossum) +* minor #5008 Enhancement: Social justification applied (gbyrka-fingo) +* minor #5023 Fix issue templates (kubawerlos) +* minor #5024 DX: add missing non-default code samples (kubawerlos) + +Changelog for v2.16.3 +--------------------- + +* bug #4915 Fix handling property PHPDocs with unsupported type (julienfalque) +* minor #4916 Fix AppVeyor build (julienfalque) +* minor #4917 CircleCI - Bump xcode to 11.4 (GrahamCampbell) +* minor #4918 DX: do not fix ".phpt" files by default (kubawerlos) + +Changelog for v2.16.2 +--------------------- + +* bug #3820 Braces - (re)indenting comment issues (SpacePossum) +* bug #3911 PhpdocVarWithoutNameFixer - fix for properties only (dmvdbrugge) +* bug #4601 ClassKeywordRemoveFixer - Fix for namespace (yassine-ah, kubawerlos) +* bug #4630 FullyQualifiedStrictTypesFixer - Ignore partial class names which look like FQCNs (localheinz, SpacePossum) +* bug #4661 ExplicitStringVariableFixer - variables pair if one is already explicit (kubawerlos) +* bug #4675 NonPrintableCharacterFixer - fix for backslash and quotes when changing to escape sequences (kubawerlos) +* bug #4678 TokensAnalyzer::isConstantInvocation - fix for importing multiple classes with single "use" (kubawerlos) +* bug #4682 Fix handling array type declaration in properties (julienfalque) +* bug #4685 Improve Symfony 5 compatibility (keradus) +* bug #4688 TokensAnalyzer::isConstantInvocation - Fix detection for fully qualified return type (julienfalque) +* bug #4689 DeclareStrictTypesFixer - fix for "strict_types" set to "0" (kubawerlos) +* bug #4690 PhpdocVarAnnotationCorrectOrderFixer - fix for multiline `@var` without type (kubawerlos) +* bug #4710 SingleTraitInsertPerStatement - fix formatting for multiline "use" (kubawerlos) +* bug #4711 Ensure that files from "tests" directory in release are autoloaded (kubawerlos) +* bug #4749 TokensAnalyze::isUnaryPredecessorOperator fix for CT::T_ARRAY_INDEX_C… (SpacePossum) +* bug #4759 Add more priority cases (SpacePossum) +* bug #4761 NoSuperfluousElseifFixer - handle single line (SpacePossum) +* bug #4783 NoSuperfluousPhpdocTagsFixer - fix for really big PHPDoc (kubawerlos, mvorisek) +* bug #4787 NoUnneededFinalMethodFixer - Mark as risky (SpacePossum) +* bug #4795 OrderedClassElementsFixer - Fix (SpacePossum) +* bug #4801 GlobalNamespaceImportFixer - fix docblock handling (gharlan) +* bug #4804 TokensAnalyzer::isUnarySuccessorOperator fix for array curly braces (SpacePossum) +* bug #4807 IncrementStyleFixer - handle after ")" (SpacePossum) +* bug #4808 Modernize types casting fixer array curly (SpacePossum) +* bug #4809 Fix "braces" and "method_argument_space" priority (julienfalque) +* bug #4813 BracesFixer - fix invalid code generation on alternative syntax (SpacePossum) +* bug #4822 fix 2 bugs in phpdoc_line_span (lmichelin) +* bug #4823 ReturnAssignmentFixer - repeat fix (SpacePossum) +* bug #4824 NoUnusedImportsFixer - SingleLineAfterImportsFixer - fix priority (SpacePossum) +* bug #4825 GlobalNamespaceImportFixer - do not import global into global (SpacePossum) +* bug #4829 YodaStyleFixer - fix precedence for T_MOD_EQUAL and T_COALESCE_EQUAL (SpacePossum) +* bug #4830 TernaryToNullCoalescingFixer - handle yield from (SpacePossum) +* bug #4835 Remove duplicate "function_to_constant" from RuleSet (SpacePossum) +* bug #4840 LineEndingFixer - T_CLOSE_TAG support, StringLineEndingFixer - T_INLI… (SpacePossum) +* bug #4846 FunctionsAnalyzer - better isGlobalFunctionCall detection (SpacePossum) +* bug #4852 Priority issues (SpacePossum) +* bug #4870 HeaderCommentFixer - do not remove class docs (gharlan) +* bug #4871 NoExtraBlankLinesFixer - handle cases on same line (SpacePossum) +* bug #4895 Fix conflict between header_comment and declare_strict_types (BackEndTea, julienfalque) +* bug #4911 PhpdocSeparationFixer - fix regression with lack of next line (keradus) +* feature #4742 FunctionToConstantFixer - get_class($this) support (SpacePossum) +* minor #4377 CommentsAnalyzer - fix for declare before header comment (kubawerlos) +* minor #4636 DX: do not check for PHPDBG when collecting coverage (kubawerlos) +* minor #4644 Docs: add info about "-vv..." (voku) +* minor #4691 Run Travis CI on stable PHP 7.4 (kubawerlos) +* minor #4693 Increase Travis CI Git clone depth (julienfalque) +* minor #4699 LineEndingFixer - handle "\r\r\n" (kubawerlos) +* minor #4703 NoSuperfluousPhpdocTagsFixer,PhpdocAddMissingParamAnnotationFixer - p… (SpacePossum) +* minor #4707 Fix typos (TysonAndre) +* minor #4712 NoBlankLinesAfterPhpdocFixer — Do not strip newline between docblock and use statements (mollierobbert) +* minor #4715 Enhancement: Install ergebnis/composer-normalize via Phive (localheinz) +* minor #4722 Fix Circle CI build (julienfalque) +* minor #4724 DX: Simplify installing PCOV (kubawerlos) +* minor #4736 NoUnusedImportsFixer - do not match variable name as import (SpacePossum) +* minor #4746 NoSuperfluousPhpdocTagsFixer - Remove for typed properties (PHP 7.4) (ruudk) +* minor #4753 Do not apply any text/.git filters to fixtures (mvorisek) +* minor #4757 Test $expected is used before $input (SpacePossum) +* minor #4758 Autoreview the PHPDoc of *Fixer::getPriority based on the priority map (SpacePossum) +* minor #4765 Add test on some return types (SpacePossum) +* minor #4766 Remove false test skip (SpacePossum) +* minor #4767 Remove useless priority comments (kubawerlos) +* minor #4769 DX: add missing priority tests (kubawerlos) +* minor #4772 NoUnneededFinalMethodFixer - update description (kubawerlos) +* minor #4774 DX: simplify Utils::camelCaseToUnderscore (kubawerlos) +* minor #4781 NoUnneededCurlyBracesFixer - handle namespaces (SpacePossum) +* minor #4784 Travis CI - Use multiple keyservers (ktomk) +* minor #4785 Improve static analysis (enumag) +* minor #4788 Configurable fixers code sample (SpacePossum) +* minor #4791 Increase PHPStan level to 3 (julienfalque) +* minor #4797 clean ups (SpacePossum) +* minor #4803 FinalClassFixer - Doctrine\ORM\Mapping as ORM alias should not be required (localheinz) +* minor #4839 2.15 - clean ups (SpacePossum) +* minor #4842 ReturnAssignmentFixer - Support more cases (julienfalque) +* minor #4843 NoSuperfluousPhpdocTagsFixer - fix typo in option description (OndraM) +* minor #4844 Same requirements for descriptions (SpacePossum) +* minor #4849 Increase PHPStan level to 5 (julienfalque) +* minor #4850 Fix phpstan (SpacePossum) +* minor #4857 Fixed the unit tests (GrahamCampbell) +* minor #4865 Use latest xcode image (GrahamCampbell) +* minor #4892 CombineNestedDirnameFixer - Add space after comma (julienfalque) +* minor #4894 DX: PhpdocToParamTypeFixer - improve typing (keradus) +* minor #4898 FixerTest - yield the data in AutoReview (Nyholm) +* minor #4899 Fix exception message format for fabbot.io (SpacePossum) +* minor #4905 Support composer v2 installed.json files (GrahamCampbell) +* minor #4906 CI: use Composer stable release for AppVeyor (kubawerlos) +* minor #4909 DX: HeaderCommentFixer - use non-aliased version of option name in code (keradus) +* minor #4912 CI: Fix AppVeyor integration (keradus) + +Changelog for v2.16.1 +--------------------- + +* bug #4476 FunctionsAnalyzer - add "isTheSameClassCall" for correct verifying of function calls (kubawerlos) +* bug #4605 PhpdocToParamTypeFixer - cover more cases (keradus, julienfalque) +* bug #4626 FinalPublicMethodForAbstractClassFixer - Do not attempt to mark abstract public methods as final (localheinz) +* bug #4632 NullableTypeDeclarationForDefaultNullValueFixer - fix for not lowercase "null" (kubawerlos) +* bug #4638 Ensure compatibility with PHP 7.4 (julienfalque) +* bug #4641 Add typed properties test to VisibilityRequiredFixerTest (GawainLynch, julienfalque) +* bug #4654 ArrayIndentationFixer - Fix array indentation for multiline values (julienfalque) +* bug #4660 TokensAnalyzer::isConstantInvocation - fix for extending multiple interfaces (kubawerlos) +* bug #4668 TokensAnalyzer::isConstantInvocation - fix for interface method return type (kubawerlos) +* minor #4608 Allow Symfony 5 components (l-vo) +* minor #4622 Disallow PHP 7.4 failures on Travis CI (julienfalque) +* minor #4623 README - Mark up as code (localheinz) +* minor #4637 PHP 7.4 integration test (GawainLynch, julienfalque) +* minor #4643 DX: Update .gitattributes and move ci-integration.sh to root of the project (kubawerlos, keradus) +* minor #4645 Check PHP extensions on runtime (kubawerlos) +* minor #4655 Improve docs - README (mvorisek) +* minor #4662 DX: generate headers in README.rst (kubawerlos) +* minor #4669 Enable execution under PHP 7.4 (keradus) +* minor #4670 TravisTest - rewrite tests to allow last supported by tool PHP version to be snapshot (keradus) +* minor #4671 TravisTest - rewrite tests to allow last supported by tool PHP version to be snapshot (keradus) + +Changelog for v2.16.0 +--------------------- + +* feature #3810 PhpdocLineSpanFixer - Introduction (BackEndTea) +* feature #3928 Add FinalPublicMethodForAbstractClassFixer (Slamdunk) +* feature #4000 FinalStaticAccessFixer - Introduction (ntzm) +* feature #4275 Issue #4274: Let lowercase_constants directive to be configurable. (drupol) +* feature #4355 GlobalNamespaceImportFixer - Introduction (gharlan) +* feature #4358 SelfStaticAccessorFixer - Introduction (SpacePossum) +* feature #4385 CommentToPhpdocFixer - allow to ignore tags (kubawerlos) +* feature #4401 Add NullableTypeDeclarationForDefaultNullValueFixer (HypeMC) +* feature #4452 Add SingleLineThrowFixer (kubawerlos) +* feature #4500 NoSuperfluousPhpdocTags - Add remove_inheritdoc option (julienfalque) +* feature #4505 NoSuperfluousPhpdocTagsFixer - allow params that aren't on the signature (azjezz) +* feature #4531 PhpdocAlignFixer - add "property-read" and "property-write" to allowed tags (kubawerlos) +* feature #4583 Phpdoc to param type fixer rebase (jg-development) +* minor #4033 Raise deprecation warnings on usage of deprecated aliases (ntzm) +* minor #4423 DX: update branch alias (keradus) +* minor #4537 SelfStaticAccessor - extend itests (keradus) +* minor #4607 Configure no_superfluous_phpdoc_tags for Symfony (keradus) +* minor #4618 DX: fix usage of deprecated options (0x450x6c) +* minor #4619 Fix PHP 7.3 strict mode warnings (keradus) +* minor #4621 Add single_line_throw to Symfony ruleset (keradus) + +Changelog for v2.15.10 +---------------------- + +* bug #5095 Annotation - fix for Windows line endings (SpacePossum) +* bug #5221 NoSuperfluousPhpdocTagsFixer - fix for single line PHPDoc (kubawerlos) +* bug #5225 TernaryOperatorSpacesFixer - fix for alternative control structures (kubawerlos) +* bug #5235 ArrayIndentationFixer - fix for nested arrays (kubawerlos) +* bug #5248 NoBreakCommentFixer - fix throw detect (SpacePossum) +* bug #5250 SwitchAnalyzer - fix for semicolon after case/default (kubawerlos) +* bug #5253 IO - fix cache info message (SpacePossum) +* bug #5274 TernaryToNullCoalescingFixer - concat precedence fix (SpacePossum) +* feature #5216 Add RuleSets to docs (SpacePossum) +* minor #5226 Applied CS fixes from 2.17-dev (GrahamCampbell) +* minor #5229 Fixed incorrect phpdoc (GrahamCampbell) +* minor #5231 CS: unify styling with younger branches (keradus) +* minor #5232 PHP8 - throw expression support (SpacePossum) +* minor #5233 DX: simplify check_file_permissions.sh (kubawerlos) +* minor #5236 Improve handling of unavailable code samples (julienfalque, keradus) +* minor #5239 PHP8 - Allow trailing comma in parameter list support (SpacePossum) +* minor #5254 PHP8 - mixed type support (SpacePossum) +* minor #5255 Tests: do not skip documentation test (keradus) +* minor #5261 Do not update Composer twice (sanmai) +* minor #5263 PHP8 support (SpacePossum) +* minor #5266 PhpUnitTestCaseStaticMethodCallsFixer - PHPUnit 9.x support (sanmai) +* minor #5267 Improve InstallViaComposerTest (sanmai) +* minor #5276 PHP8 - add NoUnreachableDefaultArgumentValueFixer to risky set (SpacePossum) + +Changelog for v2.15.9 +--------------------- + +* bug #4378 PhpUnitNoExpectationAnnotationFixer - annotation in single line doc comment (kubawerlos) +* bug #4936 HeaderCommentFixer - Fix unexpected removal of regular comments (julienfalque) +* bug #5017 PhpdocTrimConsecutiveBlankLineSeparationFixer - must run after AlignMultilineCommentFixer (kubawerlos) +* bug #5033 VoidReturnFixer - must run after NoSuperfluousPhpdocTagsFixer (kubawerlos) +* bug #5038 HelpCommandTest - toString nested array (SpacePossum) +* bug #5040 LinebreakAfterOpeningTagFixer - do not change code if linebreak already present (kubawerlos) +* bug #5044 StandardizeIncrementFixer - fix handling static properties (kubawerlos) +* bug #5045 BacktickToShellExecFixer - add priority relation to NativeFunctionInvocationFixer and SingleQuoteFixer (kubawerlos) +* bug #5054 PhpdocTypesFixer - fix for multidimensional array (kubawerlos) +* bug #5065 TernaryOperatorSpacesFixer - fix for discovering ":" correctly (kubawerlos) +* bug #5068 Fixed php-cs-fixer crashes on input file syntax error (GrahamCampbell) +* bug #5087 NoAlternativeSyntaxFixer - add support for switch and declare (SpacePossum) +* bug #5105 ClassKeywordRemoveFixer - fix for fully qualified class (kubawerlos) +* bug #5113 TernaryOperatorSpacesFixer - handle goto labels (SpacePossum) +* bug #5124 Fix TernaryToNullCoalescingFixer when dealing with object properties (HypeMC) +* bug #5137 DoctrineAnnotationSpacesFixer - fix for typed properties (kubawerlos) +* bug #5180 Always lint test cases with the stricter process linter (GrahamCampbell) +* bug #5190 PhpUnit*Fixers - Only fix in unit test class scope (SpacePossum) +* bug #5195 YodaStyle - statements in braces should be treated as variables in strict … (SpacePossum) +* bug #5220 NoUnneededFinalMethodFixer - do not fix private constructors (SpacePossum) +* feature #3475 Rework documentation (julienfalque, SpacePossum) +* feature #5166 PHP8 (SpacePossum) +* minor #4878 ArrayIndentationFixer - refactor (julienfalque) +* minor #5031 CI: skip_cleanup: true (keradus) +* minor #5048 Allow composer/semver ^2.0 and ^3.0 (thomasvargiu) +* minor #5050 DX: moving integration test for braces, indentation_type and no_break_comment into right place (kubawerlos) +* minor #5051 DX: move all tests from AutoReview\FixerTest to Test\AbstractFixerTestCase (kubawerlos) +* minor #5053 DX: cleanup FunctionTypehintSpaceFixer (kubawerlos) +* minor #5056 DX: add missing priority test for indentation_type and phpdoc_indent (kubawerlos) +* minor #5077 DX: add missing priority test between NoUnsetCastFixer and BinaryOperatorSpacesFixer (kubawerlos) +* minor #5083 Update composer.json to prevent issue #5030 (mvorisek) +* minor #5088 NoBreakCommentFixer - NoUselessElseFixer - priority test (SpacePossum) +* minor #5100 Fixed invalid PHP 5.6 syntax (GrahamCampbell) +* minor #5106 Symfony's finder already ignores vcs and dot files by default (GrahamCampbell) +* minor #5112 DX: check file permissions (kubawerlos, SpacePossum) +* minor #5122 Show runtime PHP version (kubawerlos) +* minor #5132 Do not allow assignments in if statements (SpacePossum) +* minor #5133 RuleSetTest - Early return for boolean and detect more defaults (SpacePossum) +* minor #5139 revert some unneeded exclusions (SpacePossum) +* minor #5148 Upgrade Xcode (kubawerlos) +* minor #5149 NoUnsetOnPropertyFixer - risky description tweaks (SpacePossum) +* minor #5161 minors (SpacePossum) +* minor #5172 Remove accidentally inserted newlines (GrahamCampbell) +* minor #5173 Fix PHP8 RuleSet inherit (SpacePossum) +* minor #5174 Corrected linting error messages (GrahamCampbell) +* minor #5177 PHP8 (SpacePossum) +* minor #5188 DX: Update sibling debs to version supporting PHP8/PHPUnit9 (keradus) +* minor #5189 Create temporary linting file in system temp dir (keradus) +* minor #5191 MethodArgumentSpaceFixer - support use/import of anonymous functions. (undefinedor) +* minor #5193 DX: add AbstractPhpUnitFixer (kubawerlos) +* minor #5204 DX: cleanup NullableTypeTransformerTest (kubawerlos) +* minor #5207 Add © for logo (keradus) +* minor #5208 DX: cleanup php-cs-fixer entry file (keradus) +* minor #5210 CICD - temporarily disable problematic test (keradus) +* minor #5211 CICD: fix file permissions (keradus) +* minor #5213 DX: move report schemas to dedicated dir (keradus) +* minor #5214 CICD: fix file permissions (keradus) +* minor #5215 CICD: update checkbashisms (keradus) +* minor #5217 CICD: use Composer v2 and drop hirak/prestissimo plugin (keradus) +* minor #5218 DX: .gitignore - add .phpunit.result.cache (keradus) +* minor #5222 Upgrade Xcode (kubawerlos) + +Changelog for v2.15.8 +--------------------- + +* bug #3893 Fix handling /** and */ on the same line as the first and/or last annotation (dmvdbrugge) +* bug #4919 PhpUnitTestAnnotationFixer - fix function starting with "test" and having lowercase letter after (kubawerlos) +* bug #4929 YodaStyleFixer - handling equals empty array (kubawerlos) +* bug #4934 YodaStyleFixer - fix for conditions weird are (kubawerlos) +* bug #4958 OrderedImportsFixer - fix for trailing comma in group (kubawerlos) +* bug #4959 BlankLineBeforeStatementFixer - handle comment case (SpacePossum) +* bug #4962 MethodArgumentSpaceFixer - must run after MethodChainingIndentationFixer (kubawerlos) +* bug #4963 PhpdocToReturnTypeFixer - fix for breaking PHP syntax for type having reserved name (kubawerlos, Slamdunk) +* bug #4978 ArrayIndentationFixer - must run after MethodArgumentSpaceFixer (kubawerlos) +* bug #4994 FinalInternalClassFixer - must run before ProtectedToPrivateFixer (kubawerlos) +* bug #4996 NoEmptyCommentFixer - handle multiline comments (kubawerlos) +* bug #4999 BlankLineBeforeStatementFixer - better comment handling (SpacePossum) +* bug #5009 NoEmptyCommentFixer - better handle comments sequence (kubawerlos) +* bug #5010 SimplifiedNullReturnFixer - must run before VoidReturnFixer (kubawerlos) +* bug #5011 SingleClassElementPerStatementFixer - must run before ClassAttributesSeparationFixer (kubawerlos) +* bug #5012 StrictParamFixer - must run before NativeFunctionInvocationFixer (kubawerlos) +* bug #5029 SingleLineAfterImportsFixer - fix for line after import already added using CRLF (kubawerlos) +* minor #4904 Increase PHPStan level to 8 with strict rules (julienfalque) +* minor #4930 DX: ensure PhpUnitNamespacedFixer handles all classes (kubawerlos) +* minor #4931 DX: add test to ensure each target version in PhpUnitTargetVersion has its set in RuleSet (kubawerlos) +* minor #4932 DX: Travis CI config - fix warnings and infos (kubawerlos) +* minor #4940 Reject empty path (julienfalque) +* minor #4944 Fix grammar (julienfalque) +* minor #4946 Allow "const" option on PHP <7.1 (julienfalque) +* minor #4948 Added describe command to readme (david, 8ctopus) +* minor #4949 Fixed build readme on Windows fails if using Git Bash (Mintty) (8ctopus) +* minor #4954 Config - Trim path (julienfalque) +* minor #4957 DX: Check trailing spaces in project files only (ktomk) +* minor #4961 Assert all project source files are monolithic. (SpacePossum) +* minor #4964 Fix PHPStan baseline (julienfalque) +* minor #4973 DX: test "isRisky" method in fixer tests, not as auto review (kubawerlos) +* minor #4974 Minor: Fix typo (ktomk) +* minor #4975 Revert PHPStan level to 5 (julienfalque) +* minor #4976 Add instructions for PHPStan (julienfalque) +* minor #4980 Introduce new issue templates (julienfalque) +* minor #4981 Prevent error in CTTest::testConstants (for PHP8) (guilliamxavier) +* minor #4982 Remove PHIVE (kubawerlos) +* minor #4985 Fix tests with Symfony 5.1 (julienfalque) +* minor #4987 PhpdocAnnotationWithoutDotFixer - handle unicode characters using mb_* (SpacePossum) +* minor #5008 Enhancement: Social justification applied (gbyrka-fingo) +* minor #5023 Fix issue templates (kubawerlos) +* minor #5024 DX: add missing non-default code samples (kubawerlos) + +Changelog for v2.15.7 +--------------------- + +* bug #4915 Fix handling property PHPDocs with unsupported type (julienfalque) +* minor #4916 Fix AppVeyor build (julienfalque) +* minor #4917 CircleCI - Bump xcode to 11.4 (GrahamCampbell) +* minor #4918 DX: do not fix ".phpt" files by default (kubawerlos) + +Changelog for v2.15.6 +--------------------- + +* bug #3820 Braces - (re)indenting comment issues (SpacePossum) +* bug #3911 PhpdocVarWithoutNameFixer - fix for properties only (dmvdbrugge) +* bug #4601 ClassKeywordRemoveFixer - Fix for namespace (yassine-ah, kubawerlos) +* bug #4630 FullyQualifiedStrictTypesFixer - Ignore partial class names which look like FQCNs (localheinz, SpacePossum) +* bug #4661 ExplicitStringVariableFixer - variables pair if one is already explicit (kubawerlos) +* bug #4675 NonPrintableCharacterFixer - fix for backslash and quotes when changing to escape sequences (kubawerlos) +* bug #4678 TokensAnalyzer::isConstantInvocation - fix for importing multiple classes with single "use" (kubawerlos) +* bug #4682 Fix handling array type declaration in properties (julienfalque) +* bug #4685 Improve Symfony 5 compatibility (keradus) +* bug #4688 TokensAnalyzer::isConstantInvocation - Fix detection for fully qualified return type (julienfalque) +* bug #4689 DeclareStrictTypesFixer - fix for "strict_types" set to "0" (kubawerlos) +* bug #4690 PhpdocVarAnnotationCorrectOrderFixer - fix for multiline `@var` without type (kubawerlos) +* bug #4710 SingleTraitInsertPerStatement - fix formatting for multiline "use" (kubawerlos) +* bug #4711 Ensure that files from "tests" directory in release are autoloaded (kubawerlos) +* bug #4749 TokensAnalyze::isUnaryPredecessorOperator fix for CT::T_ARRAY_INDEX_C… (SpacePossum) +* bug #4759 Add more priority cases (SpacePossum) +* bug #4761 NoSuperfluousElseifFixer - handle single line (SpacePossum) +* bug #4783 NoSuperfluousPhpdocTagsFixer - fix for really big PHPDoc (kubawerlos, mvorisek) +* bug #4787 NoUnneededFinalMethodFixer - Mark as risky (SpacePossum) +* bug #4795 OrderedClassElementsFixer - Fix (SpacePossum) +* bug #4804 TokensAnalyzer::isUnarySuccessorOperator fix for array curly braces (SpacePossum) +* bug #4807 IncrementStyleFixer - handle after ")" (SpacePossum) +* bug #4808 Modernize types casting fixer array curly (SpacePossum) +* bug #4809 Fix "braces" and "method_argument_space" priority (julienfalque) +* bug #4813 BracesFixer - fix invalid code generation on alternative syntax (SpacePossum) +* bug #4823 ReturnAssignmentFixer - repeat fix (SpacePossum) +* bug #4824 NoUnusedImportsFixer - SingleLineAfterImportsFixer - fix priority (SpacePossum) +* bug #4829 YodaStyleFixer - fix precedence for T_MOD_EQUAL and T_COALESCE_EQUAL (SpacePossum) +* bug #4830 TernaryToNullCoalescingFixer - handle yield from (SpacePossum) +* bug #4835 Remove duplicate "function_to_constant" from RuleSet (SpacePossum) +* bug #4840 LineEndingFixer - T_CLOSE_TAG support, StringLineEndingFixer - T_INLI… (SpacePossum) +* bug #4846 FunctionsAnalyzer - better isGlobalFunctionCall detection (SpacePossum) +* bug #4852 Priority issues (SpacePossum) +* bug #4870 HeaderCommentFixer - do not remove class docs (gharlan) +* bug #4871 NoExtraBlankLinesFixer - handle cases on same line (SpacePossum) +* bug #4895 Fix conflict between header_comment and declare_strict_types (BackEndTea, julienfalque) +* bug #4911 PhpdocSeparationFixer - fix regression with lack of next line (keradus) +* feature #4742 FunctionToConstantFixer - get_class($this) support (SpacePossum) +* minor #4377 CommentsAnalyzer - fix for declare before header comment (kubawerlos) +* minor #4636 DX: do not check for PHPDBG when collecting coverage (kubawerlos) +* minor #4644 Docs: add info about "-vv..." (voku) +* minor #4691 Run Travis CI on stable PHP 7.4 (kubawerlos) +* minor #4693 Increase Travis CI Git clone depth (julienfalque) +* minor #4699 LineEndingFixer - handle "\r\r\n" (kubawerlos) +* minor #4703 NoSuperfluousPhpdocTagsFixer,PhpdocAddMissingParamAnnotationFixer - p… (SpacePossum) +* minor #4707 Fix typos (TysonAndre) +* minor #4712 NoBlankLinesAfterPhpdocFixer — Do not strip newline between docblock and use statements (mollierobbert) +* minor #4715 Enhancement: Install ergebnis/composer-normalize via Phive (localheinz) +* minor #4722 Fix Circle CI build (julienfalque) +* minor #4724 DX: Simplify installing PCOV (kubawerlos) +* minor #4736 NoUnusedImportsFixer - do not match variable name as import (SpacePossum) +* minor #4746 NoSuperfluousPhpdocTagsFixer - Remove for typed properties (PHP 7.4) (ruudk) +* minor #4753 Do not apply any text/.git filters to fixtures (mvorisek) +* minor #4757 Test $expected is used before $input (SpacePossum) +* minor #4758 Autoreview the PHPDoc of *Fixer::getPriority based on the priority map (SpacePossum) +* minor #4765 Add test on some return types (SpacePossum) +* minor #4766 Remove false test skip (SpacePossum) +* minor #4767 Remove useless priority comments (kubawerlos) +* minor #4769 DX: add missing priority tests (kubawerlos) +* minor #4772 NoUnneededFinalMethodFixer - update description (kubawerlos) +* minor #4774 DX: simplify Utils::camelCaseToUnderscore (kubawerlos) +* minor #4781 NoUnneededCurlyBracesFixer - handle namespaces (SpacePossum) +* minor #4784 Travis CI - Use multiple keyservers (ktomk) +* minor #4785 Improve static analysis (enumag) +* minor #4788 Configurable fixers code sample (SpacePossum) +* minor #4791 Increase PHPStan level to 3 (julienfalque) +* minor #4797 clean ups (SpacePossum) +* minor #4803 FinalClassFixer - Doctrine\ORM\Mapping as ORM alias should not be required (localheinz) +* minor #4839 2.15 - clean ups (SpacePossum) +* minor #4842 ReturnAssignmentFixer - Support more cases (julienfalque) +* minor #4844 Same requirements for descriptions (SpacePossum) +* minor #4849 Increase PHPStan level to 5 (julienfalque) +* minor #4857 Fixed the unit tests (GrahamCampbell) +* minor #4865 Use latest xcode image (GrahamCampbell) +* minor #4892 CombineNestedDirnameFixer - Add space after comma (julienfalque) +* minor #4898 FixerTest - yield the data in AutoReview (Nyholm) +* minor #4899 Fix exception message format for fabbot.io (SpacePossum) +* minor #4905 Support composer v2 installed.json files (GrahamCampbell) +* minor #4906 CI: use Composer stable release for AppVeyor (kubawerlos) +* minor #4909 DX: HeaderCommentFixer - use non-aliased version of option name in code (keradus) +* minor #4912 CI: Fix AppVeyor integration (keradus) + +Changelog for v2.15.5 +--------------------- + +* bug #4476 FunctionsAnalyzer - add "isTheSameClassCall" for correct verifying of function calls (kubawerlos) +* bug #4641 Add typed properties test to VisibilityRequiredFixerTest (GawainLynch, julienfalque) +* bug #4654 ArrayIndentationFixer - Fix array indentation for multiline values (julienfalque) +* bug #4660 TokensAnalyzer::isConstantInvocation - fix for extending multiple interfaces (kubawerlos) +* bug #4668 TokensAnalyzer::isConstantInvocation - fix for interface method return type (kubawerlos) +* minor #4608 Allow Symfony 5 components (l-vo) +* minor #4622 Disallow PHP 7.4 failures on Travis CI (julienfalque) +* minor #4637 PHP 7.4 integration test (GawainLynch, julienfalque) +* minor #4643 DX: Update .gitattributes and move ci-integration.sh to root of the project (kubawerlos, keradus) +* minor #4645 Check PHP extensions on runtime (kubawerlos) +* minor #4655 Improve docs - README (mvorisek) +* minor #4662 DX: generate headers in README.rst (kubawerlos) +* minor #4669 Enable execution under PHP 7.4 (keradus) +* minor #4671 TravisTest - rewrite tests to allow last supported by tool PHP version to be snapshot (keradus) + +Changelog for v2.15.4 +--------------------- + +* bug #4183 IndentationTypeFixer - fix handling 2 spaces indent (kubawerlos) +* bug #4406 NoSuperfluousElseifFixer - fix invalid escape sequence in character class (remicollet, SpacePossum) +* bug #4416 NoUnusedImports - Fix imports detected as used in namespaces (julienfalque, SpacePossum) +* bug #4518 PhpUnitNoExpectationAnnotationFixer - fix handling expect empty exception message (ktomk) +* bug #4548 HeredocIndentationFixer - remove whitespace in empty lines (gharlan) +* bug #4556 ClassKeywordRemoveFixer - fix for self,static and parent keywords (kubawerlos) +* bug #4572 TokensAnalyzer - handle nested anonymous classes (SpacePossum) +* bug #4573 CombineConsecutiveIssetsFixer - fix stop based on precedence (SpacePossum) +* bug #4577 Fix command exit code on lint error after fixing fix. (SpacePossum) +* bug #4581 FunctionsAnalyzer: fix for comment in type (kubawerlos) +* bug #4586 BracesFixer - handle dynamic static method call (SpacePossum) +* bug #4594 Braces - fix both single line comment styles (SpacePossum) +* bug #4609 PhpdocTypesOrderFixer - Prevent unexpected default value change (laurent35240) +* minor #4458 Add PHPStan (julienfalque) +* minor #4479 IncludeFixer - remove braces when the statement is wrapped in block (kubawerlos) +* minor #4490 Allow running if installed as project specific (ticktackk) +* minor #4517 Verify PCRE pattern before use (ktomk) +* minor #4521 Remove superfluous leading backslash, closes 4520 (ktomk) +* minor #4532 DX: ensure data providers are used (kubawerlos) +* minor #4534 Redo PHP7.4 - Add "str_split" => "mb_str_split" mapping (keradus, Slamdunk) +* minor #4536 DX: use PHIVE for dev tools (keradus) +* minor #4538 Docs: update Cookbook (keradus) +* minor #4541 Enhancement: Use default name property to configure command names (localheinz) +* minor #4546 DX: removing unnecessary variable initialization (kubawerlos) +* minor #4549 DX: use ::class whenever possible (keradus, kubawerlos) +* minor #4550 DX: travis_retry for dev-tools install (ktomk, keradus) +* minor #4559 Allow 7.4snapshot to fail due to a bug on it (kubawerlos) +* minor #4563 GitlabReporter - fix report output (mjanser) +* minor #4564 Move readme-update command to Section 3 (iwasherefirst2) +* minor #4566 Update symfony ruleset (gharlan) +* minor #4570 Command::execute() should always return an integer (derrabus) +* minor #4580 Add support for true/false return type hints. (SpacePossum) +* minor #4584 Increase PHPStan level to 1 (julienfalque) +* minor #4585 Fix deprecation notices (julienfalque) +* minor #4587 Output details - Explain why a file was skipped (SpacePossum) +* minor #4588 Fix STDIN test when path is one level deep (julienfalque) +* minor #4589 PhpdocToReturnType - Add support for Foo[][] (SpacePossum) +* minor #4593 Ensure compatibility with PHP 7.4 typed properties (julienfalque) +* minor #4595 Import cannot be used after `::` so can be removed (SpacePossum) +* minor #4596 Ensure compatibility with PHP 7.4 numeric literal separator (julienfalque) +* minor #4597 Fix PHP 7.4 deprecation notices (julienfalque) +* minor #4600 Ensure compatibility with PHP 7.4 arrow functions (julienfalque) +* minor #4602 Ensure compatibility with PHP 7.4 spread operator in array expression (julienfalque) +* minor #4603 Ensure compatibility with PHP 7.4 null coalescing assignment operator (julienfalque) +* minor #4606 Configure no_superfluous_phpdoc_tags for Symfony (keradus) +* minor #4610 Travis CI - Update known files list (julienfalque) +* minor #4615 Remove workaround for dev-tools install reg. Phive (ktomk) + +Changelog for v2.15.3 +--------------------- + +* bug #4533 Revert PHP7.4 - Add "str_split" => "mb_str_split" mapping (keradus) +* minor #4264 DX: AutoReview - ensure Travis handle all needed PHP versions (keradus) +* minor #4524 MethodArgumentSpaceFixerTest - make explicit configuration to prevent fail on configuration change (keradus) + +Changelog for v2.15.2 +--------------------- + +* bug #4132 BlankLineAfterNamespaceFixer - do not remove indent, handle comments (kubawerlos) +* bug #4384 MethodArgumentSpaceFixer - fix for on_multiline:ensure_fully_multiline with trailing comma in function call (kubawerlos) +* bug #4404 FileLintingIterator - fix current value on end/invalid (SpacePossum) +* bug #4421 FunctionTypehintSpaceFixer - Ensure single space between type declaration and parameter (localheinz) +* bug #4436 MethodArgumentSpaceFixer - handle misplaced ) (keradus) +* bug #4439 NoLeadingImportSlashFixer - Add space if needed (SpacePossum) +* bug #4440 SimpleToComplexStringVariableFixer - Fix $ bug (dmvdbrugge) +* bug #4453 Fix preg_match error on 7.4snapshot (kubawerlos) +* bug #4461 IsNullFixer - fix null coalescing operator handling (linniksa) +* bug #4467 ToolInfo - fix access to reference without checking existence (black-silence) +* bug #4472 Fix non-static closure unbinding this on PHP 7.4 (kelunik) +* minor #3726 Use Box 3 to build the PHAR (theofidry, keradus) +* minor #4412 PHP 7.4 - Tests for support (SpacePossum) +* minor #4431 DX: test that default config is not passed in RuleSet (kubawerlos) +* minor #4433 DX: test to ensure @PHPUnitMigration rule sets are correctly defined (kubawerlos) +* minor #4445 DX: static call of markTestSkippedOrFail (kubawerlos) +* minor #4463 Add apostrophe to possessive "team's" (ChandlerSwift) +* minor #4471 ReadmeCommandTest - use CommandTester (kubawerlos) +* minor #4477 DX: control names of public methods in test's classes (kubawerlos) +* minor #4483 NewWithBracesFixer - Fix object operator and curly brace open cases (SpacePossum) +* minor #4484 fix typos in README (Sven Ludwig) +* minor #4494 DX: Fix shell script syntax in order to fix Travis builds (drupol) +* minor #4516 DX: Lock binary SCA tools versions (keradus) + +Changelog for v2.15.1 +--------------------- + +* bug #4418 PhpUnitNamespacedFixer - properly translate classes which do not follow translation pattern (ktomk) +* bug #4419 PhpUnitTestCaseStaticMethodCallsFixer - skip anonymous classes and lambda (SpacePossum) +* bug #4420 MethodArgumentSpaceFixer - PHP7.3 trailing commas in function calls (SpacePossum) +* minor #4345 Travis: PHP 7.4 isn't allowed to fail anymore (Slamdunk) +* minor #4403 LowercaseStaticReferenceFixer - Fix invalid PHP version in example (HypeMC) +* minor #4424 DX: cleanup of composer.json - no need for branch-alias (keradus) +* minor #4425 DX: assertions are static, adjust custom assertions (keradus) +* minor #4426 DX: handle deprecations of symfony/event-dispatcher:4.3 (keradus) +* minor #4427 DX: stop using reserved T_FN in code samples (keradus) +* minor #4428 DX: update dev-tools (keradus) +* minor #4429 DX: MethodArgumentSpaceFixerTest - fix hidden merge conflict (keradus) + +Changelog for v2.15.0 +--------------------- + +* feature #3927 Add FinalClassFixer (Slamdunk) +* feature #3939 Add PhpUnitSizeClassFixer (Jefersson Nathan) +* feature #3942 SimpleToComplexStringVariableFixer - Introduction (dmvdbrugge, SpacePossum) +* feature #4113 OrderedInterfacesFixer - Introduction (dmvdbrugge) +* feature #4121 SingleTraitInsertPerStatementFixer - Introduction (SpacePossum) +* feature #4126 NativeFunctionTypeDeclarationCasingFixer - Introduction (SpacePossum) +* feature #4167 PhpUnitMockShortWillReturnFixer - Introduction (michadam-pearson) +* feature #4191 [7.3] NoWhitespaceBeforeCommaInArrayFixer - fix comma after heredoc-end (gharlan) +* feature #4288 Add Gitlab Reporter (hco) +* feature #4328 Add PhpUnitDedicateAssertInternalTypeFixer (Slamdunk) +* feature #4341 [7.3] TrailingCommaInMultilineArrayFixer - fix comma after heredoc-end (gharlan) +* feature #4342 [7.3] MethodArgumentSpaceFixer - fix comma after heredoc-end (gharlan) +* minor #4112 NoSuperfluousPhpdocTagsFixer - Add missing code sample, groom tests (keradus, SpacePossum) +* minor #4360 Add gitlab as output format in the README/help doc. (SpacePossum) +* minor #4386 Add PhpUnitMockShortWillReturnFixer to @Symfony:risky rule set (kubawerlos) +* minor #4398 New ruleset "@PHP73Migration" (gharlan) +* minor #4399 Fix 2.15 line (keradus) + +Changelog for v2.14.6 +--------------------- + +* bug #4533 Revert PHP7.4 - Add "str_split" => "mb_str_split" mapping (keradus) +* minor #4264 DX: AutoReview - ensure Travis handle all needed PHP versions (keradus) +* minor #4524 MethodArgumentSpaceFixerTest - make explicit configuration to prevent fail on configuration change (keradus) + +Changelog for v2.14.5 +--------------------- + +* bug #4132 BlankLineAfterNamespaceFixer - do not remove indent, handle comments (kubawerlos) +* bug #4384 MethodArgumentSpaceFixer - fix for on_multiline:ensure_fully_multiline with trailing comma in function call (kubawerlos) +* bug #4404 FileLintingIterator - fix current value on end/invalid (SpacePossum) +* bug #4421 FunctionTypehintSpaceFixer - Ensure single space between type declaration and parameter (localheinz) +* bug #4436 MethodArgumentSpaceFixer - handle misplaced ) (keradus) +* bug #4439 NoLeadingImportSlashFixer - Add space if needed (SpacePossum) +* bug #4453 Fix preg_match error on 7.4snapshot (kubawerlos) +* bug #4461 IsNullFixer - fix null coalescing operator handling (linniksa) +* bug #4467 ToolInfo - fix access to reference without checking existence (black-silence) +* bug #4472 Fix non-static closure unbinding this on PHP 7.4 (kelunik) +* minor #3726 Use Box 3 to build the PHAR (theofidry, keradus) +* minor #4412 PHP 7.4 - Tests for support (SpacePossum) +* minor #4431 DX: test that default config is not passed in RuleSet (kubawerlos) +* minor #4433 DX: test to ensure @PHPUnitMigration rule sets are correctly defined (kubawerlos) +* minor #4445 DX: static call of markTestSkippedOrFail (kubawerlos) +* minor #4463 Add apostrophe to possessive "team's" (ChandlerSwift) +* minor #4471 ReadmeCommandTest - use CommandTester (kubawerlos) +* minor #4477 DX: control names of public methods in test's classes (kubawerlos) +* minor #4483 NewWithBracesFixer - Fix object operator and curly brace open cases (SpacePossum) +* minor #4484 fix typos in README (Sven Ludwig) +* minor #4494 DX: Fix shell script syntax in order to fix Travis builds (drupol) +* minor #4516 DX: Lock binary SCA tools versions (keradus) + +Changelog for v2.14.4 +--------------------- + +* bug #4418 PhpUnitNamespacedFixer - properly translate classes which do not follow translation pattern (ktomk) +* bug #4419 PhpUnitTestCaseStaticMethodCallsFixer - skip anonymous classes and lambda (SpacePossum) +* bug #4420 MethodArgumentSpaceFixer - PHP7.3 trailing commas in function calls (SpacePossum) +* minor #4345 Travis: PHP 7.4 isn't allowed to fail anymore (Slamdunk) +* minor #4403 LowercaseStaticReferenceFixer - Fix invalid PHP version in example (HypeMC) +* minor #4425 DX: assertions are static, adjust custom assertions (keradus) +* minor #4426 DX: handle deprecations of symfony/event-dispatcher:4.3 (keradus) +* minor #4427 DX: stop using reserved T_FN in code samples (keradus) +* minor #4428 DX: update dev-tools (keradus) + +Changelog for v2.14.3 +--------------------- + +* bug #4298 NoTrailingWhitespaceInCommentFixer - fix for non-Unix line separators (kubawerlos) +* bug #4303 FullyQualifiedStrictTypesFixer - Fix the short type detection when a question mark (nullable) is prefixing it. (drupol) +* bug #4313 SelfAccessorFixer - fix for part qualified class name (kubawerlos, SpacePossum) +* bug #4314 PhpUnitTestCaseStaticMethodCallsFixer - fix for having property with name as method to update (kubawerlos, SpacePossum) +* bug #4316 NoUnsetCastFixer - Test for higher-precedence operators (SpacePossum) +* bug #4327 TokensAnalyzer - add concat operator to list of binary operators (SpacePossum) +* bug #4335 Cache - add indent and line ending to cache signature (dmvdbrugge) +* bug #4344 VoidReturnFixer - handle yield from (SpacePossum) +* bug #4346 BracesFixer - Do not pull close tag onto same line as a comment (SpacePossum) +* bug #4350 StrictParamFixer - Don't detect functions in use statements (bolmstedt) +* bug #4357 Fix short list syntax detection. (SpacePossum) +* bug #4365 Fix output escaping of diff for text format when line is not changed (SpacePossum) +* bug #4370 PhpUnitConstructFixer - Fix handle different casing (SpacePossum) +* bug #4379 ExplicitStringVariableFixer - add test case for variable as an array key (kubawerlos, Slamdunk) +* feature #4337 PhpUnitTestCaseStaticMethodCallsFixer - prepare for PHPUnit 8 (kubawerlos) +* minor #3799 DX: php_unit_test_case_static_method_calls - use default config (keradus) +* minor #4103 NoExtraBlankLinesFixer - fix candidate detection (SpacePossum) +* minor #4245 LineEndingFixer - BracesFixer - Priority (dmvdbrugge) +* minor #4325 Use lowercase mikey179/vfsStream in composer.json (lolli42) +* minor #4336 Collect coverage with PCOV (kubawerlos) +* minor #4338 Fix wording (kmvan, kubawerlos) +* minor #4339 Change BracesFixer to avoid indenting PHP inline braces (alecgeatches) +* minor #4340 Travis: build against 7.4snapshot instead of nightly (Slamdunk) +* minor #4351 code grooming (SpacePossum) +* minor #4353 Add more priority tests (SpacePossum) +* minor #4364 DX: MethodChainingIndentationFixer - remove unnecessary loop (Sijun Zhu) +* minor #4366 Unset the auxiliary variable $a (GrahamCampbell) +* minor #4368 Fixed TypeShortNameResolverTest::testResolver (GrahamCampbell) +* minor #4380 PHP7.4 - Add "str_split" => "mb_str_split" mapping. (SpacePossum) +* minor #4381 PHP7.4 - Add support for magic methods (un)serialize. (SpacePossum) +* minor #4393 DX: add missing explicit return types (kubawerlos) + +Changelog for v2.14.2 +--------------------- + +* minor #4306 DX: Drop HHVM conflict on Composer level to help Composer with HHVM compatibility, we still prevent HHVM on runtime (keradus) + +Changelog for v2.14.1 +--------------------- + +* bug #4240 ModernizeTypesCastingFixer - fix for operators with higher precedence (kubawerlos) +* bug #4254 PhpUnitDedicateAssertFixer - fix for count with additional operations (kubawerlos) +* bug #4260 Psr0Fixer and Psr4Fixer - fix for multiple classes in file with anonymous class (kubawerlos) +* bug #4262 FixCommand - fix help (keradus) +* bug #4276 MethodChainingIndentationFixer, ArrayIndentationFixer - Fix priority issue (dmvdbrugge) +* bug #4280 MethodArgumentSpaceFixer - Fix method argument alignment (Billz95) +* bug #4286 IncrementStyleFixer - fix for static statement (kubawerlos) +* bug #4291 ArrayIndentationFixer - Fix indentation after trailing spaces (julienfalque, keradus) +* bug #4292 NoSuperfluousPhpdocTagsFixer - Make null only type not considered superfluous (julienfalque) +* minor #4204 DX: Tokens - do not unregister/register found tokens when collection is not changing (kubawerlos) +* minor #4235 DX: more specific @param types (kubawerlos) +* minor #4263 DX: AppVeyor - bump PHP version (keradus) +* minor #4293 Add official support for PHP 7.3 (keradus) +* minor #4295 DX: MethodArgumentSpaceFixerTest - fix edge case for handling different line ending when only expected code is provided (keradus) +* minor #4296 DX: cleanup testing with fixer config (keradus) +* minor #4299 NativeFunctionInvocationFixer - add array_key_exists (deguif, keradus) +* minor #4300 DX: cleanup testing with fixer config (keradus) + +Changelog for v2.14.0 +--------------------- + +* bug #4220 NativeFunctionInvocationFixer - namespaced strict to remove backslash (kubawerlos) +* feature #3881 Add PhpdocVarAnnotationCorrectOrderFixer (kubawerlos) +* feature #3915 Add HeredocIndentationFixer (gharlan) +* feature #4002 NoSuperfluousPhpdocTagsFixer - Allow `mixed` in superfluous PHPDoc by configuration (MortalFlesh) +* feature #4030 Add get_required_files and user_error aliases (ntzm) +* feature #4043 NativeFunctionInvocationFixer - add option to remove redundant backslashes (kubawerlos) +* feature #4102 Add NoUnsetCastFixer (SpacePossum) +* minor #4025 Add phpdoc_types_order rule to Symfony's ruleset (carusogabriel) +* minor #4213 [7.3] PHP7.3 integration tests (SpacePossum) +* minor #4233 Add official support for PHP 7.3 (keradus) + +Changelog for v2.13.3 +--------------------- + +* bug #4216 Psr4Fixer - fix for multiple classy elements in file (keradus, kubawerlos) +* bug #4217 Psr0Fixer - class with anonymous class (kubawerlos) +* bug #4219 NativeFunctionCasingFixer - handle T_RETURN_REF (kubawerlos) +* bug #4224 FunctionToConstantFixer - handle T_RETURN_REF (SpacePossum) +* bug #4229 IsNullFixer - fix parenthesis not closed (guilliamxavier) +* minor #4193 [7.3] CombineNestedDirnameFixer - support PHP 7.3 (kubawerlos) +* minor #4198 [7.3] PowToExponentiationFixer - adding to PHP7.3 integration test (kubawerlos) +* minor #4199 [7.3] MethodChainingIndentationFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4200 [7.3] ModernizeTypesCastingFixer - support PHP 7.3 (kubawerlos) +* minor #4201 [7.3] MultilineWhitespaceBeforeSemicolonsFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4202 [7.3] ErrorSuppressionFixer - support PHP 7.3 (kubawerlos) +* minor #4205 DX: PhpdocAlignFixer - refactor to use DocBlock (kubawerlos) +* minor #4206 DX: enable multiline_whitespace_before_semicolons (keradus) +* minor #4207 [7.3] RandomApiMigrationFixerTest - tests for 7.3 (SpacePossum) +* minor #4208 [7.3] NativeFunctionCasingFixerTest - tests for 7.3 (SpacePossum) +* minor #4209 [7.3] PhpUnitStrictFixerTest - tests for 7.3 (SpacePossum) +* minor #4210 [7.3] PhpUnitConstructFixer - add test for PHP 7.3 (kubawerlos) +* minor #4211 [7.3] PhpUnitDedicateAssertFixer - support PHP 7.3 (kubawerlos) +* minor #4214 [7.3] NoUnsetOnPropertyFixerTest - tests for 7.3 (SpacePossum) +* minor #4222 [7.3] PhpUnitExpectationFixer - support PHP 7.3 (kubawerlos) +* minor #4223 [7.3] PhpUnitMockFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4230 [7.3] IsNullFixer - fix trailing comma (guilliamxavier) +* minor #4232 DX: remove Utils::splitLines (kubawerlos) +* minor #4234 [7.3] Test that "LITERAL instanceof X" is valid (guilliamxavier) + +Changelog for v2.13.2 +--------------------- + +* bug #3968 SelfAccessorFixer - support FQCN (kubawerlos) +* bug #3974 Psr4Fixer - class with anonymous class (kubawerlos) +* bug #3987 Run HeaderCommentFixer after NoBlankLinesAfterPhpdocFixer (StanAngeloff) +* bug #4009 TypeAlternationTransformer - Fix pipes in function call with constants being classified incorrectly (ntzm, SpacePossum) +* bug #4022 NoUnsetOnPropertyFixer - refactor and bugfixes (kubawerlos) +* bug #4036 ExplicitStringVariableFixer - fixes for backticks and for 2 variables next to each other (kubawerlos, Slamdunk) +* bug #4038 CommentToPhpdocFixer - handling nested PHPDoc (kubawerlos) +* bug #4064 Ignore invalid mode strings, add option to remove the "b" flag. (SpacePossum) +* bug #4071 DX: do not insert Token when calling removeLeadingWhitespace/removeTrailingWhitespace from Tokens (kubawerlos) +* bug #4073 IsNullFixer - fix function detection (kubawerlos) +* bug #4074 FileFilterIterator - do not filter out files that need fixing (SpacePossum) +* bug #4076 EregToPregFixer - fix function detection (kubawerlos) +* bug #4084 MethodChainingIndentation - fix priority with Braces (dmvdbrugge) +* bug #4099 HeaderCommentFixer - throw exception on invalid header configuration (SpacePossum) +* bug #4100 PhpdocAddMissingParamAnnotationFixer - Handle variable number of arguments and pass by reference cases (SpacePossum) +* bug #4101 ReturnAssignmentFixer - do not touch invalid code (SpacePossum) +* bug #4104 Change transformers order, fixing untransformed T_USE (dmvdbrugge) +* bug #4107 Preg::split - fix for non-UTF8 subject (ostrolucky, kubawerlos) +* bug #4109 NoBlankLines*: fix removing lines consisting only of spaces (kubawerlos, keradus) +* bug #4114 VisibilityRequiredFixer - don't remove comments (kubawerlos) +* bug #4116 OrderedImportsFixer - fix sorting without any grouping (SpacePossum) +* bug #4119 PhpUnitNoExpectationAnnotationFixer - fix extracting content from annotation (kubawerlos) +* bug #4127 LowercaseConstantsFixer - Fix case with properties using constants as their name (srathbone) +* bug #4134 [7.3] SquareBraceTransformer - nested array destructuring not handled correctly (SpacePossum) +* bug #4153 PhpUnitFqcnAnnotationFixer - handle only PhpUnit classes (kubawerlos) +* bug #4169 DirConstantFixer - Fixes for PHP7.3 syntax (SpacePossum) +* bug #4181 MultilineCommentOpeningClosingFixer - fix handling empty comment (kubawerlos) +* bug #4186 Tokens - fix removal of leading/trailing whitespace with empty token in collection (kubawerlos) +* minor #3436 Add a handful of integration tests (BackEndTea) +* minor #3774 PhpUnitTestClassRequiresCoversFixer - Remove unneeded loop and use phpunit indicator class (BackEndTea, SpacePossum) +* minor #3778 DX: Throw an exception if FileReader::read fails (ntzm) +* minor #3916 New ruleset "@PhpCsFixer" (gharlan) +* minor #4007 Fixes cookbook for fixers (greeflas) +* minor #4031 Correct FixerOptionBuilder::getOption return type (ntzm) +* minor #4046 Token - Added fast isset() path to token->equals() (staabm) +* minor #4047 Token - inline $other->getPrototype() to speedup equals() (staabm, keradus) +* minor #4048 Tokens - inlined extractTokenKind() call on the hot path (staabm) +* minor #4069 DX: Add dev-tools directory to gitattributes as export-ignore (alexmanno) +* minor #4070 Docs: Add link to a VS Code extension in readme (jakebathman) +* minor #4077 DX: cleanup - NoAliasFunctionsFixer - use FunctionsAnalyzer (kubawerlos) +* minor #4088 Add Travis test with strict types (kubawerlos) +* minor #4091 Adjust misleading sentence in CONTRIBUTING.md (ostrolucky) +* minor #4092 UseTransformer - simplify/optimize (SpacePossum) +* minor #4095 DX: Use ::class (keradus) +* minor #4096 DX: fixing typo (kubawerlos) +* minor #4097 DX: namespace casing (kubawerlos) +* minor #4110 Enhancement: Update localheinz/composer-normalize (localheinz) +* minor #4115 Changes for upcoming Travis' infra migration (sergeyklay) +* minor #4122 DX: AppVeyor - Update Composer download link (SpacePossum) +* minor #4128 DX: cleanup - AbstractFunctionReferenceFixer - use FunctionsAnalyzer (SpacePossum, kubawerlos) +* minor #4129 Fix: Symfony 4.2 deprecations (kubawerlos) +* minor #4139 DX: Fix CircleCI (kubawerlos) +* minor #4142 [7.3] NoAliasFunctionsFixer - mbregex_encoding' => 'mb_regex_encoding (SpacePossum) +* minor #4143 PhpUnitTestCaseStaticMethodCallsFixer - Add PHPUnit 7.5 new assertions (Slamdunk) +* minor #4149 [7.3] ArgumentsAnalyzer - PHP7.3 support (SpacePossum) +* minor #4161 DX: CI - show packages installed via Composer (keradus) +* minor #4162 DX: Drop symfony/lts (keradus) +* minor #4166 DX: do not use AbstractFunctionReferenceFixer when no need to (kubawerlos) +* minor #4168 DX: FopenFlagsFixer - remove useless proxy method (SpacePossum) +* minor #4171 Fix CircleCI cache (kubawerlos) +* minor #4173 [7.3] PowToExponentiationFixer - add support for PHP7.3 (SpacePossum) +* minor #4175 Fixing typo (kubawerlos) +* minor #4177 CI: Check that tag is matching version of PHP CS Fixer during deployment (keradus) +* minor #4180 Fixing typo (kubawerlos) +* minor #4182 DX: update php-cs-fixer file style (kubawerlos) +* minor #4185 [7.3] ImplodeCallFixer - add tests for PHP7.3 (kubawerlos) +* minor #4187 [7.3] IsNullFixer - support PHP 7.3 (kubawerlos) +* minor #4188 DX: cleanup (keradus) +* minor #4189 Travis - add PHP 7.3 job (keradus) +* minor #4190 Travis CI - fix config (kubawerlos) +* minor #4192 [7.3] MagicMethodCasingFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4194 [7.3] NativeFunctionInvocationFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4195 [7.3] SetTypeToCastFixer - support PHP 7.3 (kubawerlos) +* minor #4196 Update website (keradus) +* minor #4197 [7.3] StrictParamFixer - support PHP 7.3 (kubawerlos) + +Changelog for v2.13.1 +--------------------- + +* bug #3977 NoSuperfluousPhpdocTagsFixer - Fix handling of description with variable (julienfalque) +* bug #4027 PhpdocAnnotationWithoutDotFixer - add failing cases (keradus) +* bug #4028 PhpdocNoEmptyReturnFixer - handle single line PHPDoc (kubawerlos) +* bug #4034 PhpUnitTestCaseIndicator - handle anonymous class (kubawerlos) +* bug #4037 NativeFunctionInvocationFixer - fix function detection (kubawerlos) +* feature #4019 PhpdocTypesFixer - allow for configuration (keradus) +* minor #3980 Clarifies allow-risky usage (josephzidell) +* minor #4016 Bump console component due to it's bug (keradus) +* minor #4023 Enhancement: Update localheinz/composer-normalize (localheinz) +* minor #4049 use parent::offset*() methods when moving items around in insertAt() (staabm) + +Changelog for v2.13.0 +--------------------- + +* feature #3739 Add MagicMethodCasingFixer (SpacePossum) +* feature #3812 Add FopenFlagOrderFixer & FopenFlagsFixer (SpacePossum) +* feature #3826 Add CombineNestedDirnameFixer (gharlan) +* feature #3833 BinaryOperatorSpacesFixer - Add "no space" fix strategy (SpacePossum) +* feature #3841 NoAliasFunctionsFixer - add opt in option for ext-mbstring aliases (SpacePossum) +* feature #3876 NativeConstantInvocationFixer - add the scope option (stof, keradus) +* feature #3886 Add PhpUnitMethodCasingFixer (Slamdunk) +* feature #3907 Add ImplodeCallFixer (kubawerlos) +* feature #3914 NoUnreachableDefaultArgumentValueFixer - remove `null` for nullable typehints (gharlan, keradus) +* minor #3813 PhpUnitDedicateAssertFixer - fix "sizeOf" same as "count". (SpacePossum) +* minor #3873 Add the native_function_invocation fixer in the Symfony:risky ruleset (stof) +* minor #3979 DX: enable php_unit_method_casing (keradus) + +Changelog for v2.12.12 +---------------------- + +* bug #4533 Revert PHP7.4 - Add "str_split" => "mb_str_split" mapping (keradus) +* minor #4264 DX: AutoReview - ensure Travis handle all needed PHP versions (keradus) +* minor #4524 MethodArgumentSpaceFixerTest - make explicit configuration to prevent fail on configuration change (keradus) + +Changelog for v2.12.11 +---------------------- + +* bug #4132 BlankLineAfterNamespaceFixer - do not remove indent, handle comments (kubawerlos) +* bug #4384 MethodArgumentSpaceFixer - fix for on_multiline:ensure_fully_multiline with trailing comma in function call (kubawerlos) +* bug #4404 FileLintingIterator - fix current value on end/invalid (SpacePossum) +* bug #4421 FunctionTypehintSpaceFixer - Ensure single space between type declaration and parameter (localheinz) +* bug #4436 MethodArgumentSpaceFixer - handle misplaced ) (keradus) +* bug #4439 NoLeadingImportSlashFixer - Add space if needed (SpacePossum) +* bug #4453 Fix preg_match error on 7.4snapshot (kubawerlos) +* bug #4461 IsNullFixer - fix null coalescing operator handling (linniksa) +* bug #4467 ToolInfo - fix access to reference without checking existence (black-silence) +* bug #4472 Fix non-static closure unbinding this on PHP 7.4 (kelunik) +* minor #3726 Use Box 3 to build the PHAR (theofidry, keradus) +* minor #4412 PHP 7.4 - Tests for support (SpacePossum) +* minor #4431 DX: test that default config is not passed in RuleSet (kubawerlos) +* minor #4433 DX: test to ensure @PHPUnitMigration rule sets are correctly defined (kubawerlos) +* minor #4445 DX: static call of markTestSkippedOrFail (kubawerlos) +* minor #4463 Add apostrophe to possessive "team's" (ChandlerSwift) +* minor #4471 ReadmeCommandTest - use CommandTester (kubawerlos) +* minor #4477 DX: control names of public methods in test's classes (kubawerlos) +* minor #4483 NewWithBracesFixer - Fix object operator and curly brace open cases (SpacePossum) +* minor #4484 fix typos in README (Sven Ludwig) +* minor #4494 DX: Fix shell script syntax in order to fix Travis builds (drupol) +* minor #4516 DX: Lock binary SCA tools versions (keradus) + +Changelog for v2.12.10 +---------------------- + +* bug #4418 PhpUnitNamespacedFixer - properly translate classes which do not follow translation pattern (ktomk) +* bug #4419 PhpUnitTestCaseStaticMethodCallsFixer - skip anonymous classes and lambda (SpacePossum) +* bug #4420 MethodArgumentSpaceFixer - PHP7.3 trailing commas in function calls (SpacePossum) +* minor #4345 Travis: PHP 7.4 isn't allowed to fail anymore (Slamdunk) +* minor #4403 LowercaseStaticReferenceFixer - Fix invalid PHP version in example (HypeMC) +* minor #4425 DX: assertions are static, adjust custom assertions (keradus) +* minor #4426 DX: handle deprecations of symfony/event-dispatcher:4.3 (keradus) +* minor #4427 DX: stop using reserved T_FN in code samples (keradus) + +Changelog for v2.12.9 +--------------------- + +* bug #4298 NoTrailingWhitespaceInCommentFixer - fix for non-Unix line separators (kubawerlos) +* bug #4303 FullyQualifiedStrictTypesFixer - Fix the short type detection when a question mark (nullable) is prefixing it. (drupol) +* bug #4313 SelfAccessorFixer - fix for part qualified class name (kubawerlos, SpacePossum) +* bug #4314 PhpUnitTestCaseStaticMethodCallsFixer - fix for having property with name as method to update (kubawerlos, SpacePossum) +* bug #4327 TokensAnalyzer - add concat operator to list of binary operators (SpacePossum) +* bug #4335 Cache - add indent and line ending to cache signature (dmvdbrugge) +* bug #4344 VoidReturnFixer - handle yield from (SpacePossum) +* bug #4346 BracesFixer - Do not pull close tag onto same line as a comment (SpacePossum) +* bug #4350 StrictParamFixer - Don't detect functions in use statements (bolmstedt) +* bug #4357 Fix short list syntax detection. (SpacePossum) +* bug #4365 Fix output escaping of diff for text format when line is not changed (SpacePossum) +* bug #4370 PhpUnitConstructFixer - Fix handle different casing (SpacePossum) +* bug #4379 ExplicitStringVariableFixer - add test case for variable as an array key (kubawerlos, Slamdunk) +* feature #4337 PhpUnitTestCaseStaticMethodCallsFixer - prepare for PHPUnit 8 (kubawerlos) +* minor #3799 DX: php_unit_test_case_static_method_calls - use default config (keradus) +* minor #4103 NoExtraBlankLinesFixer - fix candidate detection (SpacePossum) +* minor #4245 LineEndingFixer - BracesFixer - Priority (dmvdbrugge) +* minor #4325 Use lowercase mikey179/vfsStream in composer.json (lolli42) +* minor #4336 Collect coverage with PCOV (kubawerlos) +* minor #4338 Fix wording (kmvan, kubawerlos) +* minor #4339 Change BracesFixer to avoid indenting PHP inline braces (alecgeatches) +* minor #4340 Travis: build against 7.4snapshot instead of nightly (Slamdunk) +* minor #4351 code grooming (SpacePossum) +* minor #4353 Add more priority tests (SpacePossum) +* minor #4364 DX: MethodChainingIndentationFixer - remove unnecessary loop (Sijun Zhu) +* minor #4366 Unset the auxiliary variable $a (GrahamCampbell) +* minor #4368 Fixed TypeShortNameResolverTest::testResolver (GrahamCampbell) +* minor #4380 PHP7.4 - Add "str_split" => "mb_str_split" mapping. (SpacePossum) +* minor #4393 DX: add missing explicit return types (kubawerlos) + +Changelog for v2.12.8 +--------------------- + +* minor #4306 DX: Drop HHVM conflict on Composer level to help Composer with HHVM compatibility, we still prevent HHVM on runtime (keradus) + +Changelog for v2.12.7 +--------------------- + +* bug #4240 ModernizeTypesCastingFixer - fix for operators with higher precedence (kubawerlos) +* bug #4254 PhpUnitDedicateAssertFixer - fix for count with additional operations (kubawerlos) +* bug #4260 Psr0Fixer and Psr4Fixer - fix for multiple classes in file with anonymous class (kubawerlos) +* bug #4262 FixCommand - fix help (keradus) +* bug #4276 MethodChainingIndentationFixer, ArrayIndentationFixer - Fix priority issue (dmvdbrugge) +* bug #4280 MethodArgumentSpaceFixer - Fix method argument alignment (Billz95) +* bug #4286 IncrementStyleFixer - fix for static statement (kubawerlos) +* bug #4291 ArrayIndentationFixer - Fix indentation after trailing spaces (julienfalque, keradus) +* bug #4292 NoSuperfluousPhpdocTagsFixer - Make null only type not considered superfluous (julienfalque) +* minor #4204 DX: Tokens - do not unregister/register found tokens when collection is not changing (kubawerlos) +* minor #4235 DX: more specific @param types (kubawerlos) +* minor #4263 DX: AppVeyor - bump PHP version (keradus) +* minor #4293 Add official support for PHP 7.3 (keradus) +* minor #4295 DX: MethodArgumentSpaceFixerTest - fix edge case for handling different line ending when only expected code is provided (keradus) +* minor #4296 DX: cleanup testing with fixer config (keradus) +* minor #4299 NativeFunctionInvocationFixer - add array_key_exists (deguif, keradus) + +Changelog for v2.12.6 +--------------------- + +* bug #4216 Psr4Fixer - fix for multiple classy elements in file (keradus, kubawerlos) +* bug #4217 Psr0Fixer - class with anonymous class (kubawerlos) +* bug #4219 NativeFunctionCasingFixer - handle T_RETURN_REF (kubawerlos) +* bug #4224 FunctionToConstantFixer - handle T_RETURN_REF (SpacePossum) +* bug #4229 IsNullFixer - fix parenthesis not closed (guilliamxavier) +* minor #4198 [7.3] PowToExponentiationFixer - adding to PHP7.3 integration test (kubawerlos) +* minor #4199 [7.3] MethodChainingIndentationFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4200 [7.3] ModernizeTypesCastingFixer - support PHP 7.3 (kubawerlos) +* minor #4201 [7.3] MultilineWhitespaceBeforeSemicolonsFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4202 [7.3] ErrorSuppressionFixer - support PHP 7.3 (kubawerlos) +* minor #4205 DX: PhpdocAlignFixer - refactor to use DocBlock (kubawerlos) +* minor #4206 DX: enable multiline_whitespace_before_semicolons (keradus) +* minor #4207 [7.3] RandomApiMigrationFixerTest - tests for 7.3 (SpacePossum) +* minor #4208 [7.3] NativeFunctionCasingFixerTest - tests for 7.3 (SpacePossum) +* minor #4209 [7.3] PhpUnitStrictFixerTest - tests for 7.3 (SpacePossum) +* minor #4210 [7.3] PhpUnitConstructFixer - add test for PHP 7.3 (kubawerlos) +* minor #4211 [7.3] PhpUnitDedicateAssertFixer - support PHP 7.3 (kubawerlos) +* minor #4214 [7.3] NoUnsetOnPropertyFixerTest - tests for 7.3 (SpacePossum) +* minor #4222 [7.3] PhpUnitExpectationFixer - support PHP 7.3 (kubawerlos) +* minor #4223 [7.3] PhpUnitMockFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4230 [7.3] IsNullFixer - fix trailing comma (guilliamxavier) +* minor #4232 DX: remove Utils::splitLines (kubawerlos) +* minor #4234 [7.3] Test that "LITERAL instanceof X" is valid (guilliamxavier) + +Changelog for v2.12.5 +--------------------- + +* bug #3968 SelfAccessorFixer - support FQCN (kubawerlos) +* bug #3974 Psr4Fixer - class with anonymous class (kubawerlos) +* bug #3987 Run HeaderCommentFixer after NoBlankLinesAfterPhpdocFixer (StanAngeloff) +* bug #4009 TypeAlternationTransformer - Fix pipes in function call with constants being classified incorrectly (ntzm, SpacePossum) +* bug #4022 NoUnsetOnPropertyFixer - refactor and bugfixes (kubawerlos) +* bug #4036 ExplicitStringVariableFixer - fixes for backticks and for 2 variables next to each other (kubawerlos, Slamdunk) +* bug #4038 CommentToPhpdocFixer - handling nested PHPDoc (kubawerlos) +* bug #4071 DX: do not insert Token when calling removeLeadingWhitespace/removeTrailingWhitespace from Tokens (kubawerlos) +* bug #4073 IsNullFixer - fix function detection (kubawerlos) +* bug #4074 FileFilterIterator - do not filter out files that need fixing (SpacePossum) +* bug #4076 EregToPregFixer - fix function detection (kubawerlos) +* bug #4084 MethodChainingIndentation - fix priority with Braces (dmvdbrugge) +* bug #4099 HeaderCommentFixer - throw exception on invalid header configuration (SpacePossum) +* bug #4100 PhpdocAddMissingParamAnnotationFixer - Handle variable number of arguments and pass by reference cases (SpacePossum) +* bug #4101 ReturnAssignmentFixer - do not touch invalid code (SpacePossum) +* bug #4104 Change transformers order, fixing untransformed T_USE (dmvdbrugge) +* bug #4107 Preg::split - fix for non-UTF8 subject (ostrolucky, kubawerlos) +* bug #4109 NoBlankLines*: fix removing lines consisting only of spaces (kubawerlos, keradus) +* bug #4114 VisibilityRequiredFixer - don't remove comments (kubawerlos) +* bug #4116 OrderedImportsFixer - fix sorting without any grouping (SpacePossum) +* bug #4119 PhpUnitNoExpectationAnnotationFixer - fix extracting content from annotation (kubawerlos) +* bug #4127 LowercaseConstantsFixer - Fix case with properties using constants as their name (srathbone) +* bug #4134 [7.3] SquareBraceTransformer - nested array destructuring not handled correctly (SpacePossum) +* bug #4153 PhpUnitFqcnAnnotationFixer - handle only PhpUnit classes (kubawerlos) +* bug #4169 DirConstantFixer - Fixes for PHP7.3 syntax (SpacePossum) +* bug #4181 MultilineCommentOpeningClosingFixer - fix handling empty comment (kubawerlos) +* bug #4186 Tokens - fix removal of leading/trailing whitespace with empty token in collection (kubawerlos) +* minor #3436 Add a handful of integration tests (BackEndTea) +* minor #3774 PhpUnitTestClassRequiresCoversFixer - Remove unneeded loop and use phpunit indicator class (BackEndTea, SpacePossum) +* minor #3778 DX: Throw an exception if FileReader::read fails (ntzm) +* minor #3916 New ruleset "@PhpCsFixer" (gharlan) +* minor #4007 Fixes cookbook for fixers (greeflas) +* minor #4031 Correct FixerOptionBuilder::getOption return type (ntzm) +* minor #4046 Token - Added fast isset() path to token->equals() (staabm) +* minor #4047 Token - inline $other->getPrototype() to speedup equals() (staabm, keradus) +* minor #4048 Tokens - inlined extractTokenKind() call on the hot path (staabm) +* minor #4069 DX: Add dev-tools directory to gitattributes as export-ignore (alexmanno) +* minor #4070 Docs: Add link to a VS Code extension in readme (jakebathman) +* minor #4077 DX: cleanup - NoAliasFunctionsFixer - use FunctionsAnalyzer (kubawerlos) +* minor #4088 Add Travis test with strict types (kubawerlos) +* minor #4091 Adjust misleading sentence in CONTRIBUTING.md (ostrolucky) +* minor #4092 UseTransformer - simplify/optimize (SpacePossum) +* minor #4095 DX: Use ::class (keradus) +* minor #4097 DX: namespace casing (kubawerlos) +* minor #4110 Enhancement: Update localheinz/composer-normalize (localheinz) +* minor #4115 Changes for upcoming Travis' infra migration (sergeyklay) +* minor #4122 DX: AppVeyor - Update Composer download link (SpacePossum) +* minor #4128 DX: cleanup - AbstractFunctionReferenceFixer - use FunctionsAnalyzer (SpacePossum, kubawerlos) +* minor #4129 Fix: Symfony 4.2 deprecations (kubawerlos) +* minor #4139 DX: Fix CircleCI (kubawerlos) +* minor #4143 PhpUnitTestCaseStaticMethodCallsFixer - Add PHPUnit 7.5 new assertions (Slamdunk) +* minor #4149 [7.3] ArgumentsAnalyzer - PHP7.3 support (SpacePossum) +* minor #4161 DX: CI - show packages installed via Composer (keradus) +* minor #4162 DX: Drop symfony/lts (keradus) +* minor #4166 DX: do not use AbstractFunctionReferenceFixer when no need to (kubawerlos) +* minor #4171 Fix CircleCI cache (kubawerlos) +* minor #4173 [7.3] PowToExponentiationFixer - add support for PHP7.3 (SpacePossum) +* minor #4175 Fixing typo (kubawerlos) +* minor #4177 CI: Check that tag is matching version of PHP CS Fixer during deployment (keradus) +* minor #4182 DX: update php-cs-fixer file style (kubawerlos) +* minor #4187 [7.3] IsNullFixer - support PHP 7.3 (kubawerlos) +* minor #4188 DX: cleanup (keradus) +* minor #4189 Travis - add PHP 7.3 job (keradus) +* minor #4190 Travis CI - fix config (kubawerlos) +* minor #4194 [7.3] NativeFunctionInvocationFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4195 [7.3] SetTypeToCastFixer - support PHP 7.3 (kubawerlos) +* minor #4196 Update website (keradus) +* minor #4197 [7.3] StrictParamFixer - support PHP 7.3 (kubawerlos) + +Changelog for v2.12.4 +--------------------- + +* bug #3977 NoSuperfluousPhpdocTagsFixer - Fix handling of description with variable (julienfalque) +* bug #4027 PhpdocAnnotationWithoutDotFixer - add failing cases (keradus) +* bug #4028 PhpdocNoEmptyReturnFixer - handle single line PHPDoc (kubawerlos) +* bug #4034 PhpUnitTestCaseIndicator - handle anonymous class (kubawerlos) +* bug #4037 NativeFunctionInvocationFixer - fix function detection (kubawerlos) +* feature #4019 PhpdocTypesFixer - allow for configuration (keradus) +* minor #3980 Clarifies allow-risky usage (josephzidell) +* minor #4016 Bump console component due to it's bug (keradus) +* minor #4023 Enhancement: Update localheinz/composer-normalize (localheinz) +* minor #4049 use parent::offset*() methods when moving items around in insertAt() (staabm) + +Changelog for v2.12.3 +--------------------- + +* bug #3867 PhpdocAnnotationWithoutDotFixer - Handle trailing whitespaces (kubawerlos) +* bug #3884 NoSuperfluousPhpdocTagsFixer - handle null in every position (dmvdbrugge, julienfalque) +* bug #3885 AlignMultilineCommentFixer - ArrayIndentationFixer - Priority (dmvdbrugge) +* bug #3887 ArrayIndentFixer - Don't indent empty lines (dmvdbrugge) +* bug #3888 NoExtraBlankLinesFixer - remove blank lines after open tag (kubawerlos) +* bug #3890 StrictParamFixer - make it case-insensitive (kubawerlos) +* bug #3895 FunctionsAnalyzer - false positive for constant and function definition (kubawerlos) +* bug #3908 StrictParamFixer - fix edge case (kubawerlos) +* bug #3910 FunctionsAnalyzer - fix isGlobalFunctionCall (gharlan) +* bug #3912 FullyQualifiedStrictTypesFixer - NoSuperfluousPhpdocTagsFixer - adjust priority (dmvdbrugge) +* bug #3913 TokensAnalyzer - fix isConstantInvocation (gharlan, keradus) +* bug #3921 TypeAnalysis - Fix iterable not being detected as a reserved type (ntzm) +* bug #3924 FullyQualifiedStrictTypesFixer - space bug (dmvdbrugge) +* bug #3937 LowercaseStaticReferenceFixer - Fix "Parent" word in namespace (kubawerlos) +* bug #3944 ExplicitStringVariableFixer - fix array handling (gharlan) +* bug #3951 NoSuperfluousPhpdocTagsFixer - do not call strtolower with null (SpacePossum) +* bug #3954 NoSuperfluousPhpdocTagsFixer - Index invalid or out of range (kubawerlos) +* bug #3957 NoTrailingWhitespaceFixer - trim space after opening tag (kubawerlos) +* minor #3798 DX: enable native_function_invocation (keradus) +* minor #3882 PhpdocAnnotationWithoutDotFixer - Handle empty line in comment (kubawerlos) +* minor #3889 DX: Cleanup - remove unused variables (kubawerlos, SpacePossum) +* minor #3891 PhpdocNoEmptyReturnFixer - account for null[] (dmvdbrugge) +* minor #3892 PhpdocNoEmptyReturnFixer - fix docs (keradus) +* minor #3897 DX: FunctionsAnalyzer - simplifying return expression (kubawerlos) +* minor #3903 DX: cleanup - remove special treatment for PHP <5.6 (kubawerlos) +* minor #3905 DX: Upgrade composer-require-checker to stable version (keradus) +* minor #3919 Simplify single uses of Token::isGivenKind (ntzm) +* minor #3920 Docs: Fix typo (ntzm) +* minor #3940 DX: fix phpdoc parameter type (malukenho) +* minor #3948 DX: cleanup - remove redundant @param annotations (kubawerlos) +* minor #3950 Circle CI v2 yml (siad007) +* minor #3952 DX: AbstractFixerTestCase - drop testing method already provided by trait (keradus) +* minor #3973 Bump xdebug-handler (keradus) + +Changelog for v2.12.2 +--------------------- + +* bug #3823 NativeConstantInvocationFixer - better constant detection (gharlan, SpacePossum, keradus) +* bug #3832 "yield from" as keyword (SpacePossum) +* bug #3835 Fix priority between PHPDoc return type fixers (julienfalque, keradus) +* bug #3839 MethodArgumentSpaceFixer - add empty line incorrectly (SpacePossum) +* bug #3866 SpaceAfterSemicolonFixer - loop over all tokens (SpacePossum) +* minor #3817 Update integrations tests (SpacePossum) +* minor #3829 Fix typos in changelog (mnabialek) +* minor #3848 Add install/update instructions for PHIVE to the README (SpacePossum) +* minor #3877 NamespacesAnalyzer - Optimize performance (stof) +* minor #3878 NativeFunctionInvocationFixer - use the NamespacesAnalyzer to remove duplicated code (stof) + +Changelog for v2.12.1 +--------------------- + +* bug #3808 LowercaseStaticReferenceFixer - Fix constants handling (kubawerlos, keradus) +* bug #3815 NoSuperfluousPhpdocTagsFixer - support array/callable type hints (gharlan) +* minor #3824 DX: Support PHPUnit 7.2 (keradus) +* minor #3825 UX: Provide full diff for code samples (keradus) + +Changelog for v2.12.0 +--------------------- + +* feature #2577 Add LogicalOperatorsFixer (hkdobrev, keradus) +* feature #3060 Add ErrorSuppressionFixer (kubawerlos) +* feature #3127 Add NativeConstantInvocationFixer (Slamdunk, keradus) +* feature #3223 NativeFunctionInvocationFixer - add namespace scope and include sets (SpacePossum) +* feature #3453 PhpdocAlignFixer - add align option (robert.ahmerov) +* feature #3476 Add PhpUnitTestCaseStaticMethodCallsFixer (Slamdunk, keradus) +* feature #3524 MethodArgumentSpaceFixer - Add ensure_single_line option (julienfalque, keradus) +* feature #3534 MultilineWhitespaceBeforeSemicolonsFixer - support static calls (ntzm) +* feature #3585 Add ReturnAssignmentFixer (SpacePossum, keradus) +* feature #3640 Add PhpdocToReturnTypeFixer (Slamdunk, keradus) +* feature #3691 Add PhpdocTrimAfterDescriptionFixer (nobuf, keradus) +* feature #3698 YodaStyleFixer - Add always_move_variable option (julienfalque, SpacePossum) +* feature #3709 Add SetTypeToCastFixer (SpacePossum) +* feature #3724 BlankLineBeforeStatementFixer - Add case and default as options (dmvdbrugge) +* feature #3734 Add NoSuperfluousPhpdocTagsFixer (julienfalque) +* feature #3735 Add LowercaseStaticReferenceFixer (kubawerlos, SpacePossum) +* feature #3737 Add NoUnsetOnPropertyFixer (BackEndTea, SpacePossum) +* feature #3745 Add PhpUnitInternalClassFixer (BackEndTea, SpacePossum, keradus) +* feature #3766 Add NoBinaryStringFixer (ntzm, SpacePossum, keradus) +* feature #3780 ShortScalarCastFixer - Change binary cast to string cast as well (ntzm) +* feature #3785 PhpUnitDedicateAssertFixer - fix to assertCount too (SpacePossum) +* feature #3802 Convert PhpdocTrimAfterDescriptionFixer into PhpdocTrimConsecutiveBlankLineSeparationFixer (keradus) +* minor #3738 ReturnAssignmentFixer description update (kubawerlos) +* minor #3761 Application: when run with FUTURE_MODE, error_reporting(-1) is done in entry file instead (keradus) +* minor #3772 DX: use PhpUnitTestCaseIndicator->isPhpUnitClass to discover PHPUnit classes (keradus) +* minor #3783 CI: Split COLLECT_COVERAGE job (keradus) +* minor #3789 DX: ProjectCodeTest.testThatDataProvidersAreCorrectlyNamed - performance optimization (keradus) +* minor #3791 DX: Fix collecting code coverage (keradus) +* minor #3792 DX: Upgrade DX deps (keradus) +* minor #3797 DX: ProjectCodeTest - shall not depends on xdebug/phpdbg anymore (keradus, SpacePossum) +* minor #3800 Symfony:risky ruleset: include set_type_to_cast rule (keradus) +* minor #3801 NativeFunctionInvocationFixer - fix buggy config validation (keradus, SpacePossum) + +Changelog for v2.11.2 +--------------------- + +* bug #3233 PhpdocAlignFixer - Fix linebreak inconsistency (SpacePossum, keradus) +* bug #3445 Rewrite NoUnusedImportsFixer (kubawerlos, julienfalque) +* bug #3528 MethodChainingIndentationFixer - nested params bugfix (Slamdunk) +* bug #3547 MultilineWhitespaceBeforeSemicolonsFixer - chained call for a return fix (egircys, keradus) +* bug #3597 DeclareStrictTypesFixer - fix bug of removing line (kubawerlos, keradus) +* bug #3605 DoctrineAnnotationIndentationFixer - Fix indentation with mixed lines (julienfalque) +* bug #3606 PhpdocToCommentFixer - allow multiple ( (SpacePossum) +* bug #3614 Refactor PhpdocToCommentFixer - extract checking to CommentsAnalyzer (kubawerlos) +* bug #3668 Rewrite NoUnusedImportsFixer (kubawerlos, julienfalque) +* bug #3670 PhpdocTypesOrderFixer - Fix ordering of nested generics (julienfalque) +* bug #3671 ArrayIndentationFixer - Fix indentation in HTML (julienfalque) +* bug #3673 PhpdocScalarFixer - Add "types" option (julienfalque, keradus) +* bug #3674 YodaStyleFixer - Fix variable detection for multidimensional arrays (julienfalque, SpacePossum) +* bug #3684 PhpUnitStrictFixer - Do not fix if not correct # of arguments are used (SpacePossum) +* bug #3708 EscapeImplicitBackslashesFixer - Fix escaping multiple backslashes (julienfalque) +* bug #3715 SingleImportPerStatementFixer - Fix handling whitespace before opening brace (julienfalque) +* bug #3731 PhpdocIndentFixer - crash fix (SpacePossum) +* bug #3755 YodaStyleFixer - handle space between var name and index (SpacePossum) +* bug #3765 Fix binary-prefixed double-quoted strings to single quotes (ntzm) +* bug #3770 Handle binary flags in heredoc_to_nowdoc (ntzm) +* bug #3776 ExplicitStringVariableFixer - handle binary strings (ntzm) +* bug #3777 EscapeImplicitBackslashesFixer - handle binary strings (ntzm) +* bug #3790 ProcessLinter - don't execute external process without timeout! It can freeze! (keradus) +* minor #3188 AppVeyor - add PHP 7.x (keradus, julienfalque) +* minor #3451 Update findPHPUnit functions (BackEndTea, SpacePossum, keradus) +* minor #3548 Make shell scripts POSIX-compatible (EvgenyOrekhov, keradus) +* minor #3568 New Autoreview: Correct option casing (ntzm) +* minor #3578 Add interface for deprecated options (julienfalque, keradus) +* minor #3590 Use XdebugHandler to avoid perormance penalty (AJenbo, keradus) +* minor #3607 PhpdocVarWithoutNameFixer - update sample with @ type (SpacePossum) +* minor #3617 Tests stability patches (Tom Klingenberg, keradus) +* minor #3622 Docs: Update descriptions (localheinz) +* minor #3627 Fix tests execution under phpdbg (keradus) +* minor #3629 ProjectFixerConfigurationTest - test rules are sorted (SpacePossum) +* minor #3639 DX: use benefits of symfony/force-lowest (keradus) +* minor #3641 Update check_trailing_spaces script with upstream (keradus) +* minor #3646 Extract SameStringsConstraint and XmlMatchesXsdConstraint (keradus) +* minor #3647 DX: Add CachingLinter for tests (keradus) +* minor #3649 Update check_trailing_spaces script with upstream (keradus) +* minor #3652 CiIntegrationTest - run tests with POSIX sh, not Bash (keradus) +* minor #3656 DX: Clean ups (SpacePossum) +* minor #3657 update phpunitgoodpractices/traits (SpacePossum, keradus) +* minor #3658 DX: Clean ups (SpacePossum) +* minor #3660 Fix do not rely on order of fixing in CiIntegrationTest (kubawerlos) +* minor #3661 Fix: covers annotation for NoAlternativeSyntaxFixerTest (kubawerlos) +* minor #3662 DX: Add Smoke/InstallViaComposerTest (keradus) +* minor #3663 DX: During deployment, run all smoke tests and don't allow to skip phar-related ones (keradus) +* minor #3665 CircleCI fix (kubawerlos) +* minor #3666 Use "set -eu" in shell scripts (EvgenyOrekhov) +* minor #3669 Document possible values for subset options (julienfalque, keradus) +* minor #3672 Remove SameStringsConstraint and XmlMatchesXsdConstraint (keradus) +* minor #3676 RunnerTest - workaround for failing Symfony v2.8.37 (kubawerlos) +* minor #3680 DX: Tokens - removeLeadingWhitespace and removeTrailingWhitespace must act in same way (SpacePossum) +* minor #3686 README.rst - Format all code-like strings in fixer descriptions (ntzm, keradus) +* minor #3692 DX: Optimize tests (julienfalque) +* minor #3700 README.rst - Format all code-like strings in fixer description (ntzm) +* minor #3701 Use correct casing for "PHPDoc" (ntzm) +* minor #3703 DX: InstallViaComposerTest - groom naming (keradus) +* minor #3704 DX: Tokens - fix naming (keradus) +* minor #3706 Update homebrew installation instructions (ntzm) +* minor #3713 Use HTTPS whenever possible (fabpot) +* minor #3723 Extend tests coverage (ntzm) +* minor #3733 Disable Composer optimized autoloader by default (julienfalque) +* minor #3748 PhpUnitStrictFixer - extend risky note (jnvsor) +* minor #3749 Make sure PHPUnit is cased correctly in fixers descriptions (kubawerlos) +* minor #3768 Improve deprecation messages (julienfalque, SpacePossum) +* minor #3773 AbstractFixerWithAliasedOptionsTestCase - don't export (keradus) +* minor #3775 Add tests for binary strings in string_line_ending (ntzm) +* minor #3779 Misc fixes (ntzm, keradus) +* minor #3796 DX: StdinTest - do not assume name of folder, into which project was cloned (keradus) +* minor #3803 NoEmptyPhpdocFixer/PhpdocAddMissingParamAnnotationFixer - missing priority test (SpacePossum, keradus) +* minor #3804 Cleanup: remove useless constructor comment (kubawerlos) +* minor #3805 Cleanup: add missing @param type (kubawerlos, keradus) + +Changelog for v2.11.1 +--------------------- + +* bug #3626 ArrayIndentationFixer: priority bug with BinaryOperatorSpacesFixer and MethodChainingIndentationFixer (Slamdunk) +* bug #3632 DateTimeImmutableFixer bug with adding tokens while iterating over them (kubawerlos) +* minor #3478 PhpUnitDedicateAssertFixer: handle static calls (Slamdunk) +* minor #3618 DateTimeImmutableFixer - grooming (keradus) + +Changelog for v2.11.0 +--------------------- + +* feature #3135 Add ArrayIndentationFixer (julienfalque) +* feature #3235 Implement StandardizeIncrementFixer (ntzm, SpacePossum) +* feature #3260 Add DateTimeImmutableFixer (kubawerlos) +* feature #3276 Transform Fully Qualified parameters and return types to short version (veewee, keradus) +* feature #3299 SingleQuoteFixer - fix single quote char (Slamdunk) +* feature #3340 Verbose LintingException after fixing (Slamdunk) +* feature #3423 FunctionToConstantFixer - add fix "get_called_class" option (SpacePossum) +* feature #3434 Add PhpUnitSetUpTearDownVisibilityFixer (BackEndTea, SpacePossum) +* feature #3442 Add CommentToPhpdocFixer (kubawerlos, keradus) +* feature #3448 OrderedClassElementsFixer - added sortAlgorithm option (meridius) +* feature #3454 Add StringLineEndingFixer (iluuu1994, SpacePossum, keradus, julienfalque) +* feature #3477 PhpUnitStrictFixer: handle static calls (Slamdunk) +* feature #3479 PhpUnitConstructFixer: handle static calls (Slamdunk) +* feature #3507 Add PhpUnitOrderedCoversFixer (Slamdunk) +* feature #3545 Add the 'none' sort algorithm to OrderedImportsFixer (EvgenyOrekhov) +* feature #3588 Add NoAlternativeSyntaxFixer (eddmash, keradus) +* minor #3414 DescribeCommand: add fixer class when verbose (Slamdunk) +* minor #3432 ConfigurationDefinitionFixerInterface - fix deprecation notice (keradus) +* minor #3527 Deprecate last param of Tokens::findBlockEnd (ntzm, keradus) +* minor #3539 Update UnifiedDiffOutputBuilder from gecko-packages/gecko-diff-output-builder usage after it was incorporated into sebastian/diff (keradus) +* minor #3549 DescribeCommand - use our Differ wrapper class, not external one directly (keradus) +* minor #3592 Support PHPUnit 7 (keradus) +* minor #3619 Travis - extend additional files list (keradus) + +Changelog for v2.10.5 +--------------------- + +* bug #3344 Fix method chaining indentation in HTML (julienfalque) +* bug #3594 ElseifFixer - Bug with alternative syntax (kubawerlos) +* bug #3600 StrictParamFixer - Fix issue when functions are imported (ntzm, keradus) +* minor #3589 FixerFactoryTest - add missing test (SpacePossum, keradus) +* minor #3610 make phar extension optional (Tom Klingenberg, keradus) +* minor #3612 Travis - allow for hhvm failures (keradus) +* minor #3615 Detect fabbot.io (julienfalque, keradus) +* minor #3616 FixerFactoryTest - Don't rely on autovivification (keradus) +* minor #3621 FixerFactoryTest - apply CS (keradus) + +Changelog for v2.10.4 +--------------------- + +* bug #3446 Add PregWrapper (kubawerlos) +* bug #3464 IncludeFixer - fix incorrect order of fixing (kubawerlos, SpacePossum) +* bug #3496 Bug in Tokens::removeLeadingWhitespace (kubawerlos, SpacePossum, keradus) +* bug #3557 AbstractDoctrineAnnotationFixer: edge case bugfix (Slamdunk) +* bug #3574 GeneralPhpdocAnnotationRemoveFixer - remove PHPDoc if no content is left (SpacePossum) +* minor #3563 DX add missing covers annotations (keradus) +* minor #3564 Use ::class keyword when possible (keradus) +* minor #3565 Use EventDispatcherInterface instead of EventDispatcher when possible (keradus) +* minor #3566 Update PHPUnitGoodPractices\Traits (keradus) +* minor #3572 DX: allow for more phpunit-speedtrap versions to support more PHPUnit versions (keradus) +* minor #3576 Fix Doctrine Annotation test cases merging (julienfalque) +* minor #3577 DoctrineAnnotationArrayAssignmentFixer - Add test case (julienfalque) + +Changelog for v2.10.3 +--------------------- + +* bug #3504 NoBlankLinesAfterPhpdocFixer - allow blank line before declare statement (julienfalque) +* bug #3522 Remove LOCK_EX (SpacePossum) +* bug #3560 SelfAccessorFixer is risky (Slamdunk) +* minor #3435 Add tests for general_phpdoc_annotation_remove (BackEndTea) +* minor #3484 Create Tokens::findBlockStart (ntzm) +* minor #3512 Add missing array typehints (ntzm) +* minor #3513 Making AppVeyor happy (kubawerlos) +* minor #3516 Use null|type instead of ?type in PHPDocs (ntzm) +* minor #3518 FixerFactoryTest - Test each priority test file is listed as test (SpacePossum) +* minor #3519 Fix typo (SpacePossum) +* minor #3520 Fix typos: ran vs. run (SpacePossum) +* minor #3521 Use HTTPS (carusogabriel) +* minor #3526 Remove gecko dependency (SpacePossum, keradus, julienfalque) +* minor #3531 Backport PHPMD to LTS version to ease maintainability (keradus) +* minor #3532 Implement Tokens::findOppositeBlockEdge (ntzm) +* minor #3533 DX: SCA - drop src/Resources exclusion (keradus) +* minor #3538 Don't use third parameter of Tokens::findBlockStart (ntzm) +* minor #3542 Enhancement: Run composer-normalize on Travis CI (localheinz, keradus) +* minor #3550 AutoReview\FixerFactoryTest - fix missing priority test, mark not fully valid test as incomplete (keradus) +* minor #3555 DX: composer.json - drop branch-alias, branch is already following the version (keradus) +* minor #3556 DX: Add AutoReview/ComposerTest (keradus) +* minor #3559 Don't expose new files under Test namespace (keradus) +* minor #3561 PHPUnit5 - add in place missing compat layer for PHPUnit6 (keradus) + +Changelog for v2.10.2 +--------------------- + +* bug #3502 Fix missing file in export (keradus) + +Changelog for v2.10.1 +--------------------- + +* bug #3265 YodaFixer - fix problems of block statements followed by ternary statements (weareoutman, keradus, SpacePossum) +* bug #3367 NoUnusedImportsFixer - fix comment handling (SpacePossum, keradus) +* bug #3438 PhpUnitTestAnnotationFixer: Do not prepend with test if method is test() (localheinz, SpacePossum) +* bug #3455 NoEmptyCommentFixer - comment block detection for line ending different than LF (kubawerlos, SpacePossum) +* bug #3458 SilencedDeprecationErrorFixer - fix edge cases (kubawerlos) +* bug #3466 no_whitespace_in_blank_line and no_blank_lines_after_phpdoc fixers bug (kubawerlos, keradus) +* bug #3472 YodaStyleFixer - do not un-Yoda if right side is assignment (SpacePossum, keradus) +* bug #3492 PhpdocScalarFixer - Add callback pesudo-type to callable type (carusogabriel) +* minor #3354 Added missing types to the PhpdocTypesFixer (GrahamCampbell) +* minor #3406 Fix for escaping in README (kubawerlos) +* minor #3430 Fix integration test (SpacePossum) +* minor #3431 Add missing tests (SpacePossum) +* minor #3440 Add a handful of integration tests (BackEndTea) +* minor #3443 ConfigurableFixerInterface - not deprecated but TODO (SpacePossum) +* minor #3444 IntegrationTest - ensure tests in priority dir are priority tests indeed (keradus) +* minor #3494 Add missing PHPDoc param type (ntzm) +* minor #3495 Swap @var type and element (ntzm) +* minor #3498 NoUnusedImportsFixer - fix deprecation (keradus) + +Changelog for v2.10.0 +--------------------- + +* feature #3290 Add PhpdocOpeningClosingFixer (Slamdunk, keradus) +* feature #3327 Add MultilineWhitespaceBeforeSemicolonsFixer (egircys, keradus) +* feature #3351 PhuUnit: migrate getMock to createPartialMock when arguments count is 2 (Slamdunk) +* feature #3362 Add BacktickToShellExecFixer (Slamdunk) +* minor #3285 PHPUnit - use protective traits (keradus) +* minor #3329 ConfigurationResolver - detect deprecated fixers (keradus, SpacePossum) +* minor #3343 Tokens - improve block end lookup (keradus) +* minor #3360 Adjust Symfony ruleset (keradus) +* minor #3361 no_extra_consecutive_blank_lines - rename to no_extra_blank_lines (with BC layer) (keradus) +* minor #3363 progress-type - name main option value 'dots' (keradus) +* minor #3404 Deprecate "use_yoda_style" in IsNullFixer (kubawerlos, keradus) +* minor #3418 ConfigurableFixerInterface, ConfigurationDefinitionFixerInterface - update deprecations (keradus) +* minor #3419 Dont use deprecated fixer in itest (keradus) + +Changelog for v2.9.3 +-------------------- + +* bug #3502 Fix missing file in export (keradus) + +Changelog for v2.9.2 +-------------------- + +* bug #3265 YodaFixer - fix problems of block statements followed by ternary statements (weareoutman, keradus, SpacePossum) +* bug #3367 NoUnusedImportsFixer - fix comment handling (SpacePossum, keradus) +* bug #3438 PhpUnitTestAnnotationFixer: Do not prepend with test if method is test() (localheinz, SpacePossum) +* bug #3455 NoEmptyCommentFixer - comment block detection for line ending different than LF (kubawerlos, SpacePossum) +* bug #3458 SilencedDeprecationErrorFixer - fix edge cases (kubawerlos) +* bug #3466 no_whitespace_in_blank_line and no_blank_lines_after_phpdoc fixers bug (kubawerlos, keradus) +* bug #3472 YodaStyleFixer - do not un-Yoda if right side is assignment (SpacePossum, keradus) +* minor #3354 Added missing types to the PhpdocTypesFixer (GrahamCampbell) +* minor #3406 Fix for escaping in README (kubawerlos) +* minor #3430 Fix integration test (SpacePossum) +* minor #3431 Add missing tests (SpacePossum) +* minor #3440 Add a handful of integration tests (BackEndTea) +* minor #3444 IntegrationTest - ensure tests in priority dir are priority tests indeed (keradus) +* minor #3494 Add missing PHPDoc param type (ntzm) +* minor #3495 Swap @var type and element (ntzm) +* minor #3498 NoUnusedImportsFixer - fix deprecation (keradus) + +Changelog for v2.9.1 +-------------------- + +* bug #3298 DiffConsoleFormatter - fix output escaping. (SpacePossum) +* bug #3312 PhpUnitTestAnnotationFixer: Only remove prefix if it really is a prefix (localheinz) +* bug #3318 SingleLineCommentStyleFixer - fix closing tag inside comment causes an error (kubawerlos) +* bug #3334 ExplicitStringVariableFixer: handle parsed array and object (Slamdunk) +* bug #3337 BracesFixer: nowdoc bug on template files (Slamdunk) +* bug #3349 Fix stdin handling and add tests for it (keradus) +* bug #3350 PhpUnitNoExpectationAnnotationFixer - fix handling of multiline expectedExceptionMessage annotation (Slamdunk) +* bug #3352 FunctionToConstantFixer - bugfix for get_class with leading backslash (kubawerlos) +* bug #3359 BracesFixer - handle comment for content outside of given block (keradus) +* bug #3371 IsNullFixer must be run before YodaStyleFixer (kubawerlos) +* bug #3373 PhpdocAlignFixer - Fix removing of everything after @ when there is a space after the @ (ntzm) +* bug #3415 FileFilterIterator - input checks and utests (SpacePossum, keradus) +* bug #3420 SingleLineCommentStyleFixer - fix 'strpos() expects parameter 1 to be string, boolean given' (keradus, SpacePossum) +* bug #3428 Fix archive analysing (keradus) +* bug #3429 Fix archive analysing (keradus) +* minor #3137 PHPUnit - use common base class (keradus) +* minor #3311 FinalInternalClassFixer - fix typo (localheinz) +* minor #3328 Remove duplicated space in exceptions (keradus) +* minor #3342 PhpUnitDedicateAssertFixer - Remove unexistent method is_boolean (carusogabriel) +* minor #3345 StdinFileInfo - fix __toString (keradus) +* minor #3346 StdinFileInfo - drop getContents (keradus) +* minor #3347 DX: reapply newest CS (keradus) +* minor #3365 COOKBOOK-FIXERS.md - update to provide definition instead of description (keradus) +* minor #3370 AbstractFixer - FQCN in in exceptions (Slamdunk) +* minor #3372 ProjectCodeTest - fix comment (keradus) +* minor #3393 Method call typos (Slamdunk, keradus) +* minor #3402 Always provide delimiter to `preg_quote` calls (ntzm) +* minor #3403 Remove unused import (ntzm) +* minor #3405 Fix `fopen` mode (ntzm) +* minor #3407 CombineConsecutiveIssetsFixer - Improve description (kubawerlos) +* minor #3408 Improving fixers descriptions (kubawerlos) +* minor #3409 move itests from misc to priority (keradus) +* minor #3411 Better type hinting for AbstractFixerTestCase::$fixer (kubawerlos) +* minor #3412 Convert `strtolower` inside `strpos` to just `stripos` (ntzm) +* minor #3421 DX: Use ::class (keradus) +* minor #3424 AbstractFixerTest: fix expectException arguments (Slamdunk, keradus) +* minor #3425 FixerFactoryTest - test that priority pair fixers have itest (keradus, SpacePossum) +* minor #3427 ConfigurationResolver: fix @return annotation (Slamdunk) + +Changelog for v2.9.0 +-------------------- + +* feature #3063 Method chaining indentation fixer (boliev, julienfalque) +* feature #3076 Add ExplicitStringVariableFixer (Slamdunk, keradus) +* feature #3098 MethodSeparationFixer - add class elements separation options (SpacePossum, keradus) +* feature #3155 Add EscapeImplicitBackslashesFixer (Slamdunk) +* feature #3164 Add ExplicitIndirectVariableFixer (Slamdunk, keradus) +* feature #3183 FinalInternalClassFixer introduction (keradus, SpacePossum) +* feature #3187 StaticLambdaFixer - introduction (SpacePossum, keradus) +* feature #3209 PhpdocAlignFixer - Make @method alignable (ntzm) +* feature #3275 Add PhpUnitTestAnnotationFixer (BackEndTea, keradus) + +Changelog for v2.8.4 +-------------------- + +* bug #3281 SelfAccessorFixer - stop modifying traits (kubawerlos) +* minor #3195 Add self-update command test (julienfalque) +* minor #3287 FileCacheManagerTest - drop duplicated line (keradus) +* minor #3292 PHPUnit - set memory limit (veewee) +* minor #3306 Token - better input validation (keradus) +* minor #3310 Upgrade PHP Coveralls (keradus) + +Changelog for v2.8.3 +-------------------- + +* bug #3173 SimplifiedNullReturnFixer - handle nullable return types (Slamdunk) +* bug #3268 PhpUnitNoExpectationAnnotationFixer - add case with backslashes (keradus, Slamdunk) +* bug #3272 PhpdocTrimFixer - unicode support (SpacePossum) + +Changelog for v2.8.2 +-------------------- + +* bug #3225 PhpdocTrimFixer - Fix handling of lines without leading asterisk (julienfalque) +* bug #3241 NoExtraConsecutiveBlankLinesFixer - do not crash on ^M LF only (SpacePossum) +* bug #3242 PhpUnitNoExpectationAnnotationFixer - fix ' handling (keradus) +* bug #3243 PhpUnitExpectationFixer - don't create ->expectExceptionMessage(null) (keradus) +* bug #3244 PhpUnitNoExpectationAnnotationFixer - expectation extracted from annotation shall be separated from rest of code with one blank line (keradus) +* bug #3259 PhpUnitNamespacedFixer - fix isCandidate to not rely on class declaration (keradus) +* bug #3261 PhpUnitNamespacedFixer - properly fix next usage of already fixed class (keradus) +* bug #3262 ToolInfo - support installation by branch as well (keradus) +* bug #3263 NoBreakCommentFixer - Fix handling comment text with PCRE characters (julienfalque) +* bug #3266 PhpUnitConstructFixer - multiple asserts bug (kubawerlos) +* minor #3239 Improve contributing guide and issue template (julienfalque) +* minor #3246 Make ToolInfo methods non-static (julienfalque) +* minor #3249 PhpUnitNoExpectationAnnotationFixerTest - fix hidden conflict (keradus) +* minor #3250 Travis: fail early, spare resources, save the Earth (Slamdunk, keradus) +* minor #3251 Create Title for config file docs section (IanEdington) +* minor #3254 AutoReview/FixerFactoryTest::testFixersPriority: verbose assertion message (Slamdunk) +* minor #3255 IntegrationTest: output exception stack trace (Slamdunk) +* minor #3257 README.rst - Fixed bullet list formatting (moebrowne) + +Changelog for v2.8.1 +-------------------- + +* bug #3199 TokensAnalyzer - getClassyElements (SpacePossum) +* bug #3208 BracesFixer - Fix for instantiation in control structures (julienfalque, SpacePossum) +* bug #3215 BinaryOperatorSpacesFixer - Fix spaces around multiple exception catching (|) (ntzm) +* bug #3216 AbstractLinesBeforeNamespaceFixer - add min. and max. option, not only single target count (SpacePossum) +* bug #3217 TokenizerLinter - fix lack of linting when code is cached (SpacePossum, keradus) +* minor #3200 Skip slow test when Xdebug is loaded (julienfalque) +* minor #3211 Use udiff format in CI (julienfalque) +* minor #3212 Handle rulesets unknown to fabbot.io (julienfalque) +* minor #3219 Normalise references to GitHub in docs (ntzm) +* minor #3226 Remove unused imports (ntzm) +* minor #3231 Fix typos (ntzm) +* minor #3234 Simplify Cache\Signature::equals (ntzm) +* minor #3237 UnconfigurableFixer - use only LF (keradus) +* minor #3238 AbstractFixerTest - fix @cover annotation (keradus) + +Changelog for v2.8.0 +-------------------- + +* feature #3065 Add IncrementStyleFixer (kubawerlos) +* feature #3119 Feature checkstyle reporter (K-Phoen) +* feature #3162 Add udiff as diff format (SpacePossum, keradus) +* feature #3170 Add CompactNullableTypehintFixer (jfcherng) +* feature #3189 Add PHP_CS_FIXER_FUTURE_MODE env (keradus) +* feature #3201 Add PHPUnit Migration rulesets and fixers (keradus) +* minor #3149 AbstractProxyFixer - Support multiple proxied fixers (julienfalque) +* minor #3160 Add DeprecatedFixerInterface (kubawerlos) +* minor #3185 IndentationTypeFixerTest - clean up (SpacePossum, keradus) +* minor #3198 Cleanup: add test that there is no deprecated fixer in rule set (kubawerlos) + +Changelog for v2.7.5 +-------------------- + +* bug #3225 PhpdocTrimFixer - Fix handling of lines without leading asterisk (julienfalque) +* bug #3241 NoExtraConsecutiveBlankLinesFixer - do not crash on ^M LF only (SpacePossum) +* bug #3262 ToolInfo - support installation by branch as well (keradus) +* bug #3263 NoBreakCommentFixer - Fix handling comment text with PCRE characters (julienfalque) +* bug #3266 PhpUnitConstructFixer - multiple asserts bug (kubawerlos) +* minor #3239 Improve contributing guide and issue template (julienfalque) +* minor #3246 Make ToolInfo methods non-static (julienfalque) +* minor #3250 Travis: fail early, spare resources, save the Earth (Slamdunk, keradus) +* minor #3251 Create Title for config file docs section (IanEdington) +* minor #3254 AutoReview/FixerFactoryTest::testFixersPriority: verbose assertion message (Slamdunk) +* minor #3255 IntegrationTest: output exception stack trace (Slamdunk) + +Changelog for v2.7.4 +-------------------- + +* bug #3199 TokensAnalyzer - getClassyElements (SpacePossum) +* bug #3208 BracesFixer - Fix for instantiation in control structures (julienfalque, SpacePossum) +* bug #3215 BinaryOperatorSpacesFixer - Fix spaces around multiple exception catching (|) (ntzm) +* bug #3216 AbstractLinesBeforeNamespaceFixer - add min. and max. option, not only single target count (SpacePossum) +* bug #3217 TokenizerLinter - fix lack of linting when code is cached (SpacePossum, keradus) +* minor #3200 Skip slow test when Xdebug is loaded (julienfalque) +* minor #3219 Normalise references to GitHub in docs (ntzm) +* minor #3226 Remove unused imports (ntzm) +* minor #3231 Fix typos (ntzm) +* minor #3234 Simplify Cache\Signature::equals (ntzm) +* minor #3237 UnconfigurableFixer - use only LF (keradus) +* minor #3238 AbstractFixerTest - fix @cover annotation (keradus) + +Changelog for v2.7.3 +-------------------- + +* bug #3114 SelfAccessorFixer - Fix type declarations replacement (julienfalque) + +Changelog for v2.7.2 +-------------------- + +* bug #3062 BraceClassInstantiationTransformer - Fix instantiation inside method call braces case (julienfalque, keradus) +* bug #3083 SingleBlankLineBeforeNamespaceFixer - Fix handling namespace right after opening tag (mlocati) +* bug #3109 SwitchCaseSemicolonToColonFixer - Fix bug with nested constructs (SpacePossum) +* bug #3117 Multibyte character in array key makes alignment incorrect (kubawerlos) +* bug #3123 Cache - File permissions (SpacePossum) +* bug #3138 NoHomoglyphNamesFixer - fix crash on non-ascii but not mapped either (SpacePossum) +* bug #3172 IndentationTypeFixer - do not touch whitespace that is not indentation (SpacePossum) +* bug #3176 NoMultilineWhitespaceBeforeSemicolonsFixer - SpaceAfterSemicolonFixer - priority fix (SpacePossum) +* bug #3193 TokensAnalyzer::getClassyElements - sort result before returning (SpacePossum) +* bug #3196 SelfUpdateCommand - fix exit status when can't determine newest version (julienfalque) +* minor #3107 ConfigurationResolver - improve error message when rule is not found (SpacePossum) +* minor #3113 Add WordMatcher (keradus) +* minor #3128 README: remove deprecated rule from CLI examples (chteuchteu) +* minor #3133 Unify Reporter tests (keradus) +* minor #3134 Allow Symfony 4 (keradus, garak) +* minor #3136 PHPUnit - call hooks from parent class as well (keradus) +* minor #3141 Unify description of deprecated fixer (kubawerlos) +* minor #3144 PhpUnitDedicateAssertFixer - Sort map and array by function name (localheinz) +* minor #3145 misc - Typo (localheinz) +* minor #3150 Fix CircleCI (julienfalque) +* minor #3151 Update gitattributes to ignore next file (keradus) +* minor #3156 Update php-coveralls (keradus) +* minor #3166 README - add link to new gitter channel. (SpacePossum) +* minor #3174 Update UPGRADE.md (vitek-rostislav) +* minor #3180 Fix usage of static variables (kubawerlos) +* minor #3182 Add support for PHPUnit 6, drop PHPUnit 4 (keradus) +* minor #3184 Code grooming - sort content of arrays (keradus) +* minor #3191 Travis - add nightly build to allow_failures due to Travis issues (keradus) +* minor #3197 DX groom CS (keradus) + +Changelog for v2.7.1 +-------------------- + +* bug #3115 NoUnneededFinalMethodFixer - fix edge case (Slamdunk) + +Changelog for v2.7.0 +-------------------- + +* feature #2573 BinaryOperatorSpaces reworked (SpacePossum, keradus) +* feature #3073 SpaceAfterSemicolonFixer - Add option to remove space in empty for expressions (julienfalque) +* feature #3089 NoAliasFunctionsFixer - add imap aliases (Slamdunk) +* feature #3093 NoUnneededFinalMethodFixer - Remove final keyword from private methods (localheinz, keradus) +* minor #3068 Symfony:risky ruleset - add no_homoglyph_names (keradus) +* minor #3074 [IO] Replace Diff with fork version (SpacePossum) + +Changelog for v2.6.1 +-------------------- + +* bug #3052 Fix false positive warning about paths overridden by provided as command arguments (kubawerlos) +* bug #3053 CombineConsecutiveIssetsFixer - fix priority (SpacePossum) +* bug #3058 IsNullFixer - fix whitespace handling (roukmoute) +* bug #3069 MethodArgumentSpaceFixer - new test case (keradus) +* bug #3072 IsNullFixer - fix non_yoda_style edge case (keradus) +* bug #3088 Drop dedicated Phar stub (keradus) +* bug #3100 NativeFunctionInvocationFixer - Fix test if previous token is already namespace separator (SpacePossum) +* bug #3104 DoctrineAnnotationIndentationFixer - Fix str_repeat() error (julienfalque) +* minor #3038 Support PHP 7.2 (SpacePossum, keradus) +* minor #3064 Fix couple of typos (KKSzymanowski) +* minor #3070 YodaStyleFixer - Clarify configuration parameters (SteveJobzniak) +* minor #3078 ConfigurationResolver - hide context while including config file (keradus) +* minor #3080 Direct function call instead of by string (kubawerlos) +* minor #3085 CiIntegrationTest - skip when no git is available (keradus) +* minor #3087 phar-stub.php - allow PHP 7.2 (keradus) +* minor #3092 .travis.yml - fix matrix for PHP 7.1 (keradus) +* minor #3094 NoUnneededFinalMethodFixer - Add test cases (julienfalque) +* minor #3111 DoctrineAnnotationIndentationFixer - Restore test case (julienfalque) + +Changelog for v2.6.0 +-------------------- + +* bug #3039 YodaStyleFixer - Fix echo case (SpacePossum, keradus) +* feature #2446 Add YodaStyleFixer (SpacePossum) +* feature #2940 Add NoHomoglyphNamesFixer (mcfedr, keradus) +* feature #3012 Add CombineConsecutiveIssetsFixer (SpacePossum) +* minor #3037 Update SF rule set (SpacePossum) + +Changelog for v2.5.1 +-------------------- + +* bug #3002 Bugfix braces (mnabialek) +* bug #3010 Fix handling of Github releases (julienfalque, keradus) +* bug #3015 Fix exception arguments (julienfalque) +* bug #3016 Verify phar file (keradus) +* bug #3021 Risky rules cleanup (kubawerlos) +* bug #3023 RandomApiMigrationFixer - "rand();" to "random_int(0, getrandmax());" fixing (SpacePossum) +* bug #3024 ConfigurationResolver - Handle empty "rules" value (SpacePossum, keradus) +* bug #3031 IndentationTypeFixer - fix handling tabs in indented comments (keradus) +* minor #2999 Notice when paths from config file are overridden by command arguments (julienfalque, keradus) +* minor #3007 Add PHP 7.2 to Travis build matrix (Jean85) +* minor #3009 CiIntegrationTest - run local (SpacePossum) +* minor #3013 Adjust phpunit configuration (localheinz) +* minor #3017 Fix: Risky tests (localheinz) +* minor #3018 Fix: Make sure that data providers are named correctly (localheinz, keradus) +* minor #3032 .php_cs.dist - handling UnexpectedValueException (keradus) +* minor #3033 Use ::class (keradus) +* minor #3034 Follow newest CS (keradus) +* minor #3036 Drop not existing Standalone group from PHPUnit configuration and duplicated internal tags (keradus) +* minor #3042 Update gitter address (keradus) + +Changelog for v2.5.0 +-------------------- + +* feature #2770 DoctrineAnnotationSpaces - split assignments options (julienfalque) +* feature #2843 Add estimating-max progress output type (julienfalque) +* feature #2885 Add NoSuperfluousElseifFixer (julienfalque) +* feature #2929 Add NoUnneededCurlyBracesFixer (SpacePossum) +* feature #2944 FunctionToConstantFixer - handle get_class() -> __CLASS__ as well (SpacePossum) +* feature #2953 BlankLineBeforeStatementFixer - Add more statements (localheinz, keradus) +* feature #2972 Add NoUnneededFinalMethodFixer (Slamdunk, keradus) +* feature #2992 Add Doctrine Annotation ruleset (julienfalque) +* minor #2926 Token::getNameForId (SpacePossum) + +Changelog for v2.4.2 +-------------------- + +* bug #3002 Bugfix braces (mnabialek) +* bug #3010 Fix handling of Github releases (julienfalque, keradus) +* bug #3015 Fix exception arguments (julienfalque) +* bug #3016 Verify phar file (keradus) +* bug #3021 Risky rules cleanup (kubawerlos) +* bug #3023 RandomApiMigrationFixer - "rand();" to "random_int(0, getrandmax());" fixing (SpacePossum) +* bug #3024 ConfigurationResolver - Handle empty "rules" value (SpacePossum, keradus) +* bug #3031 IndentationTypeFixer - fix handling tabs in indented comments (keradus) +* minor #2999 Notice when paths from config file are overridden by command arguments (julienfalque, keradus) +* minor #3007 Add PHP 7.2 to Travis build matrix (Jean85) +* minor #3009 CiIntegrationTest - run local (SpacePossum) +* minor #3013 Adjust phpunit configuration (localheinz) +* minor #3017 Fix: Risky tests (localheinz) +* minor #3018 Fix: Make sure that data providers are named correctly (localheinz, keradus) +* minor #3032 .php_cs.dist - handling UnexpectedValueException (keradus) +* minor #3033 Use ::class (keradus) +* minor #3034 Follow newest CS (keradus) +* minor #3036 Drop not existing Standalone group from PHPUnit configuration and duplicated internal tags (keradus) +* minor #3042 Update gitter address (keradus) + +Changelog for v2.4.1 +-------------------- + +* bug #2925 Improve CI integration suggestion (julienfalque) +* bug #2928 TokensAnalyzer::getClassyElements - Anonymous class support (SpacePossum) +* bug #2931 Psr0Fixer, Psr4Fixer - ignore "new class" syntax (dg, keradus) +* bug #2934 Config - fix handling rule without value (keradus, SpacePossum) +* bug #2939 NoUnusedImportsFixer - Fix extra blank line (julienfalque) +* bug #2941 PHP 7.2 - Group imports with trailing comma support (SpacePossum, julienfalque) +* bug #2954 NoBreakCommentFixer - Disable case sensitivity (julienfalque) +* bug #2959 MethodArgumentSpaceFixer - Skip body of fixed function (greg0ire) +* bug #2984 AlignMultilineCommentFixer - handle uni code (SpacePossum) +* bug #2987 Fix incorrect indentation of comments in `braces` fixer (rob006) +* minor #2924 Add missing Token deprecations (julienfalque) +* minor #2927 WhiteSpaceConfig - update message copy and more strict tests (SpacePossum, keradus) +* minor #2930 Trigger website build (keradus) +* minor #2932 Integrate CircleCI (keradus, aidantwoods) +* minor #2933 ProcessLinterTest - Ensure Windows test only runs on Windows, add a Mac test execution (aidantwoods) +* minor #2935 special handling of fabbot.io service if it's using too old PHP CS Fixer version (keradus) +* minor #2937 Travis: execute 5.3 job on precise (keradus) +* minor #2938 Tests fix configuration of project (SpacePossum, keradus) +* minor #2943 FunctionToConstantFixer - test with diff. arguments than fixable (SpacePossum) +* minor #2945 BlankLineBeforeStatementFixerTest - Fix covered class (julienfalque) +* minor #2946 Detect extra old installations (keradus) +* minor #2947 Test suggested CI integration (keradus) +* minor #2951 AccessibleObject - remove most of usage (keradus) +* minor #2952 BlankLineBeforeStatementFixer - Reference fixer instead of test class (localheinz) +* minor #2955 Travis - stop using old TASK_SCA residue (keradus) +* minor #2968 AssertTokensTrait - don't use AccessibleObject (keradus) +* minor #2969 Shrink down AccessibleObject usage (keradus) +* minor #2982 TrailingCommaInMultilineArrayFixer - simplify isMultilineArray condition (TomasVotruba) +* minor #2989 CiIntegrationTest - fix min supported PHP versions (keradus) + +Changelog for v2.4.0 +-------------------- + +* bug #2880 NoBreakCommentFixer - fix edge case (julienfalque) +* bug #2900 VoidReturnFixer - handle functions containing anonymous functions/classes (bendavies, keradus) +* bug #2902 Fix test classes constructor (julienfalque) +* feature #2384 Add BlankLineBeforeStatementFixer (localheinz, keradus, SpacePossum) +* feature #2440 MethodArgumentSpaceFixer - add ensure_fully_multiline option (greg0ire) +* feature #2649 PhpdocAlignFixer - make fixer configurable (ntzm) +* feature #2664 Add DoctrineAnnotationArrayAssignmentFixer (julienfalque) +* feature #2667 Add NoBreakCommentFixer (julienfalque) +* feature #2684 BracesFixer - new options for braces position after control structures and anonymous constructs (aidantwoods, keradus) +* feature #2701 NoExtraConsecutiveBlankLinesFixer - Add more configuration options related to switch statements (SpacePossum) +* feature #2740 Add VoidReturnFixer (mrmark) +* feature #2765 DoctrineAnnotationIndentationFixer - add option to indent mixed lines (julienfalque) +* feature #2815 NonPrintableCharacterFixer - Add option to replace with escape sequences (julienfalque, keradus) +* feature #2822 Add NoNullPropertyInitializationFixer (ntzm, julienfalque, SpacePossum) +* feature #2825 Add PhpdocTypesOrderFixer (julienfalque, keradus) +* feature #2856 CastSpacesFixer - add space option (kubawerlos, keradus) +* feature #2857 Add AlignMultilineCommentFixer (Slamdunk, keradus) +* feature #2866 Add SingleLineCommentStyleFixer, deprecate HashToSlashCommentFixer (Slamdunk, keradus) +* minor #2773 Travis - use stages (keradus) +* minor #2794 Drop HHVM support (keradus, julienfalque) +* minor #2801 ProjectCodeTest - Fix typo in deprecation message (SpacePossum) +* minor #2818 Token become immutable, performance optimizations (keradus) +* minor #2877 Fix PHPMD report (julienfalque) +* minor #2894 NonPrintableCharacterFixer - fix handling required PHP version on PHPUnit 4.x (keradus) +* minor #2921 InvalidForEnvFixerConfigurationException - fix handling in tests on 2.4 line (keradus) + +Changelog for v2.3.3 +-------------------- + +* bug #2807 NoUselessElseFixer - Fix detection of conditional block (SpacePossum) +* bug #2809 Phar release - fix readme generation (SpacePossum, keradus) +* bug #2827 MethodArgumentSpaceFixer - Always remove trailing spaces (julienfalque) +* bug #2835 SelfAccessorFixer - class property fix (mnabialek) +* bug #2848 PhpdocIndentFixer - fix edge case with inline phpdoc (keradus) +* bug #2849 BracesFixer - Fix indentation issues with comments (julienfalque) +* bug #2851 Tokens - ensureWhitespaceAtIndex (GrahamCampbell, SpacePossum) +* bug #2854 NoLeadingImportSlashFixer - Removing leading slash from import even when in global space (kubawerlos) +* bug #2858 Support generic types (keradus) +* bug #2869 Fix handling required configuration (keradus) +* bug #2881 NoUnusedImportsFixer - Bug when trying to insert empty token (GrahamCampbell, keradus) +* bug #2882 DocBlock\Annotation - Fix parsing of collections with multiple key types (julienfalque) +* bug #2886 NoSpacesInsideParenthesisFixer - Do not remove whitespace if next token is comment (SpacePossum) +* bug #2888 SingleImportPerStatementFixer - Add support for function and const (SpacePossum) +* bug #2901 Add missing files to archive files (keradus) +* bug #2914 HeredocToNowdocFixer - works with CRLF line ending (dg) +* bug #2920 RuleSet - Update deprecated configuration of fixers (SpacePossum, keradus) +* minor #1531 Update docs for few generic types (keradus) +* minor #2793 COOKBOOK-FIXERS.md - update to current version, fix links (keradus) +* minor #2812 ProcessLinter - compatibility with Symfony 3.3 (keradus) +* minor #2816 Tokenizer - better docs and validation (keradus) +* minor #2817 Tokenizer - use future-compatible interface (keradus) +* minor #2819 Fix benchmark (keradus) +* minor #2820 MagicConstantCasingFixer - Remove defined check (SpacePossum) +* minor #2823 Tokenizer - use future-compatible interface (keradus) +* minor #2824 code grooming (keradus) +* minor #2826 Exceptions - provide utests (localheinz) +* minor #2828 Enhancement: Reference phpunit.xsd from phpunit.xml.dist (localheinz) +* minor #2830 Differs - add tests (localheinz) +* minor #2832 Fix: Use all the columns (localheinz) +* minor #2833 Doctrine\Annotation\Token - provide utests (localheinz) +* minor #2839 Use PHP 7.2 polyfill instead of xml one (keradus) +* minor #2842 Move null to first position in PHPDoc types (julienfalque) +* minor #2850 ReadmeCommandTest - Prevent diff output (julienfalque) +* minor #2859 Fixed typo and dead code removal (GrahamCampbell) +* minor #2863 FileSpecificCodeSample - add tests (localheinz) +* minor #2864 WhitespacesAwareFixerInterface clean up (Slamdunk) +* minor #2865 AutoReview\FixerTest - test configuration samples (SpacePossum, keradus) +* minor #2867 VersionSpecification - Fix copy-paste typo (SpacePossum) +* minor #2870 Tokens - ensureWhitespaceAtIndex - Clear tokens before compare. (SpacePossum) +* minor #2874 LineTest - fix typo (keradus) +* minor #2875 HelpCommand - recursive layout fix (SpacePossum) +* minor #2883 DescribeCommand - Show which sample uses the default configuration (SpacePossum) +* minor #2887 Housekeeping - Strict whitespace checks (SpacePossum) +* minor #2895 ProjectCodeTest - check that classes in no-tests exception exist (keradus) +* minor #2896 Move testing related classes from src to tests (keradus) +* minor #2904 Reapply CS (keradus) +* minor #2910 PhpdocAnnotationWithoutDotFixer - Restrict lowercasing (oschwald) +* minor #2913 Tests - tweaks (SpacePossum, keradus) +* minor #2916 FixerFactory - drop return in sortFixers(), never used (TomasVotruba) + +Changelog for v2.3.2 +-------------------- + +* bug #2682 DoctrineAnnotationIndentationFixer - fix handling nested annotations (edhgoose, julienfalque) +* bug #2700 Fix Doctrine Annotation end detection (julienfalque) +* bug #2715 OrderedImportsFixer - handle indented groups (pilgerone) +* bug #2732 HeaderCommentFixer - fix handling blank lines (s7b4) +* bug #2745 Fix Doctrine Annotation newlines (julienfalque) +* bug #2752 FixCommand - fix typo in warning message (mnapoli) +* bug #2757 GeckoPHPUnit is not dev dependency (keradus) +* bug #2759 Update gitattributes (SpacePossum) +* bug #2763 Fix describe command with PSR-0 fixer (julienfalque) +* bug #2768 Tokens::ensureWhitespaceAtIndex - clean up comment check, add check for T_OPEN (SpacePossum) +* bug #2783 Tokens::ensureWhitespaceAtIndex - Fix handling line endings (SpacePossum) +* minor #2304 DX: use PHPMD (keradus) +* minor #2663 Use colors for keywords in commands output (julienfalque, keradus) +* minor #2706 Update README (SpacePossum) +* minor #2714 README.rst - fix wrong value in example (mleko) +* minor #2718 Remove old Symfony exception message expectation (julienfalque) +* minor #2721 Update phpstorm article link to a fresh blog post (valeryan) +* minor #2725 Use method chaining for configuration definitions (julienfalque) +* minor #2727 PHPUnit - use speedtrap (keradus) +* minor #2728 SelfUpdateCommand - verify that it's possible to replace current file (keradus) +* minor #2729 DescribeCommand - add decorated output test (julienfalque) +* minor #2731 BracesFixer - properly pass config in utest dataProvider (keradus) +* minor #2738 Upgrade tests to use new, namespaced PHPUnit TestCase class (keradus) +* minor #2742 Code cleanup (GrahamCampbell, keradus) +* minor #2743 Fixing example and description for GeneralPhpdocAnnotationRemoveFixer (kubawerlos) +* minor #2744 AbstractDoctrineAnnotationFixerTestCase - split fixers test cases (julienfalque) +* minor #2755 Fix compatibility with PHPUnit 5.4.x (keradus) +* minor #2758 Readme - improve CI integration guidelines (keradus) +* minor #2769 Psr0Fixer - remove duplicated example (julienfalque) +* minor #2774 AssertTokens Trait (keradus) +* minor #2775 NoExtraConsecutiveBlankLinesFixer - remove duplicate code sample. (SpacePossum) +* minor #2778 AutoReview - watch that code samples are unique (keradus) +* minor #2787 Add warnings about missing dom ext and require json ext (keradus) +* minor #2792 Use composer-require-checker (keradus) +* minor #2796 Update .gitattributes (SpacePossum) +* minor #2797 Update .gitattributes (SpacePossum) +* minor #2800 PhpdocTypesFixerTest - Fix typo in covers annotation (SpacePossum) + +Changelog for v2.3.1 +-------------------- + +Port of v2.2.3. + +* bug #2724 Revert #2554 Add short diff. output format (keradus) + +Changelog for v2.3.0 +-------------------- + +* feature #2450 Add ListSyntaxFixer (SpacePossum) +* feature #2708 Add PhpUnitTestClassRequiresCoversFixer (keradus) +* minor #2568 Require PHP 5.6+ (keradus) +* minor #2672 Bump symfony/* deps (keradus) + +Changelog for v2.2.20 +--------------------- + +* bug #3233 PhpdocAlignFixer - Fix linebreak inconsistency (SpacePossum, keradus) +* bug #3445 Rewrite NoUnusedImportsFixer (kubawerlos, julienfalque) +* bug #3597 DeclareStrictTypesFixer - fix bug of removing line (kubawerlos, keradus) +* bug #3605 DoctrineAnnotationIndentationFixer - Fix indentation with mixed lines (julienfalque) +* bug #3606 PhpdocToCommentFixer - allow multiple ( (SpacePossum) +* bug #3684 PhpUnitStrictFixer - Do not fix if not correct # of arguments are used (SpacePossum) +* bug #3715 SingleImportPerStatementFixer - Fix handling whitespace before opening brace (julienfalque) +* bug #3731 PhpdocIndentFixer - crash fix (SpacePossum) +* bug #3765 Fix binary-prefixed double-quoted strings to single quotes (ntzm) +* bug #3770 Handle binary flags in heredoc_to_nowdoc (ntzm) +* bug #3790 ProcessLinter - don't execute external process without timeout! It can freeze! (keradus) +* minor #3548 Make shell scripts POSIX-compatible (EvgenyOrekhov, keradus) +* minor #3568 New Autoreview: Correct option casing (ntzm) +* minor #3590 Use XdebugHandler to avoid performance penalty (AJenbo, keradus) +* minor #3607 PhpdocVarWithoutNameFixer - update sample with @ type (SpacePossum) +* minor #3617 Tests stability patches (Tom Klingenberg, keradus) +* minor #3627 Fix tests execution under phpdbg (keradus) +* minor #3629 ProjectFixerConfigurationTest - test rules are sorted (SpacePossum) +* minor #3639 DX: use benefits of symfony/force-lowest (keradus) +* minor #3641 Update check_trailing_spaces script with upstream (keradus) +* minor #3646 Extract SameStringsConstraint and XmlMatchesXsdConstraint (keradus) +* minor #3647 DX: Add CachingLinter for tests (keradus) +* minor #3649 Update check_trailing_spaces script with upstream (keradus) +* minor #3652 CiIntegrationTest - run tests with POSIX sh, not Bash (keradus) +* minor #3656 DX: Clean ups (SpacePossum) +* minor #3660 Fix do not rely on order of fixing in CiIntegrationTest (kubawerlos) +* minor #3662 DX: Add Smoke/InstallViaComposerTest (keradus) +* minor #3663 DX: During deployment, run all smoke tests and don't allow to skip phar-related ones (keradus) +* minor #3665 CircleCI fix (kubawerlos) +* minor #3666 Use "set -eu" in shell scripts (EvgenyOrekhov) +* minor #3669 Document possible values for subset options (julienfalque, keradus) +* minor #3676 RunnerTest - workaround for failing Symfony v2.8.37 (kubawerlos) +* minor #3680 DX: Tokens - removeLeadingWhitespace and removeTrailingWhitespace must act in same way (SpacePossum) +* minor #3686 README.rst - Format all code-like strings in fixer descriptions (ntzm, keradus) +* minor #3692 DX: Optimize tests (julienfalque) +* minor #3701 Use correct casing for "PHPDoc" (ntzm) +* minor #3703 DX: InstallViaComposerTets - groom naming (keradus) +* minor #3704 DX: Tokens - fix naming (keradus) +* minor #3706 Update homebrew installation instructions (ntzm) +* minor #3713 Use HTTPS whenever possible (fabpot) +* minor #3723 Extend tests coverage (ntzm) +* minor #3733 Disable Composer optimized autoloader by default (julienfalque) +* minor #3748 PhpUnitStrictFixer - extend risky note (jnvsor) +* minor #3749 Make sure PHPUnit is cased correctly in fixers descriptions (kubawerlos) +* minor #3773 AbstractFixerWithAliasedOptionsTestCase - don't export (keradus) +* minor #3796 DX: StdinTest - do not assume name of folder, into which project was cloned (keradus) +* minor #3803 NoEmptyPhpdocFixer/PhpdocAddMissingParamAnnotationFixer - missing priority test (SpacePossum, keradus) +* minor #3804 Cleanup: remove useless constructor comment (kubawerlos) + +Changelog for v2.2.19 +--------------------- + +* bug #3594 ElseifFixer - Bug with alternative syntax (kubawerlos) +* bug #3600 StrictParamFixer - Fix issue when functions are imported (ntzm, keradus) +* minor #3589 FixerFactoryTest - add missing test (SpacePossum, keradus) +* minor #3610 make phar extension optional (Tom Klingenberg, keradus) +* minor #3612 Travis - allow for hhvm failures (keradus) +* minor #3615 Detect fabbot.io (julienfalque, keradus) +* minor #3616 FixerFactoryTest - Don't rely on autovivification (keradus) + +Changelog for v2.2.18 +--------------------- + +* bug #3446 Add PregWrapper (kubawerlos) +* bug #3464 IncludeFixer - fix incorrect order of fixing (kubawerlos, SpacePossum) +* bug #3496 Bug in Tokens::removeLeadingWhitespace (kubawerlos, SpacePossum, keradus) +* bug #3557 AbstractDoctrineAnnotationFixer: edge case bugfix (Slamdunk) +* bug #3574 GeneralPhpdocAnnotationRemoveFixer - remove PHPDoc if no content is left (SpacePossum) +* minor #3563 DX add missing covers annotations (keradus) +* minor #3565 Use EventDispatcherInterface instead of EventDispatcher when possible (keradus) +* minor #3572 DX: allow for more phpunit-speedtrap versions to support more PHPUnit versions (keradus) +* minor #3576 Fix Doctrine Annotation test cases merging (julienfalque) + +Changelog for v2.2.17 +--------------------- + +* bug #3504 NoBlankLinesAfterPhpdocFixer - allow blank line before declare statement (julienfalque) +* bug #3522 Remove LOCK_EX (SpacePossum) +* bug #3560 SelfAccessorFixer is risky (Slamdunk) +* minor #3435 Add tests for general_phpdoc_annotation_remove (BackEndTea) +* minor #3484 Create Tokens::findBlockStart (ntzm) +* minor #3512 Add missing array typehints (ntzm) +* minor #3516 Use null|type instead of ?type in PHPDocs (ntzm) +* minor #3518 FixerFactoryTest - Test each priority test file is listed as test (SpacePossum) +* minor #3520 Fix typos: ran vs. run (SpacePossum) +* minor #3521 Use HTTPS (carusogabriel) +* minor #3526 Remove gecko dependency (SpacePossum, keradus, julienfalque) +* minor #3531 Backport PHPMD to LTS version to ease maintainability (keradus) +* minor #3532 Implement Tokens::findOppositeBlockEdge (ntzm) +* minor #3533 DX: SCA - drop src/Resources exclusion (keradus) +* minor #3538 Don't use third parameter of Tokens::findBlockStart (ntzm) +* minor #3542 Enhancement: Run composer-normalize on Travis CI (localheinz, keradus) +* minor #3555 DX: composer.json - drop branch-alias, branch is already following the version (keradus) +* minor #3556 DX: Add AutoReview/ComposerTest (keradus) +* minor #3559 Don't expose new files under Test namespace (keradus) + +Changelog for v2.2.16 +--------------------- + +* bug #3502 Fix missing file in export (keradus) + +Changelog for v2.2.15 +--------------------- + +* bug #3367 NoUnusedImportsFixer - fix comment handling (SpacePossum, keradus) +* bug #3455 NoEmptyCommentFixer - comment block detection for line ending different than LF (kubawerlos, SpacePossum) +* bug #3458 SilencedDeprecationErrorFixer - fix edge cases (kubawerlos) +* bug #3466 no_whitespace_in_blank_line and no_blank_lines_after_phpdoc fixers bug (kubawerlos, keradus) +* minor #3354 Added missing types to the PhpdocTypesFixer (GrahamCampbell) +* minor #3406 Fix for escaping in README (kubawerlos) +* minor #3431 Add missing tests (SpacePossum) +* minor #3440 Add a handful of integration tests (BackEndTea) +* minor #3444 IntegrationTest - ensure tests in priority dir are priority tests indeed (keradus) +* minor #3494 Add missing PHPDoc param type (ntzm) +* minor #3495 Swap @var type and element (ntzm) +* minor #3498 NoUnusedImportsFixer - fix deprecation (keradus) + +Changelog for v2.2.14 +--------------------- + +* bug #3298 DiffConsoleFormatter - fix output escaping. (SpacePossum) +* bug #3337 BracesFixer: nowdoc bug on template files (Slamdunk) +* bug #3349 Fix stdin handling and add tests for it (keradus) +* bug #3359 BracesFixer - handle comment for content outside of given block (keradus) +* bug #3415 FileFilterIterator - input checks and utests (SpacePossum, keradus) +* bug #3429 Fix archive analysing (keradus) +* minor #3137 PHPUnit - use common base class (keradus) +* minor #3342 PhpUnitDedicateAssertFixer - Remove unexistent method is_boolean (carusogabriel) +* minor #3345 StdinFileInfo - fix `__toString` (keradus) +* minor #3346 StdinFileInfo - drop getContents (keradus) +* minor #3347 DX: reapply newest CS (keradus) +* minor #3365 COOKBOOK-FIXERS.md - update to provide definition instead of description (keradus) +* minor #3370 AbstractFixer - FQCN in in exceptions (Slamdunk) +* minor #3372 ProjectCodeTest - fix comment (keradus) +* minor #3402 Always provide delimiter to `preg_quote` calls (ntzm) +* minor #3403 Remove unused import (ntzm) +* minor #3405 Fix `fopen` mode (ntzm) +* minor #3408 Improving fixers descriptions (kubawerlos) +* minor #3409 move itests from misc to priority (keradus) +* minor #3411 Better type hinting for AbstractFixerTestCase::$fixer (kubawerlos) +* minor #3412 Convert `strtolower` inside `strpos` to just `stripos` (ntzm) +* minor #3425 FixerFactoryTest - test that priority pair fixers have itest (keradus, SpacePossum) +* minor #3427 ConfigurationResolver: fix @return annotation (Slamdunk) + +Changelog for v2.2.13 +--------------------- + +* bug #3281 SelfAccessorFixer - stop modifying traits (kubawerlos) +* minor #3195 Add self-update command test (julienfalque) +* minor #3292 PHPUnit - set memory limit (veewee) +* minor #3306 Token - better input validation (keradus) + +Changelog for v2.2.12 +--------------------- + +* bug #3173 SimplifiedNullReturnFixer - handle nullable return types (Slamdunk) +* bug #3272 PhpdocTrimFixer - unicode support (SpacePossum) + +Changelog for v2.2.11 +--------------------- + +* bug #3225 PhpdocTrimFixer - Fix handling of lines without leading asterisk (julienfalque) +* bug #3262 ToolInfo - support installation by branch as well (keradus) +* bug #3266 PhpUnitConstructFixer - multiple asserts bug (kubawerlos) +* minor #3239 Improve contributing guide and issue template (julienfalque) +* minor #3246 Make ToolInfo methods non-static (julienfalque) +* minor #3250 Travis: fail early, spare resources, save the Earth (Slamdunk, keradus) +* minor #3251 Create Title for config file docs section (IanEdington) +* minor #3254 AutoReview/FixerFactoryTest::testFixersPriority: verbose assertion message (Slamdunk) + +Changelog for v2.2.10 +--------------------- + +* bug #3199 TokensAnalyzer - getClassyElements (SpacePossum) +* bug #3208 BracesFixer - Fix for instantiation in control structures (julienfalque, SpacePossum) +* bug #3215 BinaryOperatorSpacesFixer - Fix spaces around multiple exception catching (|) (ntzm) +* bug #3216 AbstractLinesBeforeNamespaceFixer - add min. and max. option, not only single target count (SpacePossum) +* bug #3217 TokenizerLinter - fix lack of linting when code is cached (SpacePossum, keradus) +* minor #3200 Skip slow test when Xdebug is loaded (julienfalque) +* minor #3219 Normalise references to GitHub in docs (ntzm) +* minor #3226 Remove unused imports (ntzm) +* minor #3231 Fix typos (ntzm) +* minor #3234 Simplify Cache\Signature::equals (ntzm) +* minor #3237 UnconfigurableFixer - use only LF (keradus) +* minor #3238 AbstractFixerTest - fix @cover annotation (keradus) + +Changelog for v2.2.9 +-------------------- + +* bug #3062 BraceClassInstantiationTransformer - Fix instantiation inside method call braces case (julienfalque, keradus) +* bug #3083 SingleBlankLineBeforeNamespaceFixer - Fix handling namespace right after opening tag (mlocati) +* bug #3109 SwitchCaseSemicolonToColonFixer - Fix bug with nested constructs (SpacePossum) +* bug #3123 Cache - File permissions (SpacePossum) +* bug #3172 IndentationTypeFixer - do not touch whitespace that is not indentation (SpacePossum) +* bug #3176 NoMultilineWhitespaceBeforeSemicolonsFixer - SpaceAfterSemicolonFixer - priority fix (SpacePossum) +* bug #3193 TokensAnalyzer::getClassyElements - sort result before returning (SpacePossum) +* bug #3196 SelfUpdateCommand - fix exit status when can't determine newest version (julienfalque) +* minor #3107 ConfigurationResolver - improve error message when rule is not found (SpacePossum) +* minor #3113 Add WordMatcher (keradus) +* minor #3133 Unify Reporter tests (keradus) +* minor #3134 Allow Symfony 4 (keradus, garak) +* minor #3136 PHPUnit - call hooks from parent class as well (keradus) +* minor #3145 misc - Typo (localheinz) +* minor #3150 Fix CircleCI (julienfalque) +* minor #3151 Update gitattributes to ignore next file (keradus) +* minor #3156 Update php-coveralls (keradus) +* minor #3166 README - add link to new gitter channel. (SpacePossum) +* minor #3174 Update UPGRADE.md (vitek-rostislav) +* minor #3180 Fix usage of static variables (kubawerlos) +* minor #3184 Code grooming - sort content of arrays (keradus) +* minor #3191 Travis - add nightly build to allow_failures due to Travis issues (keradus) +* minor #3197 DX groom CS (keradus) + +Changelog for v2.2.8 +-------------------- + +* bug #3052 Fix false positive warning about paths overridden by provided as command arguments (kubawerlos) +* bug #3058 IsNullFixer - fix whitespace handling (roukmoute) +* bug #3072 IsNullFixer - fix non_yoda_style edge case (keradus) +* bug #3088 Drop dedicated Phar stub (keradus) +* bug #3100 NativeFunctionInvocationFixer - Fix test if previous token is already namespace separator (SpacePossum) +* bug #3104 DoctrineAnnotationIndentationFixer - Fix str_repeat() error (julienfalque) +* minor #3038 Support PHP 7.2 (SpacePossum, keradus) +* minor #3064 Fix couple of typos (KKSzymanowski) +* minor #3078 ConfigurationResolver - hide context while including config file (keradus) +* minor #3080 Direct function call instead of by string (kubawerlos) +* minor #3085 CiIntegrationTest - skip when no git is available (keradus) +* minor #3087 phar-stub.php - allow PHP 7.2 (keradus) + +Changelog for v2.2.7 +-------------------- + +* bug #3002 Bugfix braces (mnabialek) +* bug #3010 Fix handling of Github releases (julienfalque, keradus) +* bug #3015 Fix exception arguments (julienfalque) +* bug #3016 Verify phar file (keradus) +* bug #3021 Risky rules cleanup (kubawerlos) +* bug #3023 RandomApiMigrationFixer - "rand();" to "random_int(0, getrandmax());" fixing (SpacePossum) +* bug #3024 ConfigurationResolver - Handle empty "rules" value (SpacePossum, keradus) +* bug #3031 IndentationTypeFixer - fix handling tabs in indented comments (keradus) +* minor #2999 Notice when paths from config file are overridden by command arguments (julienfalque, keradus) +* minor #3007 Add PHP 7.2 to Travis build matrix (Jean85) +* minor #3009 CiIntegrationTest - run local (SpacePossum) +* minor #3013 Adjust phpunit configuration (localheinz) +* minor #3017 Fix: Risky tests (localheinz) +* minor #3018 Fix: Make sure that data providers are named correctly (localheinz, keradus) +* minor #3032 .php_cs.dist - handling UnexpectedValueException (keradus) +* minor #3034 Follow newest CS (keradus) +* minor #3036 Drop not existing Standalone group from PHPUnit configuration and duplicated internal tags (keradus) +* minor #3042 Update gitter address (keradus) + +Changelog for v2.2.6 +-------------------- + +* bug #2925 Improve CI integration suggestion (julienfalque) +* bug #2928 TokensAnalyzer::getClassyElements - Anonymous class support (SpacePossum) +* bug #2931 Psr0Fixer, Psr4Fixer - ignore "new class" syntax (dg, keradus) +* bug #2934 Config - fix handling rule without value (keradus, SpacePossum) +* bug #2939 NoUnusedImportsFixer - Fix extra blank line (julienfalque) +* bug #2941 PHP 7.2 - Group imports with trailing comma support (SpacePossum, julienfalque) +* bug #2987 Fix incorrect indentation of comments in `braces` fixer (rob006) +* minor #2927 WhiteSpaceConfig - update message copy and more strict tests (SpacePossum, keradus) +* minor #2930 Trigger website build (keradus) +* minor #2932 Integrate CircleCI (keradus, aidantwoods) +* minor #2933 ProcessLinterTest - Ensure Windows test only runs on Windows, add a Mac test execution (aidantwoods) +* minor #2935 special handling of fabbot.io service if it's using too old PHP CS Fixer version (keradus) +* minor #2937 Travis: execute 5.3 job on precise (keradus) +* minor #2938 Tests fix configuration of project (SpacePossum, keradus) +* minor #2943 FunctionToConstantFixer - test with diff. arguments than fixable (SpacePossum) +* minor #2946 Detect extra old installations (keradus) +* minor #2947 Test suggested CI integration (keradus) +* minor #2951 AccessibleObject - remove most of usage (keradus) +* minor #2969 Shrink down AccessibleObject usage (keradus) +* minor #2982 TrailingCommaInMultilineArrayFixer - simplify isMultilineArray condition (TomasVotruba) + +Changelog for v2.2.5 +-------------------- + +* bug #2807 NoUselessElseFixer - Fix detection of conditional block (SpacePossum) +* bug #2809 Phar release - fix readme generation (SpacePossum, keradus) +* bug #2827 MethodArgumentSpaceFixer - Always remove trailing spaces (julienfalque) +* bug #2835 SelfAccessorFixer - class property fix (mnabialek) +* bug #2848 PhpdocIndentFixer - fix edge case with inline phpdoc (keradus) +* bug #2849 BracesFixer - Fix indentation issues with comments (julienfalque) +* bug #2851 Tokens - ensureWhitespaceAtIndex (GrahamCampbell, SpacePossum) +* bug #2854 NoLeadingImportSlashFixer - Removing leading slash from import even when in global space (kubawerlos) +* bug #2858 Support generic types (keradus) +* bug #2869 Fix handling required configuration (keradus) +* bug #2881 NoUnusedImportsFixer - Bug when trying to insert empty token (GrahamCampbell, keradus) +* bug #2882 DocBlock\Annotation - Fix parsing of collections with multiple key types (julienfalque) +* bug #2886 NoSpacesInsideParenthesisFixer - Do not remove whitespace if next token is comment (SpacePossum) +* bug #2888 SingleImportPerStatementFixer - Add support for function and const (SpacePossum) +* bug #2901 Add missing files to archive files (keradus) +* bug #2914 HeredocToNowdocFixer - works with CRLF line ending (dg) +* bug #2920 RuleSet - Update deprecated configuration of fixers (SpacePossum, keradus) +* minor #1531 Update docs for few generic types (keradus) +* minor #2793 COOKBOOK-FIXERS.md - update to current version, fix links (keradus) +* minor #2812 ProcessLinter - compatibility with Symfony 3.3 (keradus) +* minor #2816 Tokenizer - better docs and validation (keradus) +* minor #2817 Tokenizer - use future-compatible interface (keradus) +* minor #2819 Fix benchmark (keradus) +* minor #2824 code grooming (keradus) +* minor #2826 Exceptions - provide utests (localheinz) +* minor #2828 Enhancement: Reference phpunit.xsd from phpunit.xml.dist (localheinz) +* minor #2830 Differs - add tests (localheinz) +* minor #2832 Fix: Use all the columns (localheinz) +* minor #2833 Doctrine\Annotation\Token - provide utests (localheinz) +* minor #2839 Use PHP 7.2 polyfill instead of xml one (keradus) +* minor #2842 Move null to first position in PHPDoc types (julienfalque) +* minor #2850 ReadmeCommandTest - Prevent diff output (julienfalque) +* minor #2859 Fixed typo and dead code removal (GrahamCampbell) +* minor #2863 FileSpecificCodeSample - add tests (localheinz) +* minor #2864 WhitespacesAwareFixerInterface clean up (Slamdunk) +* minor #2865 AutoReview\FixerTest - test configuration samples (SpacePossum, keradus) +* minor #2867 VersionSpecification - Fix copy-paste typo (SpacePossum) +* minor #2874 LineTest - fix typo (keradus) +* minor #2875 HelpCommand - recursive layout fix (SpacePossum) +* minor #2883 DescribeCommand - Show which sample uses the default configuration (SpacePossum) +* minor #2887 Housekeeping - Strict whitespace checks (SpacePossum) +* minor #2895 ProjectCodeTest - check that classes in no-tests exception exist (keradus) +* minor #2896 Move testing related classes from src to tests (keradus) +* minor #2904 Reapply CS (keradus) +* minor #2910 PhpdocAnnotationWithoutDotFixer - Restrict lowercasing (oschwald) +* minor #2913 Tests - tweaks (SpacePossum, keradus) +* minor #2916 FixerFactory - drop return in sortFixers(), never used (TomasVotruba) + +Changelog for v2.2.4 +-------------------- + +* bug #2682 DoctrineAnnotationIndentationFixer - fix handling nested annotations (edhgoose, julienfalque) +* bug #2700 Fix Doctrine Annotation end detection (julienfalque) +* bug #2715 OrderedImportsFixer - handle indented groups (pilgerone) +* bug #2732 HeaderCommentFixer - fix handling blank lines (s7b4) +* bug #2745 Fix Doctrine Annotation newlines (julienfalque) +* bug #2752 FixCommand - fix typo in warning message (mnapoli) +* bug #2757 GeckoPHPUnit is not dev dependency (keradus) +* bug #2759 Update gitattributes (SpacePossum) +* bug #2763 Fix describe command with PSR-0 fixer (julienfalque) +* bug #2768 Tokens::ensureWhitespaceAtIndex - clean up comment check, add check for T_OPEN (SpacePossum) +* bug #2783 Tokens::ensureWhitespaceAtIndex - Fix handling line endings (SpacePossum) +* minor #2663 Use colors for keywords in commands output (julienfalque, keradus) +* minor #2706 Update README (SpacePossum) +* minor #2714 README.rst - fix wrong value in example (mleko) +* minor #2721 Update phpstorm article link to a fresh blog post (valeryan) +* minor #2727 PHPUnit - use speedtrap (keradus) +* minor #2728 SelfUpdateCommand - verify that it's possible to replace current file (keradus) +* minor #2729 DescribeCommand - add decorated output test (julienfalque) +* minor #2731 BracesFixer - properly pass config in utest dataProvider (keradus) +* minor #2738 Upgrade tests to use new, namespaced PHPUnit TestCase class (keradus) +* minor #2743 Fixing example and description for GeneralPhpdocAnnotationRemoveFixer (kubawerlos) +* minor #2744 AbstractDoctrineAnnotationFixerTestCase - split fixers test cases (julienfalque) +* minor #2755 Fix compatibility with PHPUnit 5.4.x (keradus) +* minor #2758 Readme - improve CI integration guidelines (keradus) +* minor #2769 Psr0Fixer - remove duplicated example (julienfalque) +* minor #2775 NoExtraConsecutiveBlankLinesFixer - remove duplicate code sample. (SpacePossum) +* minor #2778 AutoReview - watch that code samples are unique (keradus) +* minor #2787 Add warnings about missing dom ext and require json ext (keradus) +* minor #2792 Use composer-require-checker (keradus) +* minor #2796 Update .gitattributes (SpacePossum) +* minor #2800 PhpdocTypesFixerTest - Fix typo in covers annotation (SpacePossum) + +Changelog for v2.2.3 +-------------------- + +* bug #2724 Revert #2554 Add short diff. output format (keradus) + +Changelog for v2.2.2 +-------------------- + +Warning, this release breaks BC due to introduction of: +* minor #2554 Add short diff. output format (SpacePossum, keradus) +That PR was reverted in v2.2.3, which should be used instead of v2.2.2. + +* bug #2545 RuleSet - change resolvement (SpacePossum) +* bug #2686 Commands readme and describe - fix rare casing when not displaying some possible options of configuration (keradus) +* bug #2711 FixCommand - fix diff optional value handling (keradus) +* minor #2688 AppVeyor - Remove github oauth (keradus) +* minor #2703 Clean ups - No mixed annotations (SpacePossum) +* minor #2704 Create PHP70Migration:risky ruleset (keradus) +* minor #2707 Deprecate other than "yes" or "no" for input options (SpacePossum) +* minor #2709 code grooming (keradus) +* minor #2710 Travis - run more rules on TASK_SCA (keradus) + +Changelog for v2.2.1 +-------------------- + +* bug #2621 Tokenizer - fix edge cases with empty code, registered found tokens and code hash (SpacePossum, keradus) +* bug #2674 SemicolonAfterInstructionFixer - Fix case where block ends with an opening curly brace (ntzm) +* bug #2675 ProcessOutputTest - update tests to pass on newest Symfony components under Windows (keradus) +* minor #2651 Fix UPGRADE.md table syntax so it works in GitHub (ntzm, keradus) +* minor #2665 Travis - Improve trailing spaces detection (julienfalque) +* minor #2666 TransformersTest - move test to auto-review group (keradus) +* minor #2668 add covers annotation (keradus) +* minor #2669 TokensTest - grooming (SpacePossum) +* minor #2670 AbstractFixer: use applyFix instead of fix (Slamdunk) +* minor #2677 README: Correct progressbar option support (Laurens St�tzel) + +Changelog for v2.2.0 +-------------------- + +* bug #2640 NoExtraConsecutiveBlankLinesFixer - Fix single indent characters not working (ntzm) +* feature #2220 Doctrine annotation fixers (julienfalque) +* feature #2431 MethodArgumentSpaceFixer: allow to retain multiple spaces after comma (Slamdunk) +* feature #2459 BracesFixer - Add option for keeping opening brackets on the same line (jtojnar, SpacePossum) +* feature #2486 Add FunctionToConstantFixer (SpacePossum, keradus) +* feature #2505 FunctionDeclarationFixer - Make space after anonymous function configurable (jtojnar, keradus) +* feature #2509 FullOpeningTagFixer - Ensure opening PHP tag is lowercase (jtojnar) +* feature #2532 FixCommand - add stop-on-violation option (keradus) +* feature #2591 Improve process output (julienfalque) +* feature #2603 Add InvisibleSymbols Fixer (ivan1986, keradus) +* feature #2642 Add MagicConstantCasingFixer (ntzm) +* feature #2657 PhpdocToCommentFixer - Allow phpdoc for language constructs (ceeram, SpacePossum) +* minor #2500 Configuration resolver (julienfalque, SpacePossum, keradus) +* minor #2566 Show more details on errors and exceptions. (SpacePossum, julienfalque) +* minor #2597 HHVM - bump required version to 3.18 (keradus) +* minor #2606 FixCommand - fix missing comment close tag (keradus) +* minor #2623 OrderedClassElementsFixer - remove dead code (SpacePossum) +* minor #2625 Update Symfony and Symfony:risky rulesets (keradus) +* minor #2626 TernaryToNullCoalescingFixer - adjust ruleset membership and description (keradus) +* minor #2635 ProjectCodeTest - watch that all classes have dedicated tests (keradus) +* minor #2647 DescribeCommandTest - remove deprecated code usage (julienfalque) +* minor #2648 Move non-code covering tests to AutoReview subnamespace (keradus) +* minor #2652 NoSpacesAroundOffsetFixerTest - fix deprecation (keradus) +* minor #2656 Code grooming (keradus) +* minor #2659 Travis - speed up preparation for phar building (keradus) +* minor #2660 Fixed typo in suggest for ext-mbstring (pascal-hofmann) +* minor #2661 NonPrintableCharacterFixer - include into Symfony:risky ruleset (keradus) + +Changelog for v2.1.3 +-------------------- + +* bug #2358 Cache - Deal with signature encoding (keradus, GrahamCampbell) +* bug #2475 Add shorthand array destructing support (SpacePossum, keradus) +* bug #2595 NoUnusedImportsFixer - Fix import usage detection with properties (julienfalque) +* bug #2605 PhpdocAddMissingParamAnnotationFixer, PhpdocOrderFixer - fix priority issue (SpacePossum) +* bug #2607 Fixers - better comments handling (SpacePossum) +* bug #2612 BracesFixer - Fix early bracket close for do-while loop inside an if without brackets (felixgomez) +* bug #2614 Ensure that '*Fixer::fix()' won't crash when running on non-candidate collection (keradus) +* bug #2630 HeaderCommentFixer - Fix trailing whitespace not removed after AliasFunctionsFixer (kalessil) +* feature #1275 Added PhpdocInlineTagFixer (SpacePossum, keradus) +* feature #1292 Added MethodSeparationFixer (SpacePossum) +* feature #1383 Introduce rules and sets (keradus) +* feature #1416 Mark fixers as risky (keradus) +* feature #1440 Made AbstractFixerTestCase and AbstractIntegrationTestCase public (keradus) +* feature #1489 Added Psr4Fixer (GrahamCampbell) +* feature #1497 ExtraEmptyLinesFixer - allow to remove empty blank lines after configured tags (SpacePossum) +* feature #1529 Added PhpdocPropertyFixer, refactored Tag and Annotation (GrahamCampbell) +* feature #1628 Added OrderedClassElementsFixer (gharlan) +* feature #1742 path argument is used to create an intersection with existing finder (keradus, gharlan) +* feature #1779 Added GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocAnnotationRenameFixer (keradus) +* feature #1811 Added NoSpacesInsideOffsetFixer (phansys) +* feature #1819 Added DirConstantFixer, ModernizeTypesCastingFixer, RandomApiMigrationFixer (kalessil, SpacePossum, keradus) +* feature #1825 Added junit format (ekho) +* feature #1862 FixerFactory - Do not allow conflicting fixers (SpacePossum) +* feature #1888 Cache refactoring, better cache handling in dry-run mode (localheinz) +* feature #1889 Added SingleClassElementPerStatementFixer (phansys, SpacePossum) +* feature #1903 FixCommand - allow to pass multiple path argument (keradus) +* feature #1913 Introduce path-mode CLI option (keradus) +* feature #1949 Added DeclareStrictTypesFixer, introduce options for HeaderCommentFixer (Seldaek, SpacePossum, keradus) +* feature #1955 Introduce CT_ARRAY_INDEX_CURLY_BRACE_OPEN and CT_ARRAY_INDEX_CURLY_BRACE_CLOSE (keradus) +* feature #1958 Added NormalizeIndexBraceFixer (keradus) +* feature #2069 Add semicolon after instruction fixer (SpacePossum) +* feature #2089 Add `no_spaces_around_offset` fixer (phansys) +* feature #2179 BinaryOperatorSpacesFixer - add (un)align configuration options (SpacePossum) +* feature #2192 Add PowToExponentiationFixer (SpacePossum, keradus) +* feature #2207 Added ReturnTypeDeclarationFixer (keradus) +* feature #2213 VisibilityRequiredFixer - Add support for class const visibility added in PHP7.1. (SpacePossum) +* feature #2221 Add support for user-defined whitespaces (keradus) +* feature #2244 Config cleanup (keradus, SpacePossum) +* feature #2247 PhpdocAnnotationWithoutDotFixer - support more cases (keradus) +* feature #2289 Add PhpdocAddMissingParamAnnotationFixer (keradus) +* feature #2331 Add DescribeCommand (keradus, SpacePossum) +* feature #2332 New colours of diff on console (keradus) +* feature #829 add support for .php_cs.dist file (keradus) +* feature #998 MethodArgumentSpaceFixer - enhance, now only one space after comma (trilopin, keradus) +* minor #1007 Simplify Transformers (keradus) +* minor #1050 Make Config's setDir() fluent like the rest of methods (gonzaloserrano) +* minor #1062 Added NamespaceOperatorTransformer (gharlan) +* minor #1078 Exit status should be 0 if there are no errors (gharlan) +* minor #1101 CS: fix project itself (localheinz) +* minor #1102 Enhancement: List errors occurred before, during and after fixing (localheinz) +* minor #1105 Token::isStructureAlternativeEnd - remove unused method (keradus) +* minor #1106 readme grooming (SpacePossum, keradus) +* minor #1115 Fixer - simplify flow (keradus) +* minor #1118 Process output refactor (SpacePossum) +* minor #1132 Linter - public methods should be first (keradus) +* minor #1134 Token::isWhitespace - simplify interface (keradus) +* minor #1140 FixerInterface - check if fixer should be applied by isCandidate method (keradus) +* minor #1146 Linter - detect executable (keradus) +* minor #1156 deleted old ConfigurationResolver class (keradus) +* minor #1160 Grammar fix to README (Falkirks) +* minor #1174 DefaultFinder - boost performance by not filtering when files array is empty (keradus) +* minor #1179 Exit with non-zero if invalid files were detected prior to fixing (localheinz) +* minor #1186 Finder - do not search for .xml and .yml files (keradus) +* minor #1206 BracesFixer::getClassyTokens - remove duplicated method (keradus) +* minor #1222 Made fixers final (GrahamCampbell) +* minor #1229 Tokens - Fix PHPDoc (SpacePossum) +* minor #1241 More details on exceptions. (SpacePossum) +* minor #1263 Made internal classes final (GrahamCampbell) +* minor #1272 Readme - Add spaces around PHP-CS-Fixer headers (Soullivaneuh) +* minor #1283 Error - Fixed type phpdoc (GrahamCampbell) +* minor #1284 Token - Fix PHPDoc (SpacePossum) +* minor #1314 Added missing internal annotations (keradus) +* minor #1329 Psr0Fixer - move to contrib level (gharlan) +* minor #1340 Clean ups (SpacePossum) +* minor #1341 Linter - throw exception when write fails (SpacePossum) +* minor #1348 Linter - Prefer error output when throwing a linting exception (GrahamCampbell) +* minor #1350 Add "phpt" as a valid extension (henriquemoody) +* minor #1376 Add time and memory to XML report (junichi11) +* minor #1387 Made all test classes final (keradus) +* minor #1388 Made all tests internal (keradus) +* minor #1390 Added ProjectCodeTest that tests if all classes inside tests are internal and final or abstract (keradus) +* minor #1391 Fixer::getLevelAsString is no longer static (keradus) +* minor #1392 Add report to XML report as the root node (junichi11) +* minor #1394 Stop mixing level from config file and fixers from CLI arg when one of fixers has dash (keradus) +* minor #1426 MethodSeparationFixer - Fix spacing around comments (SpacePossum, keradus) +* minor #1432 Fixer check on factory (Soullivaneuh) +* minor #1434 Add Test\AccessibleObject class (keradus) +* minor #1442 FixerFactory - disallow to register multiple fixers with same name (keradus) +* minor #1477 rename PhpdocShortDescriptionFixer into PhpdocSummaryFixer (keradus) +* minor #1481 Fix running the tests (keradus) +* minor #1482 move AbstractTransformerTestBase class outside Tests dir (keradus) +* minor #1530 Added missing internal annotation (GrahamCampbell) +* minor #1534 Clean ups (SpacePossum) +* minor #1536 Typo fix (fabpot) +* minor #1555 Fixed indentation in composer.json (GrahamCampbell) +* minor #1558 [2.0] Cleanup the tags property in the abstract phpdoc types fixer (GrahamCampbell) +* minor #1567 PrintToEchoFixer - add to symfony rule set (gharlan) +* minor #1607 performance improvement (gharlan) +* minor #1621 Switch to PSR-4 (keradus) +* minor #1631 Configuration exceptions exception cases on master. (SpacePossum) +* minor #1646 Remove non-default Config/Finder classes (keradus) +* minor #1648 Fixer - avoid extra calls to getFileRelativePathname (GrahamCampbell) +* minor #1649 Consider the php version when caching (GrahamCampbell) +* minor #1652 Rename namespace "Symfony\CS" to "PhpCsFixer" (gharlan) +* minor #1666 new Runner, ProcessOutputInterface, DifferInterface and ResultInterface (keradus) +* minor #1674 Config - add addCustomFixers method (PedroTroller) +* minor #1677 Enhance tests (keradus) +* minor #1695 Rename Fixers (keradus) +* minor #1702 Upgrade guide (keradus) +* minor #1707 ExtraEmptyLinesFixer - fix configure docs (keradus) +* minor #1712 NoExtraConsecutiveBlankLinesFixer - Remove blankline after curly brace open (SpacePossum) +* minor #1718 CLI: rename --config-file argument (keradus) +* minor #1722 Renamed not_operators_with_space to not_operator_with_space (GrahamCampbell) +* minor #1728 PhpdocNoSimplifiedNullReturnFixer - rename back to PhpdocNoEmptyReturnFixer (keradus) +* minor #1729 Renamed whitespacy_lines to no_whitespace_in_blank_lines (GrahamCampbell) +* minor #1731 FixCommand - value for config option is required (keradus) +* minor #1732 move fixer classes from level subdirs to thematic subdirs (gharlan, keradus) +* minor #1733 ConfigurationResolver - look for .php_cs file in cwd as well (keradus) +* minor #1737 RuleSet/FixerFactory - sort arrays content (keradus) +* minor #1751 FixerInterface::configure - method should always override configuration, not patch it (keradus) +* minor #1752 Remove unused code (keradus) +* minor #1756 Finder - clean up code (keradus) +* minor #1757 Psr0Fixer - change way of configuring the fixer (keradus) +* minor #1762 Remove ConfigInterface::getDir, ConfigInterface::setDir, Finder::setDir and whole FinderInterface (keradus) +* minor #1764 Remove ConfigAwareInterface (keradus) +* minor #1780 AbstractFixer - throw error on configuring non-configurable Fixer (keradus) +* minor #1782 rename fixers (gharlan) +* minor #1815 NoSpacesInsideParenthesisFixer - simplify implementation (keradus) +* minor #1821 Ensure that PhpUnitDedicateAssertFixer runs after NoAliasFunctionsFixer, clean up NoEmptyCommentFixer (SpacePossum) +* minor #1824 Reporting extracted to separate classes (ekho, keradus, SpacePossum) +* minor #1826 Fixer - remove measuring fixing time per file (keradus) +* minor #1843 FileFilterIterator - add missing import (GrahamCampbell) +* minor #1845 FileCacheManager - Allow linting to determine the cache state too (GrahamCampbell) +* minor #1846 FileFilterIterator - Corrected an iterator typehint (GrahamCampbell) +* minor #1848 DocBlock - Remove some old unused phpdoc tags (GrahamCampbell) +* minor #1856 NoDuplicateSemicolonsFixer - Remove overcomplete fixer (SpacePossum) +* minor #1861 Fix: Offset should be Offset (localheinz) +* minor #1867 Print non-report output to stdErr (SpacePossum, keradus) +* minor #1873 Enhancement: Show path to cache file if it exists (localheinz) +* minor #1875 renamed Composer package (fabpot) +* minor #1882 Runner - Handle throwables too (GrahamCampbell) +* minor #1886 PhpdocScalarFixer - Fix lowercase str to string too (GrahamCampbell) +* minor #1940 README.rst - update CI example (keradus) +* minor #1947 SCA, CS, add more tests (SpacePossum, keradus) +* minor #1954 tests - stop using deprecated method (sebastianbergmann) +* minor #1962 TextDiffTest - tests should not produce cache file (keradus) +* minor #1973 Introduce fast PHP7 based linter (keradus) +* minor #1999 Runner - No need to determine relative file name twice (localheinz) +* minor #2002 FileCacheManagerTest - Adjust name of test and variable (localheinz) +* minor #2010 NoExtraConsecutiveBlankLinesFixer - SF rule set, add 'extra' (SpacePossum) +* minor #2013 no_whitespace_in_blank_lines -> no_whitespace_in_blank_line (SpacePossum) +* minor #2024 AbstractFixerTestCase - check if there is no duplicated Token instance inside Tokens collection (keradus) +* minor #2031 COOKBOOK-FIXERS.md - update calling doTest method (keradus) +* minor #2032 code grooming (keradus) +* minor #2068 Code grooming (keradus) +* minor #2073 DeclareStrictTypesFixer - Remove fix CS fix logic from fixer. (SpacePossum) +* minor #2088 TokenizerLintingResult - expose line number of parsing error (keradus) +* minor #2093 Tokens - add block type BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE (SpacePossum) +* minor #2095 Transformers - add required PHP version (keradus) +* minor #2096 Introduce CT for PHP7 (keradus) +* minor #2119 Create @Symfony:risky ruleset (keradus) +* minor #2163 ClassKeywordRemoveFixerTest - Fix tests (SpacePossum) +* minor #2180 FixCommand - don't refer to renamed rules (keradus) +* minor #2181 Disallow to disable linter (keradus) +* minor #2194 semicolon_after_instruction,no_unneeded_control_parentheses prio issue (SpacePossum) +* minor #2199 make fixers less risky (SpacePossum) +* minor #2206 Add PHP70Migration ruleset (keradus) +* minor #2217 SelfUpdateCommand - Print version of update fixer (SpacePossum) +* minor #2223 update integration test format (keradus) +* minor #2227 Stop polluting global namespace with CT (keradus) +* minor #2237 DX: extend integration tests for PSR2 and Symfony rulesets (keradus) +* minor #2240 Make some objects immutable (keradus) +* minor #2251 ProtectedToPrivateFixer - fix priority, fix comments with new fixer names (SpacePossum) +* minor #2252 ClassDefinitionFixer - Set configuration of the fixer in the RuleSet of SF. (SpacePossum) +* minor #2257 extend Symfony_whitespaces itest (keradus) +* minor #2258 README.rst - indicate configurable rules (keradus) +* minor #2267 RuleSet - validate set (keradus) +* minor #2268 Use strict parameters for PHP functions (keradus) +* minor #2273 fixed typo (fabpot) +* minor #2274 ShortArraySyntaxFixer/LongArraySyntaxFixer - Merge conflicting fixers (SpacePossum) +* minor #2275 Clean ups (SpacePossum) +* minor #2278 Concat*Fixer - unify concat fixers (SpacePossum, keradus) +* minor #2279 Use Prophecy (keradus) +* minor #2284 Code grooming (SpacePossum) +* minor #2285 IntegrationCase is now aware about RuleSet but not Fixers (keradus, SpacePossum) +* minor #2286 Phpdoc*Fixer - unify rename fixers (SpacePossum, keradus) +* minor #2288 FixerInterface::configure(null) reset fixer to use default configuration (keradus) +* minor #2291 Make fixers ready to use directly after creation (keradus) +* minor #2295 Code grooming (keradus) +* minor #2296 ProjectCodeTest - make test part of regular testsuite, not standalone one (keradus) +* minor #2298 ConfigurationResolver - grooming (SpacePossum) +* minor #2300 Simplify rule set (SpacePossum, keradus) +* minor #2306 DeclareStrictTypesFixer - do not move tokens (SpacePossum) +* minor #2312 RuleSet - sort rules (localheinz) +* minor #2313 DX: provide doctyping for tests (keradus) +* minor #2317 Add utests (keradus) +* minor #2318 *TestCase - Reduce visibility of setUp() (localheinz) +* minor #2319 Code grooming (keradus) +* minor #2322 DX: use whitemessy aware assertion (keradus) +* minor #2324 Echo|Print*Fixer - unify printing fixers (SpacePossum, keradus) +* minor #2337 Normalize rule naming (keradus) +* minor #2338 Drop hacks for unsupported HHVM (keradus) +* minor #2339 Add some Fixer descriptions (SpacePossum, keradus) +* minor #2343 PowToExponentiationFixer - allow to run on 5.6.0 as well (keradus) +* minor #767 Add @internal tag (keradus) +* minor #807 Tokens::isMethodNameIsMagic - remove unused method (keradus) +* minor #809 Split Tokens into Tokens and TokensAnalyzer (keradus) +* minor #844 Renamed phpdoc_params to phpdoc_align (GrahamCampbell) +* minor #854 Change default level to PSR2 (keradus) +* minor #873 Config - using cache by default (keradus) +* minor #902 change FixerInterface (keradus) +* minor #911 remove Token::$line (keradus) +* minor #914 All Transformer classes should be named with Transformer as suffix (keradus) +* minor #915 add UseTransformer (keradus) +* minor #916 add ArraySquareBraceTransformer (keradus) +* minor #917 clean up Transformer tests (keradus) +* minor #919 CurlyBraceTransformer - one transformer to handle all curly braces transformations (keradus) +* minor #928 remove Token::getLine (keradus) +* minor #929 add WhitespacyCommentTransformer (keradus) +* minor #937 fix docs/typehinting in few classes (keradus) +* minor #958 FileCacheManager - remove code for BC support (keradus) +* minor #979 Improve Tokens::clearEmptyTokens performance (keradus) +* minor #981 Tokens - code grooming (keradus) +* minor #988 Fixers - no need to search for tokens of given kind in extra loop (keradus) +* minor #989 No need for loop in Token::equals (keradus) + +Changelog for v1.13.3 +--------------------- + +* minor #3042 Update gitter address (keradus) + +Changelog for v1.13.2 +--------------------- + +* minor #2946 Detect extra old installations (keradus) + +Changelog for v1.13.1 +--------------------- + +* minor #2342 Application - adjust test to not depend on symfony/console version (keradus) +* minor #2344 AppVeyor: enforce PHP version (keradus) + +Changelog for v1.13.0 +--------------------- + +* bug #2303 ClassDefinitionFixer - Anonymous classes fixing (SpacePossum) +* feature #2208 Added fixer for PHPUnit's @expectedException annotation (ro0NL) +* feature #2249 Added ProtectedToPrivateFixer (Slamdunk, SpacePossum) +* feature #2264 SelfUpdateCommand - Do not update to next major version by default (SpacePossum) +* feature #2328 ClassDefinitionFixer - Anonymous classes format by PSR12 (SpacePossum) +* feature #2333 PhpUnitFqcnAnnotationFixer - support more annotations (keradus) +* minor #2256 EmptyReturnFixer - it's now risky fixer due to null vs void (keradus) +* minor #2281 Add issue template (SpacePossum) +* minor #2307 Update .editorconfig (SpacePossum) +* minor #2310 CI: update AppVeyor to use newest PHP, silence the composer (keradus) +* minor #2315 Token - Deprecate getLine() (SpacePossum) +* minor #2320 Clear up status code on 1.x (SpacePossum) + +Changelog for v1.12.4 +--------------------- + +* bug #2235 OrderedImportsFixer - PHP 7 group imports support (SpacePossum) +* minor #2276 Tokens cleanup (keradus) +* minor #2277 Remove trailing spaces (keradus) +* minor #2294 Improve Travis configuration (keradus) +* minor #2297 Use phpdbg instead of xdebug (keradus) +* minor #2299 Travis: proper xdebug disabling (keradus) +* minor #2301 Travis: update platform adjusting (keradus) + +Changelog for v1.12.3 +--------------------- + +* bug #2155 ClassDefinitionFixer - overhaul (SpacePossum) +* bug #2187 MultipleUseFixer - Fix handling comments (SpacePossum) +* bug #2209 LinefeedFixer - Fix in a safe way (SpacePossum) +* bug #2228 NoEmptyLinesAfterPhpdocs, SingleBlankLineBeforeNamespace - Fix priority (SpacePossum) +* bug #2230 FunctionDeclarationFixer - Fix T_USE case (SpacePossum) +* bug #2232 Add a test for style of variable declaration : var (daiglej) +* bug #2246 Fix itest requirements (keradus) +* minor #2238 .gitattributes - specified line endings (keradus) +* minor #2239 IntegrationCase - no longer internal (keradus) + +Changelog for v1.12.2 +--------------------- + +* bug #2191 PhpdocToCommentFixer - fix false positive for docblock of variable (keradus) +* bug #2193 UnneededControlParenthesesFixer - Fix more return cases. (SpacePossum) +* bug #2198 FileCacheManager - fix exception message and undefined property (j0k3r) +* minor #2170 Add dollar sign prefix for consistency (bcremer) +* minor #2190 .travis.yml - improve Travis speed for tags (keradus) +* minor #2196 PhpdocTypesFixer - support iterable type (GrahamCampbell) +* minor #2197 Update cookbook and readme (g105b, SpacePossum) +* minor #2203 README.rst - change formatting (ro0NL) +* minor #2204 FixCommand - clean unused var (keradus) +* minor #2205 Add integration test for iterable type (keradus) + +Changelog for v1.12.1 +--------------------- + +* bug #2144 Remove temporary files not deleted by destructor on failure (adawolfa) +* bug #2150 SelfUpdateCommand: resolve symlink (julienfalque) +* bug #2162 Fix issue where an exception is thrown if the cache file exists but is empty. (ikari7789) +* bug #2164 OperatorsSpacesFixer - Do not unalign double arrow and equals operators (SpacePossum) +* bug #2167 Rewrite file removal (keradus) +* minor #2152 Code cleanup (keradus) +* minor #2154 ShutdownFileRemoval - Fixed file header (GrahamCampbell) + +Changelog for v1.12.0 +--------------------- + +* feature #1493 Added MethodArgumentDefaultValueFixer (lmanzke) +* feature #1495 BracesFixer - added support for declare (EspadaV8) +* feature #1518 Added ClassDefinitionFixer (SpacePossum) +* feature #1543 [PSR-2] Switch case space fixer (Soullivaneuh) +* feature #1577 Added SpacesAfterSemicolonFixer (SpacePossum) +* feature #1580 Added HeredocToNowdocFixer (gharlan) +* feature #1581 UnneededControlParenthesesFixer - add "break" and "continue" support (gharlan) +* feature #1610 HashToSlashCommentFixer - Add (SpacePossum) +* feature #1613 ScalarCastFixer - LowerCaseCastFixer - Add (SpacePossum) +* feature #1659 NativeFunctionCasingFixer - Add (SpacePossum) +* feature #1661 SwitchCaseSemicolonToColonFixer - Add (SpacePossum) +* feature #1662 Added CombineConsecutiveUnsetsFixer (SpacePossum) +* feature #1671 Added NoEmptyStatementFixer (SpacePossum) +* feature #1705 Added NoUselessReturnFixer (SpacePossum, keradus) +* feature #1735 Added NoTrailingWhitespaceInCommentFixer (keradus) +* feature #1750 Add PhpdocSingleLineVarSpacingFixer (SpacePossum) +* feature #1765 Added NoEmptyPhpdocFixer (SpacePossum) +* feature #1773 Add NoUselessElseFixer (gharlan, SpacePossum) +* feature #1786 Added NoEmptyCommentFixer (SpacePossum) +* feature #1792 Add PhpUnitDedicateAssertFixer. (SpacePossum) +* feature #1894 BracesFixer - correctly fix indents of anonymous functions/classes (gharlan) +* feature #1985 Added ClassKeywordRemoveFixer (Soullivaneuh) +* feature #2020 Added PhpdocAnnotationWithoutDotFixer (keradus) +* feature #2067 Added DeclareEqualNormalizeFixer (keradus) +* feature #2078 Added SilencedDeprecationErrorFixer (HeahDude) +* feature #2082 Added MbStrFunctionsFixer (Slamdunk) +* bug #1657 SwitchCaseSpaceFixer - Fix spacing between 'case' and semicolon (SpacePossum) +* bug #1684 SpacesAfterSemicolonFixer - fix loops handling (SpacePossum, keradus) +* bug #1700 Fixer - resolve import conflict (keradus) +* bug #1836 NoUselessReturnFixer - Do not remove return if last statement in short if statement (SpacePossum) +* bug #1879 HeredocToNowdocFixer - Handle space in heredoc token (SpacePossum) +* bug #1896 FixCommand - Fix escaping of diff output (SpacePossum) +* bug #2034 IncludeFixer - fix support for close tag (SpacePossum) +* bug #2040 PhpdocAnnotationWithoutDotFixer - fix crash on odd character (keradus) +* bug #2041 DefaultFinder should implement FinderInterface (keradus) +* bug #2050 PhpdocAnnotationWithoutDotFixer - handle ellipsis (keradus) +* bug #2051 NativeFunctionCasingFixer - call to constructor with default NS of class with name matching native function name fix (SpacePossum) +* minor #1538 Added possibility to lint tests (gharlan) +* minor #1569 Add sample to get a specific version of the fixer (Soullivaneuh) +* minor #1571 Enhance integration tests (keradus) +* minor #1578 Code grooming (keradus) +* minor #1583 Travis - update matrix (keradus) +* minor #1585 Code grooming - Improve utests code coverage (SpacePossum) +* minor #1586 Add configuration exception classes and exit codes (SpacePossum) +* minor #1594 Fix invalid PHP code samples in utests (SpacePossum) +* minor #1597 MethodArgumentDefaultValueFixer - refactoring and fix closures with "use" clause (gharlan) +* minor #1600 Added more integration tests (SpacePossum, keradus) +* minor #1605 integration tests - swap EXPECT and INPUT (optional INPUT) (gharlan) +* minor #1608 Travis - change matrix order for faster results (gharlan) +* minor #1609 CONTRIBUTING.md - Don't rebase always on master (SpacePossum) +* minor #1616 IncludeFixer - fix and test more cases (SpacePossum) +* minor #1622 AbstractIntegratationTest - fix linting test cases (gharlan) +* minor #1624 fix invalid code in test cases (gharlan) +* minor #1625 Travis - switch to trusty (keradus) +* minor #1627 FixCommand - fix output (keradus) +* minor #1630 Pass along the exception code. (SpacePossum) +* minor #1632 Php Inspections (EA Extended): SCA for 1.12 (kalessil) +* minor #1633 Fix CS for project itself (keradus) +* minor #1634 Backport some minor changes from 2.x line (keradus) +* minor #1637 update PHP Coveralls (keradus) +* minor #1639 Revert "Travis - set dist to trusty" (keradus) +* minor #1641 AppVeyor/Travis - use GITHUB_OAUTH_TOKEN (keradus) +* minor #1642 AppVeyor - install dev deps as well (keradus) +* minor #1647 Deprecate non-default Configs and Finders (keradus) +* minor #1654 Split output to stderr and stdout (SpacePossum) +* minor #1660 update phpunit version (gharlan) +* minor #1663 DuplicateSemicolonFixer - Remove duplicate semicolons even if there are comments between those (SpacePossum) +* minor #1664 IncludeFixer - Add missing test case (SpacePossum) +* minor #1668 Code grooming (keradus) +* minor #1669 NativeFunctionCasingFixer - move to Symfony level (keradus) +* minor #1670 Backport Finder and Config classes from 2.x line (keradus) +* minor #1682 ElseifFixer - handle comments (SpacePossum) +* minor #1689 AbstractIntegrationTest - no need for single-char group and docs grooming (keradus) +* minor #1690 Integration tests - allow to not check priority, introduce IntegrationCase (keradus) +* minor #1701 Fixer - Renamed import alias (GrahamCampbell) +* minor #1708 Update composer.json requirements (keradus) +* minor #1734 Travis: Turn on linting (keradus) +* minor #1736 Integration tests - don't check priority for tests using short_tag fixer (keradus) +* minor #1739 NoTrailingWhitespaceInCommentFixer - move to PSR2 level (keradus) +* minor #1763 Deprecate ConfigInterface::getDir, ConfigInterface::setDir, Finder::setDir (keradus) +* minor #1777 NoTrailingWhitespaceInCommentFixer - fix parent class (keradus) +* minor #1816 PhpUnitDedicateAssertFixer - configuration is not required anymore (keradus) +* minor #1849 DocBlock - The category tag should be together with package (GrahamCampbell) +* minor #1870 Update README.rst (glensc) +* minor #1880 FixCommand - fix stdErr detection (SpacePossum) +* minor #1881 NoEmptyStatementFixer - handle anonymous classes correctly (gharlan) +* minor #1906 .php_cs - use no_useless_else rule (keradus) +* minor #1915 NoEmptyComment - move to Symfony level (SpacePossum) +* minor #1917 BracesFixer - fixed comment handling (gharlan) +* minor #1919 EmptyReturnFixer - move fixer outside of Symfony level (keradus) +* minor #2036 OrderedUseFixer - adjust tests (keradus) +* minor #2056 Travis - run nightly PHP (keradus) +* minor #2061 UnusedUseFixer and LineAfterNamespace - add new integration test (keradus) +* minor #2097 Add lambda tests for 7.0 and 7.1 (SpacePossum) +* minor #2111 .travis.yml - rename PHP 7.1 env (keradus) +* minor #2112 Fix 1.12 line (keradus) +* minor #2118 SilencedDeprecationErrorFixer - adjust level (keradus) +* minor #2132 composer.json - rename package name (keradus) +* minor #2133 Apply ordered_class_elements rule (keradus) +* minor #2138 composer.json - disallow to run on PHP 7.2+ (keradus) + +Changelog for v1.11.8 +--------------------- + +* bug #2143 ReadmeCommand - fix running command on phar file (keradus) +* minor #2129 Add .gitattributes to remove unneeded files (Slamdunk) +* minor #2141 Move phar building to PHP 5.6 job as newest box.phar is no longer working on 5.3 (keradus) + +Changelog for v1.11.7 +--------------------- + +* bug #2108 ShortArraySyntaxFixer, TernarySpacesFixer, UnalignEqualsFixer - fix priority bug (SpacePossum) +* bug #2092 ConcatWithoutSpacesFixer, OperatorsSpacesFixer - fix too many spaces, fix incorrect fixing of lines with comments (SpacePossum) + +Changelog for v1.11.6 +--------------------- + +* bug #2086 Braces - fix bug with comment in method prototype (keradus) +* bug #2077 SingleLineAfterImportsFixer - Do not remove lines between use cases (SpacePossum) +* bug #2079 TernarySpacesFixer - Remove multiple spaces (SpacePossum) +* bug #2087 Fixer - handle PHP7 Errors as well (keradus) +* bug #2072 LowercaseKeywordsFixer - handle CT_CLASS_CONSTANT (tgabi333) +* bug #2066 LineAfterNamespaceFixer - Handle close tag (SpacePossum) +* bug #2057 LineAfterNamespaceFixer - adding too much extra lines where namespace is last statement (keradus) +* bug #2059 OperatorsSpacesFixer - handle declare statement (keradus) +* bug #2060 UnusedUseFixer - fix handling whitespaces around removed import (keradus) +* minor #2071 ShortEchoTagFixer - allow to run tests on PHP 5.3 (keradus) + +Changelog for v1.11.5 +--------------------- + +* bug #2012 Properly build phar file for lowest supported PHP version (keradus) +* bug #2037 BracesFixer - add support for anonymous classes (keradus) +* bug #1989 Add support for PHP 7 namespaces (SpacePossum) +* bug #2019 Fixing newlines added after curly brace string index access (jaydiablo) +* bug #1840 [Bug] BracesFixer - Do add a line before close tag (SpacePossum) +* bug #1994 EchoToPrintFixer - Fix T_OPEN_TAG_WITH_ECHO on hhvm (keradus) +* bug #1970 Tokens - handle semi-reserved PHP 7 keywords (keradus) +* minor #2017 PHP7 integration tests (keradus) +* minor #1465 Bump supported HHVM version, improve ShortEchoTagFixer on HHVM (keradus) +* minor #1995 Rely on own phpunit, not one from CI service (keradus) + +Changelog for v1.11.4 +--------------------- + +* bug #1956 SelfUpdateCommand - don't update to non-stable version (keradus) +* bug #1963 Fix not wanted unneeded_control_parentheses fixer for clone (Soullivaneuh) +* bug #1960 Fix invalid test cases (keradus) +* bug #1939 BracesFixer - fix handling comment around control token (keradus) +* minor #1927 NewWithBracesFixer - remove invalid testcase (keradus) + +Changelog for v1.11.3 +--------------------- + +* bug #1868 NewWithBracesFixer - fix handling more neighbor tokens (keradus) +* bug #1893 BracesFixer - handle comments inside lambda function prototype (keradus) +* bug #1806 SelfAccessorFixer - skip anonymous classes (gharlan) +* bug #1813 BlanklineAfterOpenTagFixer, NoBlankLinesBeforeNamespaceFixer - fix priority (SpacePossum) +* minor #1807 Tokens - simplify isLambda() (gharlan) + +Changelog for v1.11.2 +--------------------- + +* bug #1776 EofEndingFixer - new line on end line comment is allowed (Slamdunk) +* bug #1775 FileCacheManager - ignore corrupted serialized data (keradus) +* bug #1769 FunctionDeclarationFixer - fix more cases (keradus) +* bug #1747 Fixer - Fix ordering of fixer when both level and custom fixers are used (SpacePossum) +* bug #1744 Fixer - fix rare situation when file was visited twice (keradus) +* bug #1710 LowercaseConstantFixer - Fix comment cases. (SpacePossum) +* bug #1711 FunctioncallSpaceFixer - do not touch function declarations. (SpacePossum) +* minor #1798 LintManager - meaningful tempnam (Slamdunk) +* minor #1759 UniqueFileIterator - performance improvement (GrahamCampbell) +* minor #1745 appveyor - fix build (keradus) + +Changelog for v1.11.1 +--------------------- + +* bug #1680 NewWithBracesFixer - End tags (SpacePossum) +* bug #1685 EmptyReturnFixer - Make independent of LowercaseConstantsFixer (SpacePossum) +* bug #1640 IntegrationTest - fix directory separator (keradus) +* bug #1595 ShortTagFixer - fix priority (keradus) +* bug #1576 SpacesBeforeSemicolonFixer - do not remove space before semicolon if that space is after a semicolon (SpacePossum) +* bug #1570 UnneededControlParenthesesFixer - fix test samples (keradus) +* minor #1653 Update license year (gharlan) + +Changelog for v1.11 +------------------- + +* feature #1550 Added UnneededControlParenthesesFixer (Soullivaneuh, keradus) +* feature #1532 Added ShortBoolCastFixer (SpacePossum) +* feature #1523 Added EchoToPrintFixer and PrintToEchoFixer (Soullivaneuh) +* feature #1552 Warn when running with xdebug extension (SpacePossum) +* feature #1484 Added ArrayElementNoSpaceBeforeCommaFixer and ArrayElementWhiteSpaceAfterCommaFixer (amarczuk) +* feature #1449 PhpUnitConstructFixer - Fix more use cases (SpacePossum) +* feature #1382 Added PhpdocTypesFixer (GrahamCampbell) +* feature #1384 Add integration tests (SpacePossum) +* feature #1349 Added FunctionTypehintSpaceFixer (keradus) +* minor #1562 Fix invalid PHP code samples in utests (SpacePossum) +* minor #1560 Fixed project name in xdebug warning (gharlan) +* minor #1545 Fix invalid PHP code samples in utests (SpacePossum) +* minor #1554 Alphabetically sort entries in .gitignore (GrahamCampbell) +* minor #1527 Refactor the way types work on annotations (GrahamCampbell) +* minor #1546 Update coding guide in cookbook (keradus) +* minor #1526 Support more annotations when fixing types in phpdoc (GrahamCampbell) +* minor #1535 clean ups (SpacePossum) +* minor #1510 Added Symfony 3.0 support (Ener-Getick) +* minor #1520 Code grooming (keradus) +* minor #1515 Support property, property-read and property-write tags (GrahamCampbell) +* minor #1488 Added more inline phpdoc tests (GrahamCampbell) +* minor #1496 Add docblock to AbstractFixerTestBase::makeTest (lmanzke) +* minor #1467 PhpdocShortDescriptionFixer - add support for Japanese sentence-ending characters (fritz-c) +* minor #1453 remove calling array_keys in foreach loops (keradus) +* minor #1448 Code grooming (keradus) +* minor #1437 Added import fixers integration test (GrahamCampbell) +* minor #1433 phpunit.xml.dist - disable gc (keradus) +* minor #1427 Change arounded to surrounded in README.rst (36degrees) +* minor #1420 AlignDoubleArrowFixer, AlignEqualsFixer - add integration tests (keradus) +* minor #1423 appveyor.yml - do not cache C:\tools, its internal forAppVeyor (keradus) +* minor #1400 appveyor.yml - add file (keradus) +* minor #1396 AbstractPhpdocTypesFixer - instance method should be called on instance (keradus) +* minor #1395 code grooming (keradus) +* minor #1393 boost .travis.yml file (keradus) +* minor #1372 Don't allow PHP 7 to fail (GrahamCampbell) +* minor #1332 PhpUnitConstructFixer - fix more functions (keradus) +* minor #1339 CONTRIBUTING.md - add link to PSR-5 (keradus) +* minor #1346 Core grooming (SpacePossum) +* minor #1328 Tokens: added typehint for Iterator elements (gharlan) + +Changelog for v1.10.3 +--------------------- + +* bug #1559 WhitespacyLinesFixer - fix bug cases (SpacePossum, keradus) +* bug #1541 Psr0Fixer - Ignore filenames that are a reserved keyword or predefined constant (SpacePossum) +* bug #1537 Psr0Fixer - ignore file without name or with name started by digit (keradus) +* bug #1516 FixCommand - fix wrong message for dry-run (SpacePossum) +* bug #1486 ExtraEmptyLinesFixer - Remove extra lines after comment lines too (SpacePossum) +* bug #1503 Psr0Fixer - fix case with comments lying around (GrahamCampbell) +* bug #1474 PhpdocToCommentFixer - fix not properly fixing for block right after namespace (GrahamCampbell) +* bug #1478 BracesFixer - do not remove empty lines after class opening (keradus) +* bug #1468 Add missing ConfigInterface::getHideProgress() (Eugene Leonovich, rybakit) +* bug #1466 Fix bad indent on align double arrow fixer (Soullivaneuh, keradus) +* bug #1479 Tokens - fix detection of short array (keradus) + +Changelog for v1.10.2 +--------------------- + +* bug #1461 PhpUnitConstructFixer - fix case when first argument is an expression (keradus) +* bug #1460 AlignDoubleArrowFixer - fix handling of nested arrays (Soullivaneuh, keradus) + +Changelog for v1.10.1 +--------------------- + +* bug #1424 Fixed the import fixer priorities (GrahamCampbell) +* bug #1444 OrderedUseFixer - fix next case (keradus) +* bug #1441 BracesFixer - fix next case (keradus) +* bug #1422 AlignDoubleArrowFixer - fix handling of nested array (SpacePossum) +* bug #1425 PhpdocInlineTagFixerTest - fix case when met invalid PHPDoc (keradus) +* bug #1419 AlignDoubleArrowFixer, AlignEqualsFixer - fix priorities (keradus) +* bug #1415 BlanklineAfterOpenTagFixer - Do not add a line break if there is one already. (SpacePossum) +* bug #1410 PhpdocIndentFixer - Fix for open tag (SpacePossum) +* bug #1401 PhpdocVarWithoutNameFixer - Fixed the var without name fixer for inline docs (keradus, GrahamCampbell) +* bug #1369 Fix not well-formed XML output (junichi11) +* bug #1356 Psr0Fixer - disallow run on StdinFileInfo (keradus) + +Changelog for v1.10 +------------------- + +* feature #1306 Added LogicalNotOperatorsWithSuccessorSpaceFixer (phansys) +* feature #1286 Added PhpUnitConstructFixer (keradus) +* feature #1316 Added PhpdocInlineTagFixer (SpacePossum, keradus) +* feature #1303 Added LogicalNotOperatorsWithSpacesFixer (phansys) +* feature #1279 Added PhpUnitStrictFixer (keradus) +* feature #1267 SingleQuoteFixer fix more use cases (SpacePossum) +* minor #1319 PhpUnitConstructFixer - fix performance and add to local .php_cs (keradus) +* minor #1280 Fix non-utf characters in docs (keradus) +* minor #1274 Cookbook - No change auto-test note (Soullivaneuh) + +Changelog for v1.9.3 +-------------------- + +* bug #1327 DocBlock\Tag - keep the case of tags (GrahamCampbell) + +Changelog for v1.9.2 +-------------------- + +* bug #1313 AlignDoubleArrowFixer - fix aligning after UTF8 chars (keradus) +* bug #1296 PhpdocScalarFixer - fix property annotation too (GrahamCampbell) +* bug #1299 WhitespacyLinesFixer - spaces on next valid line must not be fixed (Slamdunk) + +Changelog for v1.9.1 +-------------------- + +* bug #1288 TrimArraySpacesFixer - fix moving first comment (keradus) +* bug #1287 PhpdocParamsFixer - now works on any indentation level (keradus) +* bug #1278 Travis - fix PHP7 build (keradus) +* bug #1277 WhitespacyLinesFixer - stop changing non-whitespacy tokens (SpacePossum, SamBurns-awin, keradus) +* bug #1224 TrailingSpacesFixer - stop changing non-whitespacy tokens (SpacePossum, SamBurns-awin, keradus) +* bug #1266 FunctionCallSpaceFixer - better detection of function call (funivan) +* bug #1255 make sure some phpdoc fixers are run in right order (SpacePossum) + +Changelog for v1.9 +------------------ + +* feature #1097 Added ShortEchoTagFixer (vinkla) +* minor #1238 Fixed error handler to respect current error_reporting (JanJakes) +* minor #1234 Add class to exception message, use sprintf for exceptions (SpacePossum) +* minor #1210 set custom error handler for application run (keradus) +* minor #1214 Tokens::isMonolithicPhp - enhance performance (keradus) +* minor #1207 Update code documentation (keradus) +* minor #1202 Update IDE tool urls (keradus) +* minor #1195 PreIncrementFixer - move to Symfony level (gharlan) + +Changelog for v1.8.1 +-------------------- + +* bug #1193 EofEndingFixer - do not add an empty line at EOF if the PHP tags have been closed (SpacePossum) +* bug #1209 PhpdocParamsFixer - fix corrupting following custom annotation (keradus) +* bug #1205 BracesFixer - fix missing indentation fixes for class level (keradus) +* bug #1204 Tag - fix treating complex tag as simple PhpDoc tag (keradus) +* bug #1198 Tokens - fixed unary/binary operator check for type-hinted reference arguments (gharlan) +* bug #1201 Php4ConstructorFixer - fix invalid handling of subnamespaces (gharlan) +* minor #1221 Add more tests (SpacePossum) +* minor #1216 Tokens - Add unit test for array detection (SpacePossum) + +Changelog for v1.8 +------------------ + +* feature #1168 Added UnalignEqualsFixer (keradus) +* feature #1167 Added UnalignDoubleArrowFixer (keradus) +* bug #1169 ToolInfo - Fix way to find script dir (sp-ian-monge) +* minor #1181 composer.json - Update description (SpacePossum) +* minor #1180 create Tokens::overrideAt method (keradus) + +Changelog for v1.7.1 +-------------------- + +* bug #1165 BracesFixer - fix bug when comment is a first statement in control structure without braces (keradus) + +Changelog for v1.7 +------------------ + +* feature #1113 Added PreIncrementFixer (gharlan) +* feature #1144 Added PhpdocNoAccessFixer (GrahamCampbell) +* feature #1116 Added SelfAccessorFixer (gharlan) +* feature #1064 OperatorsSpacesFixer enhancements (gharlan) +* bug #1151 Prevent token collection corruption by fixers (stof, keradus) +* bug #1152 LintManager - fix handling of temporary file (keradus) +* bug #1139 NamespaceNoLeadingWhitespaceFixer - remove need for ctype extension (keradus) +* bug #1117 Tokens - fix iterator used with foreach by reference (keradus) +* minor #1148 code grooming (keradus) +* minor #1142 We are actually PSR-4, not PSR-0 (GrahamCampbell) +* minor #1131 Phpdocs and typos (SpacePossum) +* minor #1069 state min HHVM version (keradus) +* minor #1129 [DX] Help developers choose the right branch (SpacePossum) +* minor #1138 PhpClosingTagFixer - simplify flow, no need for loop (keradus) +* minor #1123 Reference mismatches fixed, SCA (kalessil) +* minor #1109 SingleQuoteFixer - made fixer more accurate (gharlan) +* minor #1110 code grooming (kalessil) + +Changelog for v1.6.2 +-------------------- + +* bug #1149 UnusedUseFixer - must be run before LineAfterNamespaceFixer, fix token collection corruption (keradus) +* minor #1145 AbstractLinesBeforeNamespaceFixer - fix docs for fixLinesBeforeNamespace (GrahamCampbell) + +Changelog for v1.6.1 +-------------------- + +* bug #1108 UnusedUseFixer - fix false positive when name is used as part of another namespace (gharlan) +* bug #1114 Fixed PhpdocParamsFixer with malformed doc block (gharlan) +* minor #1135 PhpdocTrimFixer - fix doc typo (localheinz) +* minor #1093 Travis - test lowest dependencies (boekkooi) + +Changelog for v1.6 +------------------ + +* feature #1089 Added NewlineAfterOpenTagFixer and BlanklineAfterOpenTagFixer (ceeram, keradus) +* feature #1090 Added TrimArraySpacesFixer (jaredh159, keradus) +* feature #1058 Added SingleQuoteFixer (gharlan) +* feature #1059 Added LongArraySyntaxFixer (gharlan) +* feature #1037 Added PhpdocScalarFixer (GrahamCampbell, keradus) +* feature #1028 Add ListCommasFixer (keradus) +* bug #1047 Utils::camelCaseToUnderscore - fix regexp (odin-delrio) +* minor #1073 ShortTagFixer enhancement (gharlan) +* minor #1079 Use LongArraySyntaxFixer for this repo (gharlan) +* minor #1070 Tokens::isMonolithicPhp - remove unused T_CLOSE_TAG search (keradus) +* minor #1049 OrderedUseFixer - grooming (keradus) + +Changelog for v1.5.2 +-------------------- + +* bug #1025 Fixer - ignore symlinks (kix) +* bug #1071 Psr0Fixer - fix bug for fixing file with long extension like .class.php (keradus) +* bug #1080 ShortTagFixer - fix false positive (gharlan) +* bug #1066 Php4ConstructorFixer - fix causing infinite recursion (mbeccati) +* bug #1056 VisibilityFixer - fix T_VAR with multiple props (localheinz, keradus) +* bug #1065 Php4ConstructorFixer - fix detection of a PHP4 parent constructor variant (mbeccati) +* bug #1060 Tokens::isShortArray: tests and bugfixes (gharlan) +* bug #1057 unused_use: fix false positive when name is only used as variable name (gharlan) + +Changelog for v1.5.1 +-------------------- + +* bug #1054 VisibilityFixer - fix var with array value assigned (localheinz, keradus) +* bug #1048 MultilineArrayTrailingCommaFixer, SingleArrayNoTrailingCommaFixer - using heredoc inside array not causing to treat it as multiline array (keradus) +* bug #1043 PhpdocToCommentFixer - also check other control structures, besides foreach (ceeram) +* bug #1045 OrderedUseFixer - fix namespace order for trailing digits (rusitschka) +* bug #1035 PhpdocToCommentFixer - Add static as valid keyword for structural element (ceeram) +* bug #1020 BracesFixer - fix missing braces for nested if elseif else (malengrin) +* minor #1036 Added php7 to travis build (fonsecas72) +* minor #1026 Fix typo in ShortArraySyntaxFixer (tommygnr) +* minor #1024 code grooming (keradus) + +Changelog for v1.5 +------------------ + +* feature #887 Added More Phpdoc Fixers (GrahamCampbell, keradus) +* feature #1002 Add HeaderCommentFixer (ajgarlag) +* feature #974 Add EregToPregFixer (mbeccati) +* feature #970 Added Php4ConstructorFixer (mbeccati) +* feature #997 Add PhpdocToCommentFixer (ceeram, keradus) +* feature #932 Add NoBlankLinesAfterClassOpeningFixer (ceeram) +* feature #879 Add SingleBlankLineBeforeNamespaceFixer and NoBlankLinesBeforeNamespaceFixer (GrahamCampbell) +* feature #860 Add single_line_after_imports fixer (ceeram) +* minor #1014 Fixed a few file headers (GrahamCampbell) +* minor #1011 Fix HHVM as it works different than PHP (keradus) +* minor #1010 Fix invalid UTF-8 char in docs (ajgarlag) +* minor #1003 Fix header comment in php files (ajgarlag) +* minor #1005 Add Utils::calculateBitmask method (keradus) +* minor #973 Add Tokens::findSequence (mbeccati) +* minor #991 Longer explanation of how to use blacklist (bmitch, networkscraper) +* minor #972 Add case sensitive option to the tokenizer (mbeccati) +* minor #986 Add benchmark script (dericofilho) +* minor #985 Fix typo in COOKBOOK-FIXERS.md (mattleff) +* minor #978 Token - fix docs (keradus) +* minor #957 Fix Fixers methods order (GrahamCampbell) +* minor #944 Enable caching of composer downloads on Travis (stof) +* minor #941 EncodingFixer - enhance tests (keradus) +* minor #938 Psr0Fixer - remove unneeded assignment (keradus) +* minor #936 FixerTest - test description consistency (keradus) +* minor #933 NoEmptyLinesAfterPhpdocsFixer - remove unneeded code, clarify description (ceeram) +* minor #934 StdinFileInfo::getFilename - Replace phpdoc with normal comment and add back empty line before return (ceeram) +* minor #927 Exclude the resources folder from coverage reports (GrahamCampbell) +* minor #926 Update Token::isGivenKind phpdoc (GrahamCampbell) +* minor #925 Improved AbstractFixerTestBase (GrahamCampbell) +* minor #922 AbstractFixerTestBase::makeTest - test if input is different than expected (keradus) +* minor #904 Refactoring Utils (GrahamCampbell) +* minor #901 Improved Readme Formatting (GrahamCampbell) +* minor #898 Tokens::getImportUseIndexes - simplify function (keradus) +* minor #897 phpunit.xml.dist - split testsuite (keradus) + +Changelog for v1.4.2 +-------------------- + +* bug #994 Fix detecting of short arrays (keradus) +* bug #995 DuplicateSemicolonFixer - ignore duplicated semicolons inside T_FOR (keradus) + +Changelog for v1.4.1 +-------------------- + +* bug #990 MultilineArrayTrailingCommaFixer - fix case with short array on return (keradus) +* bug #975 NoEmptyLinesAfterPhpdocsFixer - fix only when documentation documents sth (keradus) +* bug #976 PhpdocIndentFixer - fix error when there is a comment between docblock and next meaningful token (keradus, ceeram) + +Changelog for v1.4 +------------------ + +* feature #841 PhpdocParamsFixer: added aligning var/type annotations (GrahamCampbell) +* bug #965 Fix detection of lambda function that returns a reference (keradus) +* bug #962 PhpdocIndentFixer - fix bug when documentation is on the end of braces block (keradus) +* bug #961 Fixer - fix handling of empty file (keradus) +* bug #960 IncludeFixer - fix bug when include is part of condition statement (keradus) +* bug #954 AlignDoubleArrowFixer - fix new buggy case (keradus) +* bug #955 ParenthesisFixer - fix case with list call with trailing comma (keradus) +* bug #950 Tokens::isLambda - fix detection near comments (keradus) +* bug #951 Tokens::getImportUseIndexes - fix detection near comments (keradus) +* bug #949 Tokens::isShortArray - fix detection near comments (keradus) +* bug #948 NewWithBracesFixer - fix case with multidimensional array (keradus) +* bug #945 Skip files containing __halt_compiler() on PHP 5.3 (stof) +* bug #946 BracesFixer - fix typo in exception name (keradus) +* bug #940 Tokens::setCode - apply missing transformation (keradus) +* bug #908 BracesFixer - fix invalid inserting brace for control structure without brace and lambda inside of it (keradus) +* bug #903 NoEmptyLinesAfterPhpdocsFixer - fix bug with Windows style lines (GrahamCampbell) +* bug #895 [PSR-2] Preserve blank line after control structure opening brace (marcaube) +* bug #892 Fixed the double arrow multiline whitespace fixer (GrahamCampbell) +* bug #874 BracesFixer - fix bug of removing empty lines after class' opening { (ceeram) +* bug #868 BracesFixer - fix missing braces when statement is not followed by ; (keradus) +* bug #861 Updated PhpdocParamsFixer not to change line endings (keradus, GrahamCampbell) +* bug #837 FixCommand - stop corrupting xml/json format (keradus) +* bug #846 Made phpdoc_params run after phpdoc_indent (GrahamCampbell) +* bug #834 Correctly handle tab indentation (ceeram) +* bug #822 PhpdocIndentFixer - Ignore inline docblocks (ceeram) +* bug #813 MultilineArrayTrailingCommaFixer - do not move array end to new line (keradus) +* bug #817 LowercaseConstantsFixer - ignore class' constants TRUE/FALSE/NULL (keradus) +* bug #821 JoinFunctionFixer - stop changing declaration method name (ceeram) +* minor #963 State the minimum version of PHPUnit in CONTRIBUTING.md (SpacePossum) +* minor #943 Improve the cookbook to use relative links (stof) +* minor #921 Add changelog file (keradus) +* minor #909 BracesFixerTest - no \n line in \r\n test (keradus) +* minor #864 Added NoEmptyLinesAfterPhpdocsFixer (GrahamCampbell) +* minor #871 Added missing author (GrahamCampbell) +* minor #852 Fixed the coveralls version constraint (GrahamCampbell) +* minor #863 Tweaked testRetainsNewLineCharacters (GrahamCampbell) +* minor #849 Removed old alias (GrahamCampbell) +* minor #843 integer should be int (GrahamCampbell) +* minor #830 Remove whitespace before opening tag (ceeram) +* minor #835 code grooming (keradus) +* minor #828 PhpdocIndentFixerTest - code grooming (keradus) +* minor #827 UnusedUseFixer - code grooming (keradus) +* minor #825 improve code coverage (keradus) +* minor #810 improve code coverage (keradus) +* minor #811 ShortArraySyntaxFixer - remove not needed if statement (keradus) + +Changelog for v1.3 +------------------ + +* feature #790 Add docblock indent fixer (ceeram) +* feature #771 Add JoinFunctionFixer (keradus) +* bug #798 Add DynamicVarBrace Transformer for properly handling ${$foo} syntax (keradus) +* bug #796 LowercaseConstantsFixer - rewrite to handle new test cases (keradus) +* bug #789 T_CASE is not succeeded by parentheses (dericofilho) +* minor #814 Minor improvements to the phpdoc_params fixer (GrahamCampbell) +* minor #815 Minor fixes (GrahamCampbell) +* minor #782 Cookbook on how to make a new fixer (dericofilho) +* minor #806 Fix Tokens::detectBlockType call (keradus) +* minor #758 travis - disable sudo (keradus) +* minor #808 Tokens - remove commented code (keradus) +* minor #802 Address Sensiolabs Insight's warning of code cloning. (dericofilho) +* minor #803 README.rst - fix \` into \`\` (keradus) + +Changelog for v1.2 +------------------ + +* feature #706 Remove lead slash (dericofilho) +* feature #740 Add EmptyReturnFixer (GrahamCampbell) +* bug #775 PhpClosingTagFixer - fix case with T_OPEN_TAG_WITH_ECHO (keradus) +* bug #756 Fix broken cases for AlignDoubleArrowFixer (dericofilho) +* bug #763 MethodArgumentSpaceFixer - fix receiving data in list context with omitted values (keradus) +* bug #759 Fix Tokens::isArrayMultiLine (stof, keradus) +* bug #754 LowercaseKeywordsFixer - __HALT_COMPILER must not be lowercased (keradus) +* bug #753 Fix for double arrow misalignment in deeply nested arrays. (dericofilho) +* bug #752 OrderedUseFixer should be case-insensitive (rusitschka) +* minor #779 Fixed a docblock type (GrahamCampbell) +* minor #765 Typehinting in FileCacheManager, remove unused variable in Tokens (keradus) +* minor #764 SelfUpdateCommand - get local version only if remote version was successfully obtained (keradus) +* minor #761 align => (keradus) +* minor #757 Some minor code simplify and extra test (keradus) +* minor #713 Download php-cs-fixer.phar without sudo (michaelsauter) +* minor #742 Various Minor Improvements (GrahamCampbell) + +Changelog for v1.1 +------------------ + +* feature #749 remove the --no-progress option (replaced by the standard -v) (fabpot, keradus) +* feature #728 AlignDoubleArrowFixer - standardize whitespace after => (keradus) +* feature #647 Add DoubleArrowMultilineWhitespacesFixer (dericofilho, keradus) +* bug #746 SpacesBeforeSemicolonFixerTest - fix bug with semicolon after comment (keradus) +* bug #741 Fix caching when composer is installed in custom path (cmodijk) +* bug #725 DuplicateSemicolonFixer - fix clearing whitespace after duplicated semicolon (keradus) +* bug #730 Cache busting when fixers list changes (Seldaek) +* bug #722 Fix lint for STDIN-files (ossinkine) +* bug #715 TrailingSpacesFixer - fix bug with french UTF-8 chars (keradus) +* bug #718 Fix package name for composer cache (Seldaek) +* bug #711 correct vendor name (keradus) +* minor #745 Show progress by default and allow to disable it (keradus) +* minor #731 Add a way to disable all default filters and really provide a whitelist (Seldaek) +* minor #737 Extract tool info into new class, self-update command works now only for PHAR version (keradus) +* minor #739 fix fabbot issues (keradus) +* minor #726 update CONTRIBUTING.md for installing dependencies (keradus) +* minor #736 Fix fabbot issues (GrahamCampbell) +* minor #727 Fixed typos (pborreli) +* minor #719 Add update instructions for composer and caching docs (Seldaek) + +Changelog for v1.0 +------------------ + +First stable release. diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/CONTRIBUTING.md b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/CONTRIBUTING.md new file mode 100644 index 00000000..2362e7e2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/CONTRIBUTING.md @@ -0,0 +1,93 @@ +# Contributions Are Welcome! + +If you need any help, don't hesitate to ask the community using [GitHub Discussions](https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/discussions/categories/q-a). + +## Glossary + +### Fixer + +A *fixer* is a class that tries to fix a single code style issue (a ``Fixer`` class must implement ``FixerInterface``). + +### Ruleset + +A *ruleset* is a collection of rules (*fixers*) that may be referenced in the config file similarly to a single *fixer*. When you work on existing fixer please keep in mind it can be a part of a *ruleset*(s) and changes may affect many users. When working on new *fixer* please consider if it should be added to some *ruleset*(s). + +### Config + +A *config* knows about the code style rules and the files and directories that must be scanned by the tool when run in the context of your project. It is useful for projects that follow a well-known directory structures, but the tool is not limited to any specific structure, and you can configure it in a very flexible way. + +## How to contribute + +ℹ️ **IMPORTANT**: before contributing with really significant changes that require a lot of effort or are crucial from this tool's architecture perspective, please open [RFC on GitHub Discussion](https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/discussions/categories/rfc). The development effort should start only after the proposal is discussed and the approach aligned. + +### Development + +* [Fork](https://help.github.com/articles/fork-a-repo/) this repository. You can use native Git approach or use [`gh` CLI tool](https://cli.github.com/). +* Create new branch on top of the latest revision of `master` branch (if you already had project locally, then make sure to update this branch before going to next steps). It's good when branch's name reflects intent of the changes, but this is not strict requirement since pull request provides description of the change. However, with good branch naming it's easier to work on multiple changes simultaneously. +* Install dependencies by running `composer update` (since project does not contain `composer.lock` it's better to ensure latest versions of packages by running `update` command instead of `install`). +* Make changes. Please remember that **all** changes have to be covered by tests. + * if you work on a bug fix, please start with reproducing the problem by adding failing test case(s). When you have failing test case(s), you can [create pull request](#opening-a-pull-request) just to reproduce fail in the CI. Then you can provide fix _in the subsequent commits_, it will make code review easier. It's allowed to modify existing test cases in bug fix pull request, but *only if* current behavior is proved to be invalid. + * if you work on existing fixers then don't change existing test cases, because these are contract between the maintainers and users (they ensure how tool works). Add new test cases that cover provided changes - preferred way of defining test cases is with [data provider](https://docs.phpunit.de/en/10.0/writing-tests-for-phpunit.html#data-providers) which uses `yield` with proper case description as a key (e.g. `yield 'Some specific scenario' => ['some', 'example', 'data'];`). Codebase may still contain test cases in different format, and it's totally acceptable to use `yield` approach next to existing `return` usages. +* Update documentation: `composer docs`. This requires the highest version of PHP supported by PHP CS Fixer. If it is not installed on your system, you can run it in a Docker container instead: `docker compose run php-8.2 php dev-tools/doc.php`. +* Run QA suite: `composer qa`. +* Fix project itself (if needed): `composer cs:fix`. + +### Opening a [pull request](https://help.github.com/articles/about-pull-requests/) + +You can do some things to increase the chance that your pull request is accepted without communication ping-pong between you and the reviewers: + +* Submit [single](https://en.wikipedia.org/wiki/Single-responsibility_principle) pull request per fix or feature. +* Don't amend commits because it makes review rounds harder - all commits from your branch will be squashed (without commit messages) during merge, so you can treat pull request as a playground, without keeping everything tidy at any point. +* If your changes are not up-to-date, [rebase](https://git-scm.com/docs/git-rebase) your branch onto the parent branch. Do it regularly whenever your branch is behind `master` branch, that will eliminate risk of problems after the merge. +* Follow the conventions used in the project. +* Remember about tests and documentation. +* Don't bump `PhpCsFixer\Console\Application::VERSION`, it's done during release. + +## Working With Docker + +This project provides a Docker setup that allows working on it using any of the PHP versions supported by the tool. + +To use it, you first need to install [Docker](https://docs.docker.com/get-docker/) ([Docker Compose](https://docs.docker.com/compose/) is a built-in plugin of the main tool). + +Next, copy [`compose.override.dist.yaml`](./compose.override.dist.yaml) to `compose.override.yaml` and edit it to your needs. The relevant parameters that might require some tweaking have comments to help you. + +You can then build the images: + +```console +docker compose build --parallel +``` + +Now you can run commands needed to work on the project. For example, say you want to run PHPUnit tests on PHP 8.2: + +```console +docker compose run php-8.2 vendor/bin/phpunit +``` + +Sometimes it can be more convenient to have a shell inside the container: + +```console +docker compose run php-7.4 sh +/app vendor/bin/phpunit +``` + +The images come with an [`xdebug` script](github.com/julienfalque/xdebug/) that allows running any PHP command with Xdebug enabled to help debug problems. + +```console +docker compose run php-8.2 xdebug vendor/bin/phpunit +``` + +If you're using PhpStorm, you need to create a [server](https://www.jetbrains.com/help/phpstorm/servers.html) with a name that matches the `PHP_IDE_CONFIG` environment variable defined in the Docker Compose configuration files, which is `php-cs-fixer` by default. + +All images use port 9003 for debug connections. + +## Making New Fixers + +There is a [cookbook](doc/cookbook_fixers.rst) with basic instructions on how to build a new fixer. Consider reading it before opening a PR. + +## Project's Standards + +* [PSR-1: Basic Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md) +* [PSR-2: Coding Style Guide](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) +* [PSR-4: Autoloading Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md) +* [PSR-5: PHPDoc (draft)](https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md) +* [Symfony Coding Standards](https://symfony.com/doc/current/contributing/code/standards.html) diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/LICENSE b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/LICENSE new file mode 100644 index 00000000..871def02 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012+ Fabien Potencier, Dariusz Rumiński + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/README.md b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/README.md new file mode 100644 index 00000000..8ad8cf35 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/README.md @@ -0,0 +1,95 @@ +

+ + PHP CS Fixer logo + +

+ +PHP Coding Standards Fixer +========================== + +The PHP Coding Standards Fixer (PHP CS Fixer) tool fixes your code to follow standards; +whether you want to follow PHP coding standards as defined in the PSR-1, PSR-2, etc., +or other community driven ones like the Symfony one. +You can **also** define your (team's) style through configuration. + +It can modernize your code (like converting the ``pow`` function to the ``**`` operator on PHP 5.6) +and (micro) optimize it. + +If you are already using a linter to identify coding standards problems in your +code, you know that fixing them by hand is tedious, especially on large +projects. This tool does not only detect them, but also fixes them for you. + +## Supported PHP Versions + +* PHP 7.4 +* PHP 8.0 (except PHP 8.0.0 due to [bug in PHP tokenizer](https://bugs.php.net/bug.php?id=80462)) +* PHP 8.1 +* PHP 8.2 +* PHP 8.3 + +> **Note** +> Each new PHP version requires a huge effort to support the new syntax. +> That's why the latest PHP version might not be supported yet. If you need it, +> please, consider supporting the project in any convenient way, for example +> with code contribution or reviewing existing PRs. To run PHP CS Fixer on yet +> unsupported versions "at your own risk" - leverage the +> [PHP_CS_FIXER_IGNORE_ENV](./doc/usage.rst#environment-options). + +## Documentation + +### Installation + +The recommended way to install PHP CS Fixer is to use [Composer](https://getcomposer.org/download/) +in a dedicated `composer.json` file in your project, for example in the +`tools/php-cs-fixer` directory: + +```console +mkdir -p tools/php-cs-fixer +composer require --working-dir=tools/php-cs-fixer friendsofphp/php-cs-fixer +``` + +Or using the main `composer.json`: +```console +composer require --dev friendsofphp/php-cs-fixer +``` + +For more details and other installation methods, see +[installation instructions](./doc/installation.rst). + +### Usage + +Assuming you installed PHP CS Fixer as instructed above, you can run the +following command to fix the files PHP files in the `src` directory: + +```console +tools/php-cs-fixer/vendor/bin/php-cs-fixer fix src +``` + +See [usage](./doc/usage.rst), list of [built-in rules](./doc/rules/index.rst), list of [rule sets](./doc/ruleSets/index.rst) +and [configuration file](./doc/config.rst) documentation for more details. + +If you need to apply code styles that are not supported by the tool, you can +[create custom rules](./doc/custom_rules.rst). + +## Editor Integration + +Dedicated plugins exist for: + +* [NetBeans](https://plugins.netbeans.apache.org/catalogue/?id=36) +* [PhpStorm](https://www.jetbrains.com/help/phpstorm/using-php-cs-fixer.html) +* [Sublime Text](https://github.com/benmatselby/sublime-phpcs) +* [Vim](https://github.com/stephpy/vim-php-cs-fixer) +* [VS Code](https://github.com/junstyle/vscode-php-cs-fixer) + +## Community + +The PHP CS Fixer is maintained on GitHub at https://github.com/PHP-CS-Fixer/PHP-CS-Fixer. +Bug reports and ideas about new features are welcome there. + +You can reach us in the [GitHub Discussions](https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/discussions/) regarding the +project, configuration, possible improvements, ideas and questions. Please visit us there! + +## Contribute + +The tool comes with quite a few built-in fixers, but everyone is more than +welcome to [contribute](CONTRIBUTING.md) more of them. diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/UPGRADE-v3.md b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/UPGRADE-v3.md new file mode 100644 index 00000000..00e0a9c5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/UPGRADE-v3.md @@ -0,0 +1,167 @@ +UPGRADE GUIDE FROM 2.x to 3.0 +============================= + +This is guide for upgrade from version 2.x to 3.0 for using the CLI tool. + +*Before following this guide, install [v2.19](https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/releases/tag/v2.19.0) and run in verbose mode (`php-cs-fixer fix -v`) or in future mode (`PHP_CS_FIXER_FUTURE_MODE=1 php-cs-fixer fix`) to identify deprecations and fix them first.* + +Rename of files +--------------- + +| 2.x | 3.0 | Description | +| ---------------- | ------------------------ | -------------------------------------- | +| `.php_cs` | `.php-cs-fixer.php` | Configuration file (local) | +| `.php_cs.dist` | `.php-cs-fixer.dist.php` | Configuration file (to be distributed) | +| `.php_cs.cache` | `.php-cs-fixer.cache` | Cache file | + +CLI options +----------- + +| 2.x | 3.0 | Description | Note | +| ---------------- | --------------- | ----------------------------------------------- | -------------------------------------- | +| --diff-format | | Type of differ | Option was removed, all diffs are now | +| | | | `udiff` | +| --show-progress | --show-progress | Type of progress indicator | Allowed values were modified: | +| | | | `run-in` and `estimating` was removed, | +| | | | `estimating-max` was renamed to `dots` | +| --rules | --rules | Default value changed from @PSR2 to @PSR12 | | +| --config --rules | | | No longer allowed to pass both | + +Changes to rules +---------------- + +### Renamed rules + +Old name | New name | Note +-------- | -------- | ---- +`blank_line_before_return` | `blank_line_before_statement` | use configuration `['statements' => ['return']]` +`final_static_access` | `self_static_accessor` | +`hash_to_slash_comment` | `single_line_comment_style` | use configuration `['comment_types' => ['hash']]` +`lowercase_constants` | `constant_case` | use configuration `['case' => 'lower']` +`method_separation` | `class_attributes_separation` | use configuration `['elements' => ['method']]` +`no_extra_consecutive_blank_lines` | `no_extra_blank_lines` | +`no_multiline_whitespace_before_semicolons` | `multiline_whitespace_before_semicolons` | +`no_short_echo_tag` | `echo_tag_syntax` | use configuration `['format' => 'long']` +`php_unit_ordered_covers` | `phpdoc_order_by_value` | use configuration `['annotations' => [ 'covers' ]]` +`phpdoc_inline_tag` | `general_phpdoc_tag_rename`, `phpdoc_inline_tag_normalizer` and `phpdoc_tag_type` | +`pre_increment` | `increment_style` | use configuration `['style' => 'pre']` +`psr0` | `psr_autoloading` | use configuration `['dir' => x ]` +`psr4` | `psr_autoloading` | +`silenced_deprecation_error` | `error_suppression` | +`trailing_comma_in_multiline_array` | `trailing_comma_in_multiline` | use configuration `['elements' => ['arrays']]` + +### Removed rootless configuration + +Rule | Root option | Note +------------------------------------ | -------------- | ---- +`general_phpdoc_annotation_remove` | `annotations` +`no_extra_consecutive_blank_lines` | `tokens` +`no_spaces_around_offset` | `positions` +`no_unneeded_control_parentheses` | `statements` +`ordered_class_elements` | `order` +`php_unit_construct` | `assertions` +`php_unit_dedicate_assert` | `target` | root option works differently than rootless configuration +`php_unit_strict` | `assertions` +`phpdoc_no_alias_tag` | `replacements` +`phpdoc_return_self_reference` | `replacements` +`random_api_migration` | `replacements` +`single_class_element_per_statement` | `elements` +`visibility_required` | `elements` + +### Changed options + +Rule | Option | Change +---- | ------ | ------ +`binary_operator_spaces` | `align_double_arrow` | option was removed, use `operators` instead +`binary_operator_spaces` | `align_equals` | option was removed use `operators` instead +`blank_line_before_statement` | `statements: die` | option `die` was removed from `statements`, use `exit` instead +`class_attributes_separation` | `elements` | option does no longer accept flat array as a value, use map instead +`class_definition` | `multiLineExtendsEachSingleLine` | option was renamed to `multi_line_extends_each_single_line` +`class_definition` | `singleItemSingleLine` | option was renamed to `single_item_single_line` +`class_definition` | `singleLine` | option was renamed to `single_line` +`doctrine_annotation_spaces` | `around_argument_assignments` | option was removed, use `before_argument_assignments` and `after_argument_assignments` instead +`doctrine_annotation_spaces` | `around_array_assignments` | option was removed, use `after_array_assignments_colon`, `after_array_assignments_equals`, `before_array_assignments_colon` and `before_array_assignments_equals` instead +`final_internal_class` | `annotation-black-list` | option was renamed, use `annotation_exclude` +`final_internal_class` | `annotation-white-list` | option was renamed, use `annotation_include` +`final_internal_class` | `consider-absent-docblock-as-internal-class` | option was renamed, use `consider_absent_docblock_as_internal_class` +`header_comment` | `commentType` | option was renamed to `comment_type` +`is_null` | `use_yoda_style` | option was removed, use `yoda_style` rule instead +`no_extra_consecutive_blank_lines` | `tokens` | one of possible values, `useTrait`, was renamed to `use_trait` +`ordered_class_elements` | `sortAlgorithm` | option was renamed, use `sort_algorithm` instead +`ordered_imports` | `importsOrder` | option was renamed, use `imports_order` +`ordered_imports` | `sortAlgorithm` | option was renamed, use `sort_algorithm` +`php_unit_dedicate_assert` | `functions` | option was removed, use `target` instead +`php_unit_test_annotation` | `case` | option was removed, use `php_unit_method_casing` rule instead + +### Changed default values of options + +Rule | Option | Old value | New value +---- | ---- | ---- | ---- +`array_syntax` | `syntax` | `'long'` | `'short'` +`function_to_constant` | `functions` | `['get_class', 'php_sapi_name', 'phpversion', 'pi']` | `['get_called_class', 'get_class', 'php_sapi_name', 'phpversion', 'pi']` +`list_syntax` | `syntax` | `'long'` | `'short'` +`method_argument_space` | `on_multiline` | `'ignore'` | `'ensure_fully_multiline'` +`native_constant_invocation` | `strict` | `false` | `true` +`native_function_casing` | `include` | `'@internal'` | `'@compiler_optimized'` +`native_function_invocation` | `include` | `'@internal'` | `'@compiler_optimized'` +`native_function_invocation` | `strict` | `false` | `true` +`non_printable_character` | `use_escape_sequences_in_strings` | `false` | `true` (when running on PHP 7.0 and up) +`php_unit_dedicate_assert` | `target` | `'5.0'` | `'newest'` +`phpdoc_align` | `tags` | `['param', 'return', 'throws', 'type', 'var']` | `['method', 'param', 'property', 'return', 'throws', 'type', 'var']` +`phpdoc_scalar` | `types` | `['boolean', 'double', 'integer', 'real', 'str']` | `['boolean', 'callback', 'double', 'integer', 'real', 'str']` + +### Removed rule sets + +Rule set | Note +-------- | ---- +`@PHP56Migration` | was empty + +### Rule behavior changes + +- `no_unused_imports` now runs all files defined in the configuration (used to exclude some hardcoded directories) + +### Various + +- `udiff` output now includes the file name in the output (if applicable) + +Code BC changes +=============== + +### Removed; various + +- class `AbstractAlignFixerHelper` has been removed +- class `AccessibleObject` has been removed +- class `AlignDoubleArrowFixerHelper` has been removed +- class `AlignEqualsFixerHelper` has been removed +- class `FixerConfigurationResolverRootless` has been removed +- `HeaderCommentFixer` deprecated properties have been removed +- `MethodArgumentSpaceFixer` deprecated methods have been removed +- `NoMixedEchoPrintFixer` the property `$defaultConfig` has been removed +- class `Tokens`, the following methods has been removed: + - `current()` + - `key()` + - `next()` + - `rewind()` + - `valid()` +- namespace `PhpCsFixer\Test\` and each class in it has been removed, as it served pure development purpose and should not be part of production code - reach out to community if you are willing to help building dev package + +### Interface changes + +- `ConfigurableFixerInterface` has been updated +- `ConfigurationDefinitionFixerInterface` has been removed in favor of the updated `ConfigurableFixerInterface` +- `DefinedFixerInterface` has been removed, related methods are now part of the updated `FixerInterface` interface +- `DifferInterface` has been updated +- `FixerInterface` interface has been updated +- `PhpCsFixer\RuleSetInterface` has been removed in favor of `\PhpCsFixer\RuleSet\RuleSetInterface` + +### BC breaks; various + +- class `Token` is now `final` +- class `Tokens` is now `final` +- method `create` of class `Config` has been removed, [use the constructor](./doc/config.rst) +- method `create` of class `RuleSet` has been removed, [use the constructor](./doc/custom_rules.rst) + +### BC breaks; common internal classes + +- method `getClassyElements` of class `TokensAnalyzer` parameter `$returnTraitsImports` has been removed; now always returns trait import information +- method `getSetDefinitionNames` of class `RuleSet` has been removed, use `RuleSets::getSetDefinitionNames()` diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/ci-integration.sh b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/ci-integration.sh new file mode 100644 index 00000000..6ede4fd5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/ci-integration.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu + +IFS=' +' +CHANGED_FILES=$(git diff --name-only --diff-filter=ACMRTUXB "${COMMIT_RANGE}") +if ! echo "${CHANGED_FILES}" | grep -qE "^(\\.php-cs-fixer(\\.dist)?\\.php|composer\\.lock)$"; then EXTRA_ARGS=$(printf -- '--path-mode=intersection\n--\n%s' "${CHANGED_FILES}"); else EXTRA_ARGS=''; fi +vendor/bin/php-cs-fixer check --config=.php-cs-fixer.dist.php -v --stop-on-violation --using-cache=no ${EXTRA_ARGS} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/composer.json b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/composer.json new file mode 100644 index 00000000..dd900585 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/composer.json @@ -0,0 +1,169 @@ +{ + "name": "friendsofphp/php-cs-fixer", + "description": "A tool to automatically fix PHP code style", + "license": "MIT", + "type": "application", + "keywords": [ + "fixer", + "standards", + "static analysis", + "static code analysis" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Dariusz Rumiński", + "email": "dariusz.ruminski@gmail.com" + } + ], + "require": { + "php": "^7.4 || ^8.0", + "ext-json": "*", + "ext-tokenizer": "*", + "composer/semver": "^3.4", + "composer/xdebug-handler": "^3.0.3", + "sebastian/diff": "^4.0 || ^5.0", + "symfony/console": "^5.4 || ^6.0 || ^7.0", + "symfony/event-dispatcher": "^5.4 || ^6.0 || ^7.0", + "symfony/filesystem": "^5.4 || ^6.0 || ^7.0", + "symfony/finder": "^5.4 || ^6.0 || ^7.0", + "symfony/options-resolver": "^5.4 || ^6.0 || ^7.0", + "symfony/polyfill-mbstring": "^1.28", + "symfony/polyfill-php80": "^1.28", + "symfony/polyfill-php81": "^1.28", + "symfony/process": "^5.4 || ^6.0 || ^7.0", + "symfony/stopwatch": "^5.4 || ^6.0 || ^7.0" + }, + "require-dev": { + "facile-it/paraunit": "^1.3 || ^2.0", + "justinrainbow/json-schema": "^5.2", + "keradus/cli-executor": "^2.1", + "mikey179/vfsstream": "^1.6.11", + "php-coveralls/php-coveralls": "^2.7", + "php-cs-fixer/accessible-object": "^1.1", + "php-cs-fixer/phpunit-constraint-isidenticalstring": "^1.4", + "php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "^1.4", + "phpspec/prophecy": "^1.17", + "phpspec/prophecy-phpunit": "^2.0", + "phpunit/phpunit": "^9.6", + "symfony/phpunit-bridge": "^6.3.8 || ^7.0", + "symfony/yaml": "^5.4 || ^6.0 || ^7.0" + }, + "suggest": { + "ext-dom": "For handling output formats in XML", + "ext-mbstring": "For handling non-UTF8 characters." + }, + "autoload": { + "psr-4": { + "PhpCsFixer\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "PhpCsFixer\\Tests\\": "tests/" + } + }, + "bin": [ + "php-cs-fixer" + ], + "config": { + "allow-plugins": { + "ergebnis/composer-normalize": true, + "infection/extension-installer": false + }, + "prefer-stable": true, + "sort-packages": true + }, + "scripts": { + "post-autoload-dump": [ + "@install-tools" + ], + "auto-review": [ + "Composer\\Config::disableProcessTimeout", + "paraunit run --testsuite auto-review" + ], + "cs:check": "@php php-cs-fixer check --diff", + "cs:fix": "@php php-cs-fixer fix", + "cs:fix:parallel": "echo '🔍 Will run in batches of 50 files.'; if [[ -f .php-cs-fixer.php ]]; then FIXER_CONFIG=.php-cs-fixer.php; else FIXER_CONFIG=.php-cs-fixer.dist.php; fi; php php-cs-fixer list-files --config=$FIXER_CONFIG | xargs -n 50 -P 8 php php-cs-fixer fix --config=$FIXER_CONFIG --path-mode intersection 2> /dev/null", + "docs": "@php dev-tools/doc.php", + "install-tools": "@composer --working-dir=dev-tools install", + "mess-detector": "@php dev-tools/vendor/bin/phpmd . ansi dev-tools/mess-detector/phpmd.xml --exclude vendor/*,dev-tools/vendor/*,dev-tools/phpstan/*,tests/Fixtures/*", + "normalize": [ + "@composer normalize --working-dir=dev-tools --dry-run ../composer.json", + "@composer normalize --working-dir=dev-tools --dry-run composer.json" + ], + "phpstan": "@php -d memory_limit=512M dev-tools/vendor/bin/phpstan analyse", + "phpstan:baseline": "@php -d memory_limit=512M dev-tools/vendor/bin/phpstan analyse --generate-baseline=./dev-tools/phpstan/baseline.php", + "qa": "@quality-assurance", + "quality-assurance": [ + "Composer\\Config::disableProcessTimeout", + "@install-tools --quiet", + "@self-check", + "@static-analysis", + "@test" + ], + "require-checker": "@php dev-tools/vendor/bin/composer-require-checker check composer.json --config-file .composer-require-checker.json", + "sa": "@static-analysis", + "self-check": [ + "./dev-tools/check_file_permissions.sh", + "./dev-tools/check_trailing_spaces.sh", + "@normalize", + "@require-checker", + "@auto-review" + ], + "static-analysis": [ + "@cs:check", + "@phpstan", + "@mess-detector" + ], + "test": "@test:all", + "test:all": [ + "@test:unit", + "@test:integration" + ], + "test:coverage": [ + "Composer\\Config::disableProcessTimeout", + "paraunit coverage --testsuite unit --exclude-group covers-nothing" + ], + "test:integration": [ + "Composer\\Config::disableProcessTimeout", + "paraunit run --testsuite integration" + ], + "test:smoke": [ + "Composer\\Config::disableProcessTimeout", + "paraunit run --testsuite smoke" + ], + "test:unit": [ + "Composer\\Config::disableProcessTimeout", + "paraunit run --testsuite unit" + ] + }, + "scripts-descriptions": { + "auto-review": "Execute Auto-review", + "cs:check": "Check coding standards", + "cs:fix": "Fix coding standards", + "cs:fix:parallel": "Fix coding standards in naive parallel mode (using xargs)", + "docs": "Regenerate docs", + "install-tools": "Install DEV tools", + "mess-detector": "Analyse code with Mess Detector", + "normalize": "Run normalization for composer.json files", + "phpstan": "Run PHPStan analysis", + "phpstan:baseline": "Dump PHPStan baseline file - use only for updating, do not add new errors when possible", + "post-autoload-dump": "Run additional tasks after installing/updating main dependencies", + "qa": "Alias for 'quality-assurance'", + "quality-assurance": "Run QA suite", + "require-checker": "Verifies if codebase does not contain soft dependencies", + "sa": "Alias for 'static-analysis'", + "self-check": "Run set of self-checks ensuring repository's validity", + "static-analysis": "Run static analysis", + "test": "Alias for 'test:all'", + "test:all": "Run Unit and Integration tests (but *NOT* Smoke tests)", + "test:coverage": "Run tests that provide code coverage", + "test:integration": "Run Integration tests", + "test:smoke": "Run Smoke tests", + "test:unit": "Run Unit tests" + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/feature-or-bug.rst b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/feature-or-bug.rst new file mode 100644 index 00000000..e5959422 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/feature-or-bug.rst @@ -0,0 +1,24 @@ +========================== +Is it a feature or a bug ? +========================== + +Sometimes it's a bit tricky to define if given change proposal or change request is adding new feature or fixing existing issue. This document is providing more clarity about categorisation we use. + +Bug +--- + +Example of bugs: + +- crash during application or rule execution +- wrong changes are applied during "fixing codebase" process +- issue with generated report + +Feature +------- + +Example of features: + +- introduction of new rule +- enhancement of existing rule to cover more cases (for example adding support for newly introduced PHP syntax) +- introduction of new ruleset +- update of existing ruleset (for example adjusting it to match newest style of given community or adding newly implemented rule that was supposed to be followed by style of given community, yet not implemented as a rule before) diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/logo.md b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/logo.md new file mode 100644 index 00000000..c2877f71 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/logo.md @@ -0,0 +1,3 @@ +The logo is © 2010+ Sensio Labs. + +Original resolution can be found at https://github.com/PHP-CS-Fixer/logo . diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/logo.png b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/logo.png new file mode 100644 index 00000000..0ee90a82 Binary files /dev/null and b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/logo.png differ diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/php-cs-fixer b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/php-cs-fixer new file mode 100755 index 00000000..402b49ae --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/php-cs-fixer @@ -0,0 +1,104 @@ +#!/usr/bin/env php + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED); + +set_error_handler(static function ($severity, $message, $file, $line) { + if ($severity & error_reporting()) { + throw new ErrorException($message, 0, $severity, $file, $line); + } +}); + +// check environment requirements +(function () { + if (\PHP_VERSION_ID === 80000) { + fwrite(STDERR, "PHP CS Fixer is not able run on PHP 8.0.0 due to bug in PHP tokenizer (https://bugs.php.net/bug.php?id=80462).\n"); + fwrite(STDERR, "Update PHP version to unblock execution.\n"); + + exit(1); + } + + if (\PHP_VERSION_ID < 70400 || \PHP_VERSION_ID >= 80400) { + fwrite(STDERR, "PHP needs to be a minimum version of PHP 7.4.0 and maximum version of PHP 8.3.*.\n"); + fwrite(STDERR, 'Current PHP version: '.PHP_VERSION.".\n"); + + if (getenv('PHP_CS_FIXER_IGNORE_ENV')) { + fwrite(STDERR, "Ignoring environment requirements because `PHP_CS_FIXER_IGNORE_ENV` is set. Execution may be unstable.\n"); + } else { + fwrite(STDERR, "To ignore this requirement please set `PHP_CS_FIXER_IGNORE_ENV`.\n"); + fwrite(STDERR, "If you use PHP version higher than supported, you may experience code modified in a wrong way.\n"); + fwrite(STDERR, "Please report such cases at https://github.com/PHP-CS-Fixer/PHP-CS-Fixer .\n"); + + exit(1); + } + } + + foreach (['json', 'tokenizer'] as $extension) { + if (!extension_loaded($extension)) { + fwrite(STDERR, sprintf("PHP extension ext-%s is missing from your system. Install or enable it.\n", $extension)); + + if (getenv('PHP_CS_FIXER_IGNORE_ENV')) { + fwrite(STDERR, "Ignoring environment requirements because `PHP_CS_FIXER_IGNORE_ENV` is set. Execution may be unstable.\n"); + } else { + exit(1); + } + } + } +})(); + +// load dependencies +(function () { + $require = true; + if (class_exists('Phar')) { + // Maybe this file is used as phar-stub? Let's try! + try { + Phar::mapPhar('php-cs-fixer.phar'); + + require_once 'phar://php-cs-fixer.phar/vendor/autoload.php'; + $require = false; + } catch (PharException $e) { + } + } + + if ($require) { + // OK, it's not, let give Composer autoloader a try! + $possibleFiles = [__DIR__.'/../../autoload.php', __DIR__.'/../autoload.php', __DIR__.'/vendor/autoload.php']; + $file = null; + foreach ($possibleFiles as $possibleFile) { + if (file_exists($possibleFile)) { + $file = $possibleFile; + + break; + } + } + + if (null === $file) { + throw new RuntimeException('Unable to locate autoload.php file.'); + } + + require_once $file; + } +})(); + +use Composer\XdebugHandler\XdebugHandler; +use PhpCsFixer\Console\Application; + +// Restart if xdebug is loaded, unless the environment variable PHP_CS_FIXER_ALLOW_XDEBUG is set. +$xdebug = new XdebugHandler('PHP_CS_FIXER'); +$xdebug->check(); +unset($xdebug); + +$application = new Application(); +$application->run(); + +__HALT_COMPILER(); diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractDoctrineAnnotationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractDoctrineAnnotationFixer.php new file mode 100644 index 00000000..4ce212c1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractDoctrineAnnotationFixer.php @@ -0,0 +1,235 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Doctrine\Annotation\Tokens as DoctrineAnnotationTokens; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @internal + */ +abstract class AbstractDoctrineAnnotationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private array $classyElements; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + // fetch indices one time, this is safe as we never add or remove a token during fixing + $analyzer = new TokensAnalyzer($tokens); + $this->classyElements = $analyzer->getClassyElements(); + + /** @var Token $docCommentToken */ + foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $index => $docCommentToken) { + if (!$this->nextElementAcceptsDoctrineAnnotations($tokens, $index)) { + continue; + } + + $doctrineAnnotationTokens = DoctrineAnnotationTokens::createFromDocComment( + $docCommentToken, + $this->configuration['ignored_tags'] + ); + + $this->fixAnnotations($doctrineAnnotationTokens); + $tokens[$index] = new Token([T_DOC_COMMENT, $doctrineAnnotationTokens->getCode()]); + } + } + + /** + * Fixes Doctrine annotations from the given PHPDoc style comment. + */ + abstract protected function fixAnnotations(DoctrineAnnotationTokens $doctrineAnnotationTokens): void; + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('ignored_tags', 'List of tags that must not be treated as Doctrine Annotations.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([static function (array $values): bool { + foreach ($values as $value) { + if (!\is_string($value)) { + return false; + } + } + + return true; + }]) + ->setDefault([ + // PHPDocumentor 1 + 'abstract', + 'access', + 'code', + 'deprec', + 'encode', + 'exception', + 'final', + 'ingroup', + 'inheritdoc', + 'inheritDoc', + 'magic', + 'name', + 'toc', + 'tutorial', + 'private', + 'static', + 'staticvar', + 'staticVar', + 'throw', + + // PHPDocumentor 2 + 'api', + 'author', + 'category', + 'copyright', + 'deprecated', + 'example', + 'filesource', + 'global', + 'ignore', + 'internal', + 'license', + 'link', + 'method', + 'package', + 'param', + 'property', + 'property-read', + 'property-write', + 'return', + 'see', + 'since', + 'source', + 'subpackage', + 'throws', + 'todo', + 'TODO', + 'usedBy', + 'uses', + 'var', + 'version', + + // PHPUnit + 'after', + 'afterClass', + 'backupGlobals', + 'backupStaticAttributes', + 'before', + 'beforeClass', + 'codeCoverageIgnore', + 'codeCoverageIgnoreStart', + 'codeCoverageIgnoreEnd', + 'covers', + 'coversDefaultClass', + 'coversNothing', + 'dataProvider', + 'depends', + 'expectedException', + 'expectedExceptionCode', + 'expectedExceptionMessage', + 'expectedExceptionMessageRegExp', + 'group', + 'large', + 'medium', + 'preserveGlobalState', + 'requires', + 'runTestsInSeparateProcesses', + 'runInSeparateProcess', + 'small', + 'test', + 'testdox', + 'ticket', + 'uses', + + // PHPCheckStyle + 'SuppressWarnings', + + // PHPStorm + 'noinspection', + + // PEAR + 'package_version', + + // PlantUML + 'enduml', + 'startuml', + + // Psalm + 'psalm', + + // PHPStan + 'phpstan', + 'template', + + // other + 'fix', + 'FIXME', + 'fixme', + 'override', + ]) + ->getOption(), + ]); + } + + private function nextElementAcceptsDoctrineAnnotations(Tokens $tokens, int $index): bool + { + $classModifiers = [T_ABSTRACT, T_FINAL]; + + if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.2+ is required + $classModifiers[] = T_READONLY; + } + + do { + $index = $tokens->getNextMeaningfulToken($index); + + if (null === $index) { + return false; + } + } while ($tokens[$index]->isGivenKind($classModifiers)); + + if ($tokens[$index]->isGivenKind(T_CLASS)) { + return true; + } + + $modifierKinds = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FINAL, T_ABSTRACT, T_NS_SEPARATOR, T_STRING, CT::T_NULLABLE_TYPE]; + + if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required + $modifierKinds[] = T_READONLY; + } + + while ($tokens[$index]->isGivenKind($modifierKinds)) { + $index = $tokens->getNextMeaningfulToken($index); + } + + if (!isset($this->classyElements[$index])) { + return false; + } + + return $tokens[$this->classyElements[$index]['classIndex']]->isGivenKind(T_CLASS); // interface, enums and traits cannot have doctrine annotations + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractFixer.php new file mode 100644 index 00000000..7b9ac1a0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractFixer.php @@ -0,0 +1,194 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\ConfigurationException\InvalidForEnvFixerConfigurationException; +use PhpCsFixer\ConfigurationException\RequiredFixerConfigurationException; +use PhpCsFixer\Console\Application; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\DeprecatedFixerOption; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\InvalidOptionsForEnvException; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Exception\ExceptionInterface; +use Symfony\Component\OptionsResolver\Exception\MissingOptionsException; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +abstract class AbstractFixer implements FixerInterface +{ + /** + * @var null|array + */ + protected $configuration; + + /** + * @var WhitespacesFixerConfig + */ + protected $whitespacesConfig; + + /** + * @var null|FixerConfigurationResolverInterface + */ + private $configurationDefinition; + + public function __construct() + { + if ($this instanceof ConfigurableFixerInterface) { + try { + $this->configure([]); + } catch (RequiredFixerConfigurationException $e) { + // ignore + } + } + + if ($this instanceof WhitespacesAwareFixerInterface) { + $this->whitespacesConfig = $this->getDefaultWhitespacesFixerConfig(); + } + } + + final public function fix(\SplFileInfo $file, Tokens $tokens): void + { + if ($this instanceof ConfigurableFixerInterface && null === $this->configuration) { + throw new RequiredFixerConfigurationException($this->getName(), 'Configuration is required.'); + } + + if (0 < $tokens->count() && $this->isCandidate($tokens) && $this->supports($file)) { + $this->applyFix($file, $tokens); + } + } + + public function isRisky(): bool + { + return false; + } + + public function getName(): string + { + $nameParts = explode('\\', static::class); + $name = substr(end($nameParts), 0, -\strlen('Fixer')); + + return Utils::camelCaseToUnderscore($name); + } + + public function getPriority(): int + { + return 0; + } + + public function supports(\SplFileInfo $file): bool + { + return true; + } + + /** + * @param array $configuration + */ + public function configure(array $configuration): void + { + if (!$this instanceof ConfigurableFixerInterface) { + throw new \LogicException('Cannot configure using Abstract parent, child not implementing "PhpCsFixer\Fixer\ConfigurableFixerInterface".'); + } + + foreach ($this->getConfigurationDefinition()->getOptions() as $option) { + if (!$option instanceof DeprecatedFixerOption) { + continue; + } + + $name = $option->getName(); + if (\array_key_exists($name, $configuration)) { + Utils::triggerDeprecation(new \InvalidArgumentException(sprintf( + 'Option "%s" for rule "%s" is deprecated and will be removed in version %d.0. %s', + $name, + $this->getName(), + Application::getMajorVersion() + 1, + str_replace('`', '"', $option->getDeprecationMessage()) + ))); + } + } + + try { + $this->configuration = $this->getConfigurationDefinition()->resolve($configuration); + } catch (MissingOptionsException $exception) { + throw new RequiredFixerConfigurationException( + $this->getName(), + sprintf('Missing required configuration: %s', $exception->getMessage()), + $exception + ); + } catch (InvalidOptionsForEnvException $exception) { + throw new InvalidForEnvFixerConfigurationException( + $this->getName(), + sprintf('Invalid configuration for env: %s', $exception->getMessage()), + $exception + ); + } catch (ExceptionInterface $exception) { + throw new InvalidFixerConfigurationException( + $this->getName(), + sprintf('Invalid configuration: %s', $exception->getMessage()), + $exception + ); + } + } + + public function getConfigurationDefinition(): FixerConfigurationResolverInterface + { + if (!$this instanceof ConfigurableFixerInterface) { + throw new \LogicException(sprintf('Cannot get configuration definition using Abstract parent, child "%s" not implementing "PhpCsFixer\Fixer\ConfigurableFixerInterface".', static::class)); + } + + if (null === $this->configurationDefinition) { + $this->configurationDefinition = $this->createConfigurationDefinition(); + } + + return $this->configurationDefinition; + } + + public function setWhitespacesConfig(WhitespacesFixerConfig $config): void + { + if (!$this instanceof WhitespacesAwareFixerInterface) { + throw new \LogicException('Cannot run method for class not implementing "PhpCsFixer\Fixer\WhitespacesAwareFixerInterface".'); + } + + $this->whitespacesConfig = $config; + } + + abstract protected function applyFix(\SplFileInfo $file, Tokens $tokens): void; + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + if (!$this instanceof ConfigurableFixerInterface) { + throw new \LogicException('Cannot create configuration definition using Abstract parent, child not implementing "PhpCsFixer\Fixer\ConfigurableFixerInterface".'); + } + + throw new \LogicException('Not implemented.'); + } + + private function getDefaultWhitespacesFixerConfig(): WhitespacesFixerConfig + { + static $defaultWhitespacesFixerConfig = null; + + if (null === $defaultWhitespacesFixerConfig) { + $defaultWhitespacesFixerConfig = new WhitespacesFixerConfig(' ', "\n"); + } + + return $defaultWhitespacesFixerConfig; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractFopenFlagFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractFopenFlagFixer.php new file mode 100644 index 00000000..da862da7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractFopenFlagFixer.php @@ -0,0 +1,116 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + */ +abstract class AbstractFopenFlagFixer extends AbstractFunctionReferenceFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAllTokenKindsFound([T_STRING, T_CONSTANT_ENCAPSED_STRING]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + $index = 0; + $end = $tokens->count() - 1; + while (true) { + $candidate = $this->find('fopen', $tokens, $index, $end); + + if (null === $candidate) { + break; + } + + $index = $candidate[1]; // proceed to '(' of `fopen` + + // fetch arguments + $arguments = $argumentsAnalyzer->getArguments( + $tokens, + $index, + $candidate[2] + ); + + $argumentsCount = \count($arguments); // argument count sanity check + + if ($argumentsCount < 2 || $argumentsCount > 4) { + continue; + } + + $argumentStartIndex = array_keys($arguments)[1]; // get second argument index + + $this->fixFopenFlagToken( + $tokens, + $argumentStartIndex, + $arguments[$argumentStartIndex] + ); + } + } + + abstract protected function fixFopenFlagToken(Tokens $tokens, int $argumentStartIndex, int $argumentEndIndex): void; + + protected function isValidModeString(string $mode): bool + { + $modeLength = \strlen($mode); + if ($modeLength < 1 || $modeLength > 13) { // 13 === length 'r+w+a+x+c+etb' + return false; + } + + $validFlags = [ + 'a' => true, + 'b' => true, + 'c' => true, + 'e' => true, + 'r' => true, + 't' => true, + 'w' => true, + 'x' => true, + ]; + + if (!isset($validFlags[$mode[0]])) { + return false; + } + + unset($validFlags[$mode[0]]); + + for ($i = 1; $i < $modeLength; ++$i) { + if (isset($validFlags[$mode[$i]])) { + unset($validFlags[$mode[$i]]); + + continue; + } + + if ('+' !== $mode[$i] + || ( + 'a' !== $mode[$i - 1] // 'a+','c+','r+','w+','x+' + && 'c' !== $mode[$i - 1] + && 'r' !== $mode[$i - 1] + && 'w' !== $mode[$i - 1] + && 'x' !== $mode[$i - 1] + ) + ) { + return false; + } + } + + return true; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractFunctionReferenceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractFunctionReferenceFixer.php new file mode 100644 index 00000000..97a92def --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractFunctionReferenceFixer.php @@ -0,0 +1,74 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @author Vladimir Reznichenko + */ +abstract class AbstractFunctionReferenceFixer extends AbstractFixer +{ + /** + * @var null|FunctionsAnalyzer + */ + private $functionsAnalyzer; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + /** + * Looks up Tokens sequence for suitable candidates and delivers boundaries information, + * which can be supplied by other methods in this abstract class. + * + * @return null|int[] returns $functionName, $openParenthesis, $closeParenthesis packed into array + */ + protected function find(string $functionNameToSearch, Tokens $tokens, int $start = 0, ?int $end = null): ?array + { + if (null === $this->functionsAnalyzer) { + $this->functionsAnalyzer = new FunctionsAnalyzer(); + } + + // make interface consistent with findSequence + $end ??= $tokens->count(); + + // find raw sequence which we can analyse for context + $candidateSequence = [[T_STRING, $functionNameToSearch], '(']; + $matches = $tokens->findSequence($candidateSequence, $start, $end, false); + + if (null === $matches) { + return null; // not found, simply return without further attempts + } + + // translate results for humans + [$functionName, $openParenthesis] = array_keys($matches); + + if (!$this->functionsAnalyzer->isGlobalFunctionCall($tokens, $functionName)) { + return $this->find($functionNameToSearch, $tokens, $openParenthesis, $end); + } + + return [$functionName, $openParenthesis, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis)]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractNoUselessElseFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractNoUselessElseFixer.php new file mode 100644 index 00000000..48cd7763 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractNoUselessElseFixer.php @@ -0,0 +1,204 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Tokenizer\Tokens; + +abstract class AbstractNoUselessElseFixer extends AbstractFixer +{ + public function getPriority(): int + { + // should be run before NoWhitespaceInBlankLineFixer, NoExtraBlankLinesFixer, BracesFixer and after NoEmptyStatementFixer. + return 39; + } + + protected function isSuperfluousElse(Tokens $tokens, int $index): bool + { + $previousBlockStart = $index; + + do { + // Check if all 'if', 'else if ' and 'elseif' blocks above this 'else' always end, + // if so this 'else' is overcomplete. + [$previousBlockStart, $previousBlockEnd] = $this->getPreviousBlock($tokens, $previousBlockStart); + + // short 'if' detection + $previous = $previousBlockEnd; + if ($tokens[$previous]->equals('}')) { + $previous = $tokens->getPrevMeaningfulToken($previous); + } + + if ( + !$tokens[$previous]->equals(';') // 'if' block doesn't end with semicolon, keep 'else' + || $tokens[$tokens->getPrevMeaningfulToken($previous)]->equals('{') // empty 'if' block, keep 'else' + ) { + return false; + } + + $candidateIndex = $tokens->getPrevTokenOfKind( + $previous, + [ + ';', + [T_BREAK], + [T_CLOSE_TAG], + [T_CONTINUE], + [T_EXIT], + [T_GOTO], + [T_IF], + [T_RETURN], + [T_THROW], + ] + ); + + if (null === $candidateIndex || $tokens[$candidateIndex]->equalsAny([';', [T_CLOSE_TAG], [T_IF]])) { + return false; + } + + if ($tokens[$candidateIndex]->isGivenKind(T_THROW)) { + $previousIndex = $tokens->getPrevMeaningfulToken($candidateIndex); + + if (!$tokens[$previousIndex]->equalsAny([';', '{'])) { + return false; + } + } + + if ($this->isInConditional($tokens, $candidateIndex, $previousBlockStart) + || $this->isInConditionWithoutBraces($tokens, $candidateIndex, $previousBlockStart) + ) { + return false; + } + + // implicit continue, i.e. delete candidate + } while (!$tokens[$previousBlockStart]->isGivenKind(T_IF)); + + return true; + } + + /** + * Return the first and last token index of the previous block. + * + * [0] First is either T_IF, T_ELSE or T_ELSEIF + * [1] Last is either '}' or ';' / T_CLOSE_TAG for short notation blocks + * + * @param int $index T_IF, T_ELSE, T_ELSEIF + * + * @return int[] + */ + private function getPreviousBlock(Tokens $tokens, int $index): array + { + $close = $previous = $tokens->getPrevMeaningfulToken($index); + // short 'if' detection + if ($tokens[$close]->equals('}')) { + $previous = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $close); + } + + $open = $tokens->getPrevTokenOfKind($previous, [[T_IF], [T_ELSE], [T_ELSEIF]]); + if ($tokens[$open]->isGivenKind(T_IF)) { + $elseCandidate = $tokens->getPrevMeaningfulToken($open); + if ($tokens[$elseCandidate]->isGivenKind(T_ELSE)) { + $open = $elseCandidate; + } + } + + return [$open, $close]; + } + + /** + * @param int $index Index of the token to check + * @param int $lowerLimitIndex Lower limit index. Since the token to check will always be in a conditional we must stop checking at this index + */ + private function isInConditional(Tokens $tokens, int $index, int $lowerLimitIndex): bool + { + $candidateIndex = $tokens->getPrevTokenOfKind($index, [')', ';', ':']); + if ($tokens[$candidateIndex]->equals(':')) { + return true; + } + + if (!$tokens[$candidateIndex]->equals(')')) { + return false; // token is ';' or close tag + } + + // token is always ')' here. + // If it is part of the condition the token is always in, return false. + // If it is not it is a nested condition so return true + $open = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $candidateIndex); + + return $tokens->getPrevMeaningfulToken($open) > $lowerLimitIndex; + } + + /** + * For internal use only, as it is not perfect. + * + * Returns if the token at given index is part of an if/elseif/else statement + * without {}. Assumes not passing the last `;`/close tag of the statement, not + * out of range index, etc. + * + * @param int $index Index of the token to check + */ + private function isInConditionWithoutBraces(Tokens $tokens, int $index, int $lowerLimitIndex): bool + { + do { + if ($tokens[$index]->isComment() || $tokens[$index]->isWhitespace()) { + $index = $tokens->getPrevMeaningfulToken($index); + } + + $token = $tokens[$index]; + if ($token->isGivenKind([T_IF, T_ELSEIF, T_ELSE])) { + return true; + } + + if ($token->equals(';')) { + return false; + } + + if ($token->equals('{')) { + $index = $tokens->getPrevMeaningfulToken($index); + + // OK if belongs to: for, do, while, foreach + // Not OK if belongs to: if, else, elseif + if ($tokens[$index]->isGivenKind(T_DO)) { + --$index; + + continue; + } + + if (!$tokens[$index]->equals(')')) { + return false; // like `else {` + } + + $index = $tokens->findBlockStart( + Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, + $index + ); + + $index = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$index]->isGivenKind([T_IF, T_ELSEIF])) { + return false; + } + } elseif ($token->equals(')')) { + $type = Tokens::detectBlockType($token); + $index = $tokens->findBlockStart( + $type['type'], + $index + ); + + $index = $tokens->getPrevMeaningfulToken($index); + } else { + --$index; + } + } while ($index > $lowerLimitIndex); + + return false; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocToTypeDeclarationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocToTypeDeclarationFixer.php new file mode 100644 index 00000000..e9d70639 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocToTypeDeclarationFixer.php @@ -0,0 +1,280 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + */ +abstract class AbstractPhpdocToTypeDeclarationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const REGEX_CLASS = '(?:\\\\?+'.TypeExpression::REGEX_IDENTIFIER + .'(\\\\'.TypeExpression::REGEX_IDENTIFIER.')*+)'; + + /** + * @var array + */ + private array $versionSpecificTypes = [ + 'void' => 7_01_00, + 'iterable' => 7_01_00, + 'object' => 7_02_00, + 'mixed' => 8_00_00, + 'never' => 8_01_00, + ]; + + /** + * @var array + */ + private array $scalarTypes = [ + 'bool' => true, + 'float' => true, + 'int' => true, + 'string' => true, + ]; + + /** + * @var array + */ + private static array $syntaxValidationCache = []; + + public function isRisky(): bool + { + return true; + } + + abstract protected function isSkippedType(string $type): bool; + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('scalar_types', 'Fix also scalar types; may have unexpected behaviour due to PHP bad type coercion system.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + /** + * @param int $index The index of the function token + */ + protected function findFunctionDocComment(Tokens $tokens, int $index): ?int + { + do { + $index = $tokens->getPrevNonWhitespace($index); + } while ($tokens[$index]->isGivenKind([ + T_COMMENT, + T_ABSTRACT, + T_FINAL, + T_PRIVATE, + T_PROTECTED, + T_PUBLIC, + T_STATIC, + ])); + + if ($tokens[$index]->isGivenKind(T_DOC_COMMENT)) { + return $index; + } + + return null; + } + + /** + * @return Annotation[] + */ + protected function getAnnotationsFromDocComment(string $name, Tokens $tokens, int $docCommentIndex): array + { + $namespacesAnalyzer = new NamespacesAnalyzer(); + $namespace = $namespacesAnalyzer->getNamespaceAt($tokens, $docCommentIndex); + + $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); + $namespaceUses = $namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace); + + $doc = new DocBlock( + $tokens[$docCommentIndex]->getContent(), + $namespace, + $namespaceUses + ); + + return $doc->getAnnotationsOfType($name); + } + + /** + * @return Token[] + */ + protected function createTypeDeclarationTokens(string $type, bool $isNullable): array + { + $newTokens = []; + + if (true === $isNullable && 'mixed' !== $type) { + $newTokens[] = new Token([CT::T_NULLABLE_TYPE, '?']); + } + + $newTokens = array_merge( + $newTokens, + $this->createTokensFromRawType($type)->toArray() + ); + + // 'scalar's, 'void', 'iterable' and 'object' must be unqualified + foreach ($newTokens as $i => $token) { + if ($token->isGivenKind(T_STRING)) { + $typeUnqualified = $token->getContent(); + + if ( + (isset($this->scalarTypes[$typeUnqualified]) || isset($this->versionSpecificTypes[$typeUnqualified])) + && isset($newTokens[$i - 1]) + && '\\' === $newTokens[$i - 1]->getContent() + ) { + unset($newTokens[$i - 1]); + } + } + } + + return array_values($newTokens); + } + + /** + * Each fixer inheriting from this class must define a way of creating token collection representing type + * gathered from phpDoc, e.g. `Foo|Bar` should be transformed into 3 tokens (`Foo`, `|` and `Bar`). + * This can't be standardised, because some types may be allowed in one place, and invalid in others. + * + * @param string $type Type determined (and simplified) from phpDoc + */ + abstract protected function createTokensFromRawType(string $type): Tokens; + + /** + * @return null|array{string, bool} + */ + protected function getCommonTypeInfo(TypeExpression $typesExpression, bool $isReturnType): ?array + { + $commonType = $typesExpression->getCommonType(); + $isNullable = $typesExpression->allowsNull(); + + if (null === $commonType) { + return null; + } + + if ($isNullable && 'void' === $commonType) { + return null; + } + + if ('static' === $commonType && (!$isReturnType || \PHP_VERSION_ID < 8_00_00)) { + $commonType = 'self'; + } + + if ($this->isSkippedType($commonType)) { + return null; + } + + if (isset($this->versionSpecificTypes[$commonType]) && \PHP_VERSION_ID < $this->versionSpecificTypes[$commonType]) { + return null; + } + + if (isset($this->scalarTypes[$commonType])) { + if (false === $this->configuration['scalar_types']) { + return null; + } + } elseif (!Preg::match('/^'.self::REGEX_CLASS.'$/', $commonType)) { + return null; + } + + return [$commonType, $isNullable]; + } + + protected function getUnionTypes(TypeExpression $typesExpression, bool $isReturnType): ?string + { + if (\PHP_VERSION_ID < 8_00_00) { + return null; + } + + if (!$typesExpression->isUnionType() || '|' !== $typesExpression->getTypesGlue()) { + return null; + } + + $types = $typesExpression->getTypes(); + $isNullable = $typesExpression->allowsNull(); + $unionTypes = []; + $containsOtherThanIterableType = false; + $containsOtherThanEmptyType = false; + + foreach ($types as $type) { + if ('null' === $type) { + continue; + } + + if ($this->isSkippedType($type)) { + return null; + } + + if (isset($this->versionSpecificTypes[$type]) && \PHP_VERSION_ID < $this->versionSpecificTypes[$type]) { + return null; + } + + $typeExpression = new TypeExpression($type, null, []); + $commonType = $typeExpression->getCommonType(); + + if (!$containsOtherThanIterableType && !\in_array($commonType, ['array', 'Traversable', 'iterable'], true)) { + $containsOtherThanIterableType = true; + } + if ($isReturnType && !$containsOtherThanEmptyType && !\in_array($commonType, ['null', 'void', 'never'], true)) { + $containsOtherThanEmptyType = true; + } + + if (!$isNullable && $typesExpression->allowsNull()) { + $isNullable = true; + } + + $unionTypes[] = $commonType; + } + + if (!$containsOtherThanIterableType) { + return null; + } + if ($isReturnType && !$containsOtherThanEmptyType) { + return null; + } + + if ($isNullable) { + $unionTypes[] = 'null'; + } + + return implode($typesExpression->getTypesGlue(), array_unique($unionTypes)); + } + + final protected function isValidSyntax(string $code): bool + { + if (!isset(self::$syntaxValidationCache[$code])) { + try { + Tokens::fromCode($code); + self::$syntaxValidationCache[$code] = true; + } catch (\ParseError $e) { + self::$syntaxValidationCache[$code] = false; + } + } + + return self::$syntaxValidationCache[$code]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocTypesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocTypesFixer.php new file mode 100644 index 00000000..c7266c6d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocTypesFixer.php @@ -0,0 +1,118 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * This abstract fixer provides a base for fixers to fix types in PHPDoc. + * + * @author Graham Campbell + * + * @internal + */ +abstract class AbstractPhpdocTypesFixer extends AbstractFixer +{ + /** + * The annotation tags search inside. + * + * @var string[] + */ + protected array $tags; + + public function __construct() + { + parent::__construct(); + + $this->tags = Annotation::getTagsWithTypes(); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $annotations = $doc->getAnnotationsOfType($this->tags); + + if (0 === \count($annotations)) { + continue; + } + + foreach ($annotations as $annotation) { + $this->fixTypes($annotation); + } + + $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); + } + } + + /** + * Actually normalize the given type. + */ + abstract protected function normalize(string $type): string; + + /** + * Fix the types at the given line. + * + * We must be super careful not to modify parts of words. + * + * This will be nicely handled behind the scenes for us by the annotation class. + */ + private function fixTypes(Annotation $annotation): void + { + $types = $annotation->getTypes(); + + $new = $this->normalizeTypes($types); + + if ($types !== $new) { + $annotation->setTypes($new); + } + } + + /** + * @param string[] $types + * + * @return string[] + */ + private function normalizeTypes(array $types): array + { + foreach ($types as $index => $type) { + $types[$index] = $this->normalizeType($type); + } + + return $types; + } + + /** + * Prepare the type and normalize it. + */ + private function normalizeType(string $type): string + { + return str_ends_with($type, '[]') + ? $this->normalizeType(substr($type, 0, -2)).'[]' + : $this->normalize($type); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractProxyFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractProxyFixer.php new file mode 100644 index 00000000..d312bae9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/AbstractProxyFixer.php @@ -0,0 +1,106 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +abstract class AbstractProxyFixer extends AbstractFixer +{ + /** + * @var array + */ + protected array $proxyFixers = []; + + public function __construct() + { + foreach (Utils::sortFixers($this->createProxyFixers()) as $proxyFixer) { + $this->proxyFixers[$proxyFixer->getName()] = $proxyFixer; + } + + parent::__construct(); + } + + public function isCandidate(Tokens $tokens): bool + { + foreach ($this->proxyFixers as $fixer) { + if ($fixer->isCandidate($tokens)) { + return true; + } + } + + return false; + } + + public function isRisky(): bool + { + foreach ($this->proxyFixers as $fixer) { + if ($fixer->isRisky()) { + return true; + } + } + + return false; + } + + public function getPriority(): int + { + if (\count($this->proxyFixers) > 1) { + throw new \LogicException('You need to override this method to provide the priority of combined fixers.'); + } + + return reset($this->proxyFixers)->getPriority(); + } + + public function supports(\SplFileInfo $file): bool + { + foreach ($this->proxyFixers as $fixer) { + if ($fixer->supports($file)) { + return true; + } + } + + return false; + } + + public function setWhitespacesConfig(WhitespacesFixerConfig $config): void + { + parent::setWhitespacesConfig($config); + + foreach ($this->proxyFixers as $fixer) { + if ($fixer instanceof WhitespacesAwareFixerInterface) { + $fixer->setWhitespacesConfig($config); + } + } + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($this->proxyFixers as $fixer) { + $fixer->fix($file, $tokens); + } + } + + /** + * @return FixerInterface[] + */ + abstract protected function createProxyFixers(): array; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/Cache.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/Cache.php new file mode 100644 index 00000000..dfa70634 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/Cache.php @@ -0,0 +1,151 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +use PhpCsFixer\Utils; + +/** + * @author Andreas Möller + * + * @internal + */ +final class Cache implements CacheInterface +{ + private SignatureInterface $signature; + + /** + * @var array + */ + private array $hashes = []; + + public function __construct(SignatureInterface $signature) + { + $this->signature = $signature; + } + + public function getSignature(): SignatureInterface + { + return $this->signature; + } + + public function has(string $file): bool + { + return \array_key_exists($file, $this->hashes); + } + + public function get(string $file): ?string + { + if (!$this->has($file)) { + return null; + } + + return $this->hashes[$file]; + } + + public function set(string $file, string $hash): void + { + $this->hashes[$file] = $hash; + } + + public function clear(string $file): void + { + unset($this->hashes[$file]); + } + + public function toJson(): string + { + $json = json_encode([ + 'php' => $this->getSignature()->getPhpVersion(), + 'version' => $this->getSignature()->getFixerVersion(), + 'indent' => $this->getSignature()->getIndent(), + 'lineEnding' => $this->getSignature()->getLineEnding(), + 'rules' => $this->getSignature()->getRules(), + 'hashes' => $this->hashes, + ]); + + if (JSON_ERROR_NONE !== json_last_error()) { + throw new \UnexpectedValueException(sprintf( + 'Cannot encode cache signature to JSON, error: "%s". If you have non-UTF8 chars in your signature, like in license for `header_comment`, consider enabling `ext-mbstring` or install `symfony/polyfill-mbstring`.', + json_last_error_msg() + )); + } + + return $json; + } + + /** + * @throws \InvalidArgumentException + */ + public static function fromJson(string $json): self + { + $data = json_decode($json, true); + + if (null === $data && JSON_ERROR_NONE !== json_last_error()) { + throw new \InvalidArgumentException(sprintf( + 'Value needs to be a valid JSON string, got "%s", error: "%s".', + $json, + json_last_error_msg() + )); + } + + $requiredKeys = [ + 'php', + 'version', + 'indent', + 'lineEnding', + 'rules', + 'hashes', + ]; + + $missingKeys = array_diff_key(array_flip($requiredKeys), $data); + + if (\count($missingKeys) > 0) { + throw new \InvalidArgumentException(sprintf( + 'JSON data is missing keys %s', + Utils::naturalLanguageJoin(array_keys($missingKeys)) + )); + } + + $signature = new Signature( + $data['php'], + $data['version'], + $data['indent'], + $data['lineEnding'], + $data['rules'] + ); + + $cache = new self($signature); + + // before v3.11.1 the hashes were crc32 encoded and saved as integers + // @TODO: remove the to string cast/array_map in v4.0 + $cache->hashes = array_map(static fn ($v): string => \is_int($v) ? (string) $v : $v, $data['hashes']); + + return $cache; + } + + /** + * @internal + */ + public function backfillHashes(self $oldCache): bool + { + if (!$this->getSignature()->equals($oldCache->getSignature())) { + return false; + } + + $this->hashes = array_merge($oldCache->hashes, $this->hashes); + + return true; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheInterface.php new file mode 100644 index 00000000..29ab7197 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheInterface.php @@ -0,0 +1,35 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * @author Andreas Möller + * + * @internal + */ +interface CacheInterface +{ + public function getSignature(): SignatureInterface; + + public function has(string $file): bool; + + public function get(string $file): ?string; + + public function set(string $file, string $hash): void; + + public function clear(string $file): void; + + public function toJson(): string; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheManagerInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheManagerInterface.php new file mode 100644 index 00000000..4e82d0c9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheManagerInterface.php @@ -0,0 +1,27 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +interface CacheManagerInterface +{ + public function needFixing(string $file, string $fileContent): bool; + + public function setFile(string $file, string $fileContent): void; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/Directory.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/Directory.php new file mode 100644 index 00000000..26573896 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/Directory.php @@ -0,0 +1,49 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class Directory implements DirectoryInterface +{ + private string $directoryName; + + public function __construct(string $directoryName) + { + $this->directoryName = $directoryName; + } + + public function getRelativePathTo(string $file): string + { + $file = $this->normalizePath($file); + + if ( + '' === $this->directoryName + || 0 !== stripos($file, $this->directoryName.\DIRECTORY_SEPARATOR) + ) { + return $file; + } + + return substr($file, \strlen($this->directoryName) + 1); + } + + private function normalizePath(string $path): string + { + return str_replace(['\\', '/'], \DIRECTORY_SEPARATOR, $path); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/DirectoryInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/DirectoryInterface.php new file mode 100644 index 00000000..2fdce86a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/DirectoryInterface.php @@ -0,0 +1,23 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * @author Dariusz Rumiński + */ +interface DirectoryInterface +{ + public function getRelativePathTo(string $file): string; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/FileCacheManager.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/FileCacheManager.php new file mode 100644 index 00000000..1e3f64dc --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/FileCacheManager.php @@ -0,0 +1,141 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * Class supports caching information about state of fixing files. + * + * Cache is supported only for phar version and version installed via composer. + * + * File will be processed by PHP CS Fixer only if any of the following conditions is fulfilled: + * - cache is corrupt + * - fixer version changed + * - rules changed + * - file is new + * - file changed + * + * @author Dariusz Rumiński + * + * @internal + */ +final class FileCacheManager implements CacheManagerInterface +{ + public const WRITE_FREQUENCY = 10; + + private FileHandlerInterface $handler; + + private SignatureInterface $signature; + + private bool $isDryRun; + + private DirectoryInterface $cacheDirectory; + + private int $writeCounter = 0; + + private bool $signatureWasUpdated = false; + + /** + * @var CacheInterface + */ + private $cache; + + public function __construct( + FileHandlerInterface $handler, + SignatureInterface $signature, + bool $isDryRun = false, + ?DirectoryInterface $cacheDirectory = null + ) { + $this->handler = $handler; + $this->signature = $signature; + $this->isDryRun = $isDryRun; + $this->cacheDirectory = $cacheDirectory ?? new Directory(''); + + $this->readCache(); + } + + public function __destruct() + { + if (true === $this->signatureWasUpdated || 0 !== $this->writeCounter) { + $this->writeCache(); + } + } + + /** + * This class is not intended to be serialized, + * and cannot be deserialized (see __wakeup method). + */ + public function __sleep(): array + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + /** + * Disable the deserialization of the class to prevent attacker executing + * code by leveraging the __destruct method. + * + * @see https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection + */ + public function __wakeup(): void + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + public function needFixing(string $file, string $fileContent): bool + { + $file = $this->cacheDirectory->getRelativePathTo($file); + + return !$this->cache->has($file) || $this->cache->get($file) !== $this->calcHash($fileContent); + } + + public function setFile(string $file, string $fileContent): void + { + $file = $this->cacheDirectory->getRelativePathTo($file); + + $hash = $this->calcHash($fileContent); + + if ($this->isDryRun && $this->cache->has($file) && $this->cache->get($file) !== $hash) { + $this->cache->clear($file); + } else { + $this->cache->set($file, $hash); + } + + if (self::WRITE_FREQUENCY === ++$this->writeCounter) { + $this->writeCounter = 0; + $this->writeCache(); + } + } + + private function readCache(): void + { + $cache = $this->handler->read(); + + if (null === $cache || !$this->signature->equals($cache->getSignature())) { + $cache = new Cache($this->signature); + $this->signatureWasUpdated = true; + } + + $this->cache = $cache; + } + + private function writeCache(): void + { + $this->handler->write($this->cache); + } + + private function calcHash(string $content): string + { + return md5($content); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandler.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandler.php new file mode 100644 index 00000000..51b4ca58 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandler.php @@ -0,0 +1,184 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +use Symfony\Component\Filesystem\Exception\IOException; + +/** + * @author Andreas Möller + * @author Dariusz Rumiński + * + * @internal + */ +final class FileHandler implements FileHandlerInterface +{ + private \SplFileInfo $fileInfo; + + private int $fileMTime = 0; + + public function __construct(string $file) + { + $this->fileInfo = new \SplFileInfo($file); + } + + public function getFile(): string + { + return $this->fileInfo->getPathname(); + } + + public function read(): ?CacheInterface + { + if (!$this->fileInfo->isFile() || !$this->fileInfo->isReadable()) { + return null; + } + + $fileObject = $this->fileInfo->openFile('r'); + + $cache = $this->readFromHandle($fileObject); + $this->fileMTime = $this->getFileCurrentMTime(); + + unset($fileObject); // explicitly close file handler + + return $cache; + } + + public function write(CacheInterface $cache): void + { + $this->ensureFileIsWriteable(); + + $fileObject = $this->fileInfo->openFile('r+'); + + if (method_exists($cache, 'backfillHashes') && $this->fileMTime < $this->getFileCurrentMTime()) { + $resultOfFlock = $fileObject->flock(LOCK_EX); + if (false === $resultOfFlock) { + // Lock failed, OK - we continue without the lock. + // noop + } + + $oldCache = $this->readFromHandle($fileObject); + + $fileObject->rewind(); + + if (null !== $oldCache) { + $cache->backfillHashes($oldCache); + } + } + + $resultOfTruncate = $fileObject->ftruncate(0); + if (false === $resultOfTruncate) { + // Truncate failed. OK - we do not save the cache. + return; + } + + $resultOfWrite = $fileObject->fwrite($cache->toJson()); + if (false === $resultOfWrite) { + // Write failed. OK - we did not save the cache. + return; + } + + $resultOfFlush = $fileObject->fflush(); + if (false === $resultOfFlush) { + // Flush failed. OK - part of cache can be missing, in case this was last chunk in this pid. + // noop + } + + $this->fileMTime = time(); // we could take the fresh `mtime` of file that we just modified with `$this->getFileCurrentMTime()`, but `time()` should be good enough here and reduce IO operation + } + + private function getFileCurrentMTime(): int + { + clearstatcache(true, $this->fileInfo->getPathname()); + + $mtime = $this->fileInfo->getMTime(); + + if (false === $mtime) { + // cannot check mtime? OK - let's pretend file is old. + $mtime = 0; + } + + return $mtime; + } + + private function readFromHandle(\SplFileObject $fileObject): ?CacheInterface + { + try { + $size = $fileObject->getSize(); + if (false === $size || 0 === $size) { + return null; + } + + $content = $fileObject->fread($size); + + if (false === $content) { + return null; + } + + return Cache::fromJson($content); + } catch (\InvalidArgumentException $exception) { + return null; + } + } + + private function ensureFileIsWriteable(): void + { + if ($this->fileInfo->isFile() && $this->fileInfo->isWritable()) { + // all good + return; + } + + if ($this->fileInfo->isDir()) { + throw new IOException( + sprintf('Cannot write cache file "%s" as the location exists as directory.', $this->fileInfo->getRealPath()), + 0, + null, + $this->fileInfo->getPathname() + ); + } + + if ($this->fileInfo->isFile() && !$this->fileInfo->isWritable()) { + throw new IOException( + sprintf('Cannot write to file "%s" as it is not writable.', $this->fileInfo->getRealPath()), + 0, + null, + $this->fileInfo->getPathname() + ); + } + + $this->createFile($this->fileInfo->getPathname()); + } + + private function createFile(string $file): void + { + $dir = \dirname($file); + + // Ensure path is created, but ignore if already exists. FYI: ignore EA suggestion in IDE, + // `mkdir()` returns `false` for existing paths, so we can't mix it with `is_dir()` in one condition. + if (!@is_dir($dir)) { + @mkdir($dir, 0777, true); + } + + if (!@is_dir($dir)) { + throw new IOException( + sprintf('Directory of cache file "%s" does not exists and couldn\'t be created.', $file), + 0, + null, + $file + ); + } + + @touch($file); + @chmod($file, 0666); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandlerInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandlerInterface.php new file mode 100644 index 00000000..464b04cf --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandlerInterface.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * @author Andreas Möller + * + * @internal + */ +interface FileHandlerInterface +{ + public function getFile(): string; + + public function read(): ?CacheInterface; + + public function write(CacheInterface $cache): void; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/NullCacheManager.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/NullCacheManager.php new file mode 100644 index 00000000..ff0b6fed --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/NullCacheManager.php @@ -0,0 +1,30 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * @author Andreas Möller + * + * @internal + */ +final class NullCacheManager implements CacheManagerInterface +{ + public function needFixing(string $file, string $fileContent): bool + { + return true; + } + + public function setFile(string $file, string $fileContent): void {} +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/Signature.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/Signature.php new file mode 100644 index 00000000..48c96289 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/Signature.php @@ -0,0 +1,98 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * @author Andreas Möller + * + * @internal + */ +final class Signature implements SignatureInterface +{ + private string $phpVersion; + + private string $fixerVersion; + + private string $indent; + + private string $lineEnding; + + /** + * @var array|bool> + */ + private array $rules; + + /** + * @param array|bool> $rules + */ + public function __construct(string $phpVersion, string $fixerVersion, string $indent, string $lineEnding, array $rules) + { + $this->phpVersion = $phpVersion; + $this->fixerVersion = $fixerVersion; + $this->indent = $indent; + $this->lineEnding = $lineEnding; + $this->rules = self::makeJsonEncodable($rules); + } + + public function getPhpVersion(): string + { + return $this->phpVersion; + } + + public function getFixerVersion(): string + { + return $this->fixerVersion; + } + + public function getIndent(): string + { + return $this->indent; + } + + public function getLineEnding(): string + { + return $this->lineEnding; + } + + public function getRules(): array + { + return $this->rules; + } + + public function equals(SignatureInterface $signature): bool + { + return $this->phpVersion === $signature->getPhpVersion() + && $this->fixerVersion === $signature->getFixerVersion() + && $this->indent === $signature->getIndent() + && $this->lineEnding === $signature->getLineEnding() + && $this->rules === $signature->getRules(); + } + + /** + * @param array|bool> $data + * + * @return array|bool> + */ + private static function makeJsonEncodable(array $data): array + { + array_walk_recursive($data, static function (&$item): void { + if (\is_string($item) && !mb_detect_encoding($item, 'utf-8', true)) { + $item = base64_encode($item); + } + }); + + return $data; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/SignatureInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/SignatureInterface.php new file mode 100644 index 00000000..cc952141 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Cache/SignatureInterface.php @@ -0,0 +1,38 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * @author Andreas Möller + * + * @internal + */ +interface SignatureInterface +{ + public function getPhpVersion(): string; + + public function getFixerVersion(): string; + + public function getIndent(): string; + + public function getLineEnding(): string; + + /** + * @return array|bool> + */ + public function getRules(): array; + + public function equals(self $signature): bool; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Config.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Config.php new file mode 100644 index 00000000..6ed9f5cb --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Config.php @@ -0,0 +1,219 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Fixer\FixerInterface; + +/** + * @author Fabien Potencier + * @author Katsuhiro Ogawa + * @author Dariusz Rumiński + */ +class Config implements ConfigInterface +{ + private string $cacheFile = '.php-cs-fixer.cache'; + + /** + * @var FixerInterface[] + */ + private array $customFixers = []; + + /** + * @var null|iterable<\SplFileInfo> + */ + private ?iterable $finder = null; + + private string $format = 'txt'; + + private bool $hideProgress = false; + + private string $indent = ' '; + + private bool $isRiskyAllowed = false; + + private string $lineEnding = "\n"; + + private string $name; + + /** + * @var null|string + */ + private $phpExecutable; + + /** + * @TODO: 4.0 - update to @PER + * + * @var array|bool> + */ + private array $rules = ['@PSR12' => true]; + + private bool $usingCache = true; + + public function __construct(string $name = 'default') + { + $this->name = $name; + } + + public function getCacheFile(): string + { + return $this->cacheFile; + } + + public function getCustomFixers(): array + { + return $this->customFixers; + } + + /** + * @return Finder + */ + public function getFinder(): iterable + { + if (null === $this->finder) { + $this->finder = new Finder(); + } + + return $this->finder; + } + + public function getFormat(): string + { + return $this->format; + } + + public function getHideProgress(): bool + { + return $this->hideProgress; + } + + public function getIndent(): string + { + return $this->indent; + } + + public function getLineEnding(): string + { + return $this->lineEnding; + } + + public function getName(): string + { + return $this->name; + } + + public function getPhpExecutable(): ?string + { + return $this->phpExecutable; + } + + public function getRiskyAllowed(): bool + { + return $this->isRiskyAllowed; + } + + public function getRules(): array + { + return $this->rules; + } + + public function getUsingCache(): bool + { + return $this->usingCache; + } + + public function registerCustomFixers(iterable $fixers): ConfigInterface + { + foreach ($fixers as $fixer) { + $this->addCustomFixer($fixer); + } + + return $this; + } + + public function setCacheFile(string $cacheFile): ConfigInterface + { + $this->cacheFile = $cacheFile; + + return $this; + } + + public function setFinder(iterable $finder): ConfigInterface + { + $this->finder = $finder; + + return $this; + } + + public function setFormat(string $format): ConfigInterface + { + $this->format = $format; + + return $this; + } + + public function setHideProgress(bool $hideProgress): ConfigInterface + { + $this->hideProgress = $hideProgress; + + return $this; + } + + public function setIndent(string $indent): ConfigInterface + { + $this->indent = $indent; + + return $this; + } + + public function setLineEnding(string $lineEnding): ConfigInterface + { + $this->lineEnding = $lineEnding; + + return $this; + } + + public function setPhpExecutable(?string $phpExecutable): ConfigInterface + { + $this->phpExecutable = $phpExecutable; + + return $this; + } + + public function setRiskyAllowed(bool $isRiskyAllowed): ConfigInterface + { + $this->isRiskyAllowed = $isRiskyAllowed; + + return $this; + } + + public function setRules(array $rules): ConfigInterface + { + $this->rules = $rules; + + return $this; + } + + public function setUsingCache(bool $usingCache): ConfigInterface + { + $this->usingCache = $usingCache; + + return $this; + } + + private function addCustomFixer(FixerInterface $fixer): void + { + $this->customFixers[] = $fixer; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ConfigInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ConfigInterface.php new file mode 100644 index 00000000..b46b191b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ConfigInterface.php @@ -0,0 +1,140 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Fixer\FixerInterface; + +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + */ +interface ConfigInterface +{ + /** + * Returns the path to the cache file. + * + * @return null|string Returns null if not using cache + */ + public function getCacheFile(): ?string; + + /** + * Returns the custom fixers to use. + * + * @return FixerInterface[] + */ + public function getCustomFixers(): array; + + /** + * Returns files to scan. + * + * @return iterable<\SplFileInfo> + */ + public function getFinder(): iterable; + + public function getFormat(): string; + + /** + * Returns true if progress should be hidden. + */ + public function getHideProgress(): bool; + + public function getIndent(): string; + + public function getLineEnding(): string; + + /** + * Returns the name of the configuration. + * + * The name must be all lowercase and without any spaces. + * + * @return string The name of the configuration + */ + public function getName(): string; + + /** + * Get configured PHP executable, if any. + */ + public function getPhpExecutable(): ?string; + + /** + * Check if it is allowed to run risky fixers. + */ + public function getRiskyAllowed(): bool; + + /** + * Get rules. + * + * Keys of array are names of fixers/sets, values are true/false. + * + * @return array|bool> + */ + public function getRules(): array; + + /** + * Returns true if caching should be enabled. + */ + public function getUsingCache(): bool; + + /** + * Adds a suite of custom fixers. + * + * Name of custom fixer should follow `VendorName/rule_name` convention. + * + * @param FixerInterface[]|iterable|\Traversable $fixers + */ + public function registerCustomFixers(iterable $fixers): self; + + /** + * Sets the path to the cache file. + */ + public function setCacheFile(string $cacheFile): self; + + /** + * @param iterable<\SplFileInfo> $finder + */ + public function setFinder(iterable $finder): self; + + public function setFormat(string $format): self; + + public function setHideProgress(bool $hideProgress): self; + + public function setIndent(string $indent): self; + + public function setLineEnding(string $lineEnding): self; + + /** + * Set PHP executable. + */ + public function setPhpExecutable(?string $phpExecutable): self; + + /** + * Set if it is allowed to run risky fixers. + */ + public function setRiskyAllowed(bool $isRiskyAllowed): self; + + /** + * Set rules. + * + * Keys of array are names of fixers or sets. + * Value for set must be bool (turn it on or off). + * Value for fixer may be bool (turn it on or off) or array of configuration + * (turn it on and contains configuration for FixerInterface::configure method). + * + * @param array|bool> $rules + */ + public function setRules(array $rules): self; + + public function setUsingCache(bool $usingCache): self; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidConfigurationException.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidConfigurationException.php new file mode 100644 index 00000000..87babf8f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidConfigurationException.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\ConfigurationException; + +use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator; + +/** + * Exceptions of this type are thrown on misconfiguration of the Fixer. + * + * @internal + * + * @final Only internal extending this class is supported + */ +class InvalidConfigurationException extends \InvalidArgumentException +{ + public function __construct(string $message, ?int $code = null, ?\Throwable $previous = null) + { + parent::__construct( + $message, + $code ?? FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_CONFIG, + $previous + ); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidFixerConfigurationException.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidFixerConfigurationException.php new file mode 100644 index 00000000..140385c3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidFixerConfigurationException.php @@ -0,0 +1,45 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\ConfigurationException; + +use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator; + +/** + * Exception thrown by Fixers on misconfiguration. + * + * @internal + * + * @final Only internal extending this class is supported + */ +class InvalidFixerConfigurationException extends InvalidConfigurationException +{ + private string $fixerName; + + public function __construct(string $fixerName, string $message, ?\Throwable $previous = null) + { + parent::__construct( + sprintf('[%s] %s', $fixerName, $message), + FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG, + $previous + ); + + $this->fixerName = $fixerName; + } + + public function getFixerName(): string + { + return $this->fixerName; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidForEnvFixerConfigurationException.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidForEnvFixerConfigurationException.php new file mode 100644 index 00000000..440b2470 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidForEnvFixerConfigurationException.php @@ -0,0 +1,22 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\ConfigurationException; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class InvalidForEnvFixerConfigurationException extends InvalidFixerConfigurationException {} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/RequiredFixerConfigurationException.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/RequiredFixerConfigurationException.php new file mode 100644 index 00000000..bcc07bdf --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/RequiredFixerConfigurationException.php @@ -0,0 +1,22 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\ConfigurationException; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class RequiredFixerConfigurationException extends InvalidFixerConfigurationException {} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Application.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Application.php new file mode 100644 index 00000000..34ba8ffa --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Application.php @@ -0,0 +1,134 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console; + +use PhpCsFixer\Console\Command\CheckCommand; +use PhpCsFixer\Console\Command\DescribeCommand; +use PhpCsFixer\Console\Command\FixCommand; +use PhpCsFixer\Console\Command\HelpCommand; +use PhpCsFixer\Console\Command\ListFilesCommand; +use PhpCsFixer\Console\Command\ListSetsCommand; +use PhpCsFixer\Console\Command\SelfUpdateCommand; +use PhpCsFixer\Console\SelfUpdate\GithubClient; +use PhpCsFixer\Console\SelfUpdate\NewVersionChecker; +use PhpCsFixer\PharChecker; +use PhpCsFixer\ToolInfo; +use PhpCsFixer\Utils; +use Symfony\Component\Console\Application as BaseApplication; +use Symfony\Component\Console\Command\ListCommand; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + * + * @internal + */ +final class Application extends BaseApplication +{ + public const VERSION = '3.40.2'; + public const VERSION_CODENAME = 'I ate three cookies 🍪'; + + private ToolInfo $toolInfo; + + public function __construct() + { + parent::__construct('PHP CS Fixer', self::VERSION); + + $this->toolInfo = new ToolInfo(); + + // in alphabetical order + $this->add(new DescribeCommand()); + $this->add(new CheckCommand($this->toolInfo)); + $this->add(new FixCommand($this->toolInfo)); + $this->add(new ListFilesCommand($this->toolInfo)); + $this->add(new ListSetsCommand()); + $this->add(new SelfUpdateCommand( + new NewVersionChecker(new GithubClient()), + $this->toolInfo, + new PharChecker() + )); + } + + public static function getMajorVersion(): int + { + return (int) explode('.', self::VERSION)[0]; + } + + public function doRun(InputInterface $input, OutputInterface $output): int + { + $stdErr = $output instanceof ConsoleOutputInterface + ? $output->getErrorOutput() + : ($input->hasParameterOption('--format', true) && 'txt' !== $input->getParameterOption('--format', null, true) ? null : $output); + + if (null !== $stdErr) { + $warningsDetector = new WarningsDetector($this->toolInfo); + $warningsDetector->detectOldVendor(); + $warningsDetector->detectOldMajor(); + $warnings = $warningsDetector->getWarnings(); + + if (\count($warnings) > 0) { + foreach ($warnings as $warning) { + $stdErr->writeln(sprintf($stdErr->isDecorated() ? '%s' : '%s', $warning)); + } + $stdErr->writeln(''); + } + } + + $result = parent::doRun($input, $output); + + if ( + null !== $stdErr + && $output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE + ) { + $triggeredDeprecations = Utils::getTriggeredDeprecations(); + + if (\count($triggeredDeprecations) > 0) { + $stdErr->writeln(''); + $stdErr->writeln($stdErr->isDecorated() ? 'Detected deprecations in use:' : 'Detected deprecations in use:'); + foreach ($triggeredDeprecations as $deprecation) { + $stdErr->writeln(sprintf('- %s', $deprecation)); + } + } + } + + return $result; + } + + public function getLongVersion(): string + { + $commit = '@git-commit@'; + $versionCommit = ''; + + if ('@'.'git-commit@' !== $commit) { /** @phpstan-ignore-line as `$commit` is replaced during phar building */ + $versionCommit = substr($commit, 0, 7); + } + + return implode('', [ + parent::getLongVersion(), + $versionCommit ? sprintf(' (%s)', $versionCommit) : '', // @phpstan-ignore-line to avoid `Ternary operator condition is always true|false.` + self::VERSION_CODENAME ? sprintf(' %s', self::VERSION_CODENAME) : '', // @phpstan-ignore-line to avoid `Ternary operator condition is always true|false.` + ' by Fabien Potencier and Dariusz Ruminski.', + "\nPHP runtime: ".PHP_VERSION.'', + ]); + } + + protected function getDefaultCommands(): array + { + return [new HelpCommand(), new ListCommand()]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/CheckCommand.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/CheckCommand.php new file mode 100644 index 00000000..d5c83b72 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/CheckCommand.php @@ -0,0 +1,63 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\ToolInfoInterface; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; + +/** + * @author Greg Korba + * + * @internal + */ +#[AsCommand(name: 'check', description: 'Checks if configured files/directories comply with configured rules.')] +final class CheckCommand extends FixCommand +{ + protected static $defaultName = 'check'; + protected static $defaultDescription = 'Checks if configured files/directories comply with configured rules.'; + + public function __construct(ToolInfoInterface $toolInfo) + { + parent::__construct($toolInfo); + } + + public function getHelp(): string + { + $help = explode('--dry-run', parent::getHelp()); + + return substr($help[0], 0, strrpos($help[0], "\n") - 1) + .substr($help[1], strpos($help[1], "\n")); + } + + protected function configure(): void + { + parent::configure(); + + $this->setDefinition([ + ...array_values($this->getDefinition()->getArguments()), + ...array_values(array_filter( + $this->getDefinition()->getOptions(), + static fn (InputOption $option): bool => 'dry-run' !== $option->getName() + )), + ]); + } + + protected function isDryRun(InputInterface $input): bool + { + return true; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeCommand.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeCommand.php new file mode 100644 index 00000000..2f7f45d4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeCommand.php @@ -0,0 +1,454 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Config; +use PhpCsFixer\Console\ConfigurationResolver; +use PhpCsFixer\Differ\DiffConsoleFormatter; +use PhpCsFixer\Differ\FullDiffer; +use PhpCsFixer\Documentation\FixerDocumentGenerator; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\FixerConfiguration\AliasedFixerOption; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\DeprecatedFixerOption; +use PhpCsFixer\FixerDefinition\CodeSampleInterface; +use PhpCsFixer\FixerDefinition\FileSpecificCodeSampleInterface; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface; +use PhpCsFixer\FixerFactory; +use PhpCsFixer\Preg; +use PhpCsFixer\RuleSet\RuleSets; +use PhpCsFixer\StdinFileInfo; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\ToolInfo; +use PhpCsFixer\Utils; +use PhpCsFixer\WordMatcher; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +#[AsCommand(name: 'describe')] +final class DescribeCommand extends Command +{ + protected static $defaultName = 'describe'; + + /** + * @var string[] + */ + private $setNames; + + private FixerFactory $fixerFactory; + + /** + * @var array + */ + private $fixers; + + public function __construct(?FixerFactory $fixerFactory = null) + { + parent::__construct(); + + if (null === $fixerFactory) { + $fixerFactory = new FixerFactory(); + $fixerFactory->registerBuiltInFixers(); + } + + $this->fixerFactory = $fixerFactory; + } + + protected function configure(): void + { + $this + ->setDefinition( + [ + new InputArgument('name', InputArgument::REQUIRED, 'Name of rule / set.'), + new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a .php-cs-fixer.php file.'), + ] + ) + ->setDescription('Describe rule / ruleset.') + ; + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity() && $output instanceof ConsoleOutputInterface) { + $stdErr = $output->getErrorOutput(); + $stdErr->writeln($this->getApplication()->getLongVersion()); + } + + $resolver = new ConfigurationResolver( + new Config(), + ['config' => $input->getOption('config')], + getcwd(), + new ToolInfo() + ); + + $this->fixerFactory->registerCustomFixers($resolver->getConfig()->getCustomFixers()); + + $name = $input->getArgument('name'); + + try { + if (str_starts_with($name, '@')) { + $this->describeSet($output, $name); + + return 0; + } + + $this->describeRule($output, $name); + } catch (DescribeNameNotFoundException $e) { + $matcher = new WordMatcher( + 'set' === $e->getType() ? $this->getSetNames() : array_keys($this->getFixers()) + ); + + $alternative = $matcher->match($name); + + $this->describeList($output, $e->getType()); + + throw new \InvalidArgumentException(sprintf( + '%s "%s" not found.%s', + ucfirst($e->getType()), + $name, + null === $alternative ? '' : ' Did you mean "'.$alternative.'"?' + )); + } + + return 0; + } + + private function describeRule(OutputInterface $output, string $name): void + { + $fixers = $this->getFixers(); + + if (!isset($fixers[$name])) { + throw new DescribeNameNotFoundException($name, 'rule'); + } + + /** @var FixerInterface $fixer */ + $fixer = $fixers[$name]; + + $definition = $fixer->getDefinition(); + + $output->writeln(sprintf('Description of the `%s` rule.', $name)); + $output->writeln(''); + + if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { + $output->writeln(sprintf('Fixer class: %s.', \get_class($fixer))); + $output->writeln(''); + } + + if ($fixer instanceof DeprecatedFixerInterface) { + $successors = $fixer->getSuccessorsNames(); + $message = [] === $successors + ? 'will be removed in the next major version' + : sprintf('use %s instead', Utils::naturalLanguageJoinWithBackticks($successors)); + $message = Preg::replace('/(`[^`]+`)/', '$1', $message); + $output->writeln(sprintf('DEPRECATED: %s.', $message)); + $output->writeln(''); + } + + $output->writeln($definition->getSummary()); + + $description = $definition->getDescription(); + + if (null !== $description) { + $output->writeln($description); + } + + $output->writeln(''); + + if ($fixer->isRisky()) { + $output->writeln('Fixer applying this rule is risky.'); + + $riskyDescription = $definition->getRiskyDescription(); + + if (null !== $riskyDescription) { + $output->writeln($riskyDescription); + } + + $output->writeln(''); + } + + if ($fixer instanceof ConfigurableFixerInterface) { + $configurationDefinition = $fixer->getConfigurationDefinition(); + $options = $configurationDefinition->getOptions(); + + $output->writeln(sprintf('Fixer is configurable using following option%s:', 1 === \count($options) ? '' : 's')); + + foreach ($options as $option) { + $line = '* '.OutputFormatter::escape($option->getName()).''; + $allowed = HelpCommand::getDisplayableAllowedValues($option); + + if (null === $allowed) { + $allowed = array_map( + static fn (string $type): string => ''.$type.'', + $option->getAllowedTypes(), + ); + } else { + $allowed = array_map(static fn ($value): string => $value instanceof AllowedValueSubset + ? 'a subset of '.Utils::toString($value->getAllowedValues()).'' + : ''.Utils::toString($value).'', $allowed); + } + + $line .= ' ('.Utils::naturalLanguageJoin($allowed, '').')'; + + $description = Preg::replace('/(`.+?`)/', '$1', OutputFormatter::escape($option->getDescription())); + $line .= ': '.lcfirst(Preg::replace('/\.$/', '', $description)).'; '; + + if ($option->hasDefault()) { + $line .= sprintf( + 'defaults to %s', + Utils::toString($option->getDefault()) + ); + } else { + $line .= 'required'; + } + + if ($option instanceof DeprecatedFixerOption) { + $line .= '. DEPRECATED: '.Preg::replace( + '/(`.+?`)/', + '$1', + OutputFormatter::escape(lcfirst($option->getDeprecationMessage())) + ); + } + + if ($option instanceof AliasedFixerOption) { + $line .= '; DEPRECATED alias: '.$option->getAlias().''; + } + + $output->writeln($line); + } + + $output->writeln(''); + } + + /** @var CodeSampleInterface[] $codeSamples */ + $codeSamples = array_filter($definition->getCodeSamples(), static function (CodeSampleInterface $codeSample): bool { + if ($codeSample instanceof VersionSpecificCodeSampleInterface) { + return $codeSample->isSuitableFor(\PHP_VERSION_ID); + } + + return true; + }); + + if (0 === \count($definition->getCodeSamples())) { + $output->writeln([ + 'Fixing examples are not available for this rule.', + '', + ]); + } elseif (0 === \count($codeSamples)) { + $output->writeln([ + 'Fixing examples cannot be demonstrated on the current PHP version.', + '', + ]); + } else { + $output->writeln('Fixing examples:'); + + $differ = new FullDiffer(); + $diffFormatter = new DiffConsoleFormatter( + $output->isDecorated(), + sprintf( + ' ---------- begin diff ----------%s%%s%s ----------- end diff -----------', + PHP_EOL, + PHP_EOL + ) + ); + + foreach ($codeSamples as $index => $codeSample) { + $old = $codeSample->getCode(); + $tokens = Tokens::fromCode($old); + + $configuration = $codeSample->getConfiguration(); + + if ($fixer instanceof ConfigurableFixerInterface) { + $fixer->configure($configuration ?? []); + } + + $file = $codeSample instanceof FileSpecificCodeSampleInterface + ? $codeSample->getSplFileInfo() + : new StdinFileInfo(); + + $fixer->fix($file, $tokens); + + $diff = $differ->diff($old, $tokens->generateCode()); + + if ($fixer instanceof ConfigurableFixerInterface) { + if (null === $configuration) { + $output->writeln(sprintf(' * Example #%d. Fixing with the default configuration.', $index + 1)); + } else { + $output->writeln(sprintf(' * Example #%d. Fixing with configuration: %s.', $index + 1, Utils::toString($codeSample->getConfiguration()))); + } + } else { + $output->writeln(sprintf(' * Example #%d.', $index + 1)); + } + + $output->writeln([$diffFormatter->format($diff, ' %s'), '']); + } + } + + $ruleSetConfigs = FixerDocumentGenerator::getSetsOfRule($name); + + if ([] !== $ruleSetConfigs) { + ksort($ruleSetConfigs); + $plural = 1 !== \count($ruleSetConfigs) ? 's' : ''; + $output->writeln("Fixer is part of the following rule set{$plural}:"); + + foreach ($ruleSetConfigs as $set => $config) { + if (null !== $config) { + $output->writeln(sprintf('* %s with config: %s', $set, Utils::toString($config))); + } else { + $output->writeln(sprintf('* %s with default config', $set)); + } + } + + $output->writeln(''); + } + } + + private function describeSet(OutputInterface $output, string $name): void + { + if (!\in_array($name, $this->getSetNames(), true)) { + throw new DescribeNameNotFoundException($name, 'set'); + } + + $ruleSetDefinitions = RuleSets::getSetDefinitions(); + $fixers = $this->getFixers(); + + $output->writeln(sprintf('Description of the `%s` set.', $ruleSetDefinitions[$name]->getName())); + $output->writeln(''); + + $output->writeln($this->replaceRstLinks($ruleSetDefinitions[$name]->getDescription())); + $output->writeln(''); + + if ($ruleSetDefinitions[$name]->isRisky()) { + $output->writeln('This set contains risky rules.'); + $output->writeln(''); + } + + $help = ''; + + foreach ($ruleSetDefinitions[$name]->getRules() as $rule => $config) { + if (str_starts_with($rule, '@')) { + $set = $ruleSetDefinitions[$rule]; + $help .= sprintf( + " * %s%s\n | %s\n\n", + $rule, + $set->isRisky() ? ' risky' : '', + $this->replaceRstLinks($set->getDescription()) + ); + + continue; + } + + /** @var FixerInterface $fixer */ + $fixer = $fixers[$rule]; + + $definition = $fixer->getDefinition(); + $help .= sprintf( + " * %s%s\n | %s\n%s\n", + $rule, + $fixer->isRisky() ? ' risky' : '', + $definition->getSummary(), + true !== $config ? sprintf(" | Configuration: %s\n", Utils::toString($config)) : '' + ); + } + + $output->write($help); + } + + /** + * @return array + */ + private function getFixers(): array + { + if (null !== $this->fixers) { + return $this->fixers; + } + + $fixers = []; + + foreach ($this->fixerFactory->getFixers() as $fixer) { + $fixers[$fixer->getName()] = $fixer; + } + + $this->fixers = $fixers; + ksort($this->fixers); + + return $this->fixers; + } + + /** + * @return string[] + */ + private function getSetNames(): array + { + if (null !== $this->setNames) { + return $this->setNames; + } + + $this->setNames = RuleSets::getSetDefinitionNames(); + + return $this->setNames; + } + + /** + * @param string $type 'rule'|'set' + */ + private function describeList(OutputInterface $output, string $type): void + { + if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) { + $describe = [ + 'sets' => $this->getSetNames(), + 'rules' => $this->getFixers(), + ]; + } elseif ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { + $describe = 'set' === $type ? ['sets' => $this->getSetNames()] : ['rules' => $this->getFixers()]; + } else { + return; + } + + /** @var string[] $items */ + foreach ($describe as $list => $items) { + $output->writeln(sprintf('Defined %s:', $list)); + + foreach ($items as $name => $item) { + $output->writeln(sprintf('* %s', \is_string($name) ? $name : $item)); + } + } + } + + private function replaceRstLinks(string $content): string + { + return Preg::replaceCallback( + '/(`[^<]+<[^>]+>`_)/', + static fn (array $matches) => Preg::replaceCallback( + '/`(.*)<(.*)>`_/', + static fn (array $matches): string => $matches[1].'('.$matches[2].')', + $matches[1] + ), + $content + ); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeNameNotFoundException.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeNameNotFoundException.php new file mode 100644 index 00000000..27f5bcfc --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeNameNotFoundException.php @@ -0,0 +1,46 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +/** + * @internal + */ +final class DescribeNameNotFoundException extends \InvalidArgumentException +{ + private string $name; + + /** + * 'rule'|'set'. + */ + private string $type; + + public function __construct(string $name, string $type) + { + $this->name = $name; + $this->type = $type; + + parent::__construct(); + } + + public function getName(): string + { + return $this->name; + } + + public function getType(): string + { + return $this->type; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DocumentationCommand.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DocumentationCommand.php new file mode 100644 index 00000000..781a13e6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DocumentationCommand.php @@ -0,0 +1,116 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Documentation\DocumentationLocator; +use PhpCsFixer\Documentation\FixerDocumentGenerator; +use PhpCsFixer\Documentation\RuleSetDocumentationGenerator; +use PhpCsFixer\FixerFactory; +use PhpCsFixer\RuleSet\RuleSets; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\Finder\Finder; +use Symfony\Component\Finder\SplFileInfo; + +/** + * @internal + */ +#[AsCommand(name: 'documentation')] +final class DocumentationCommand extends Command +{ + protected static $defaultName = 'documentation'; + + protected function configure(): void + { + $this + ->setAliases(['doc']) + ->setDescription('Dumps the documentation of the project into its "/doc" directory.') + ; + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $filesystem = new Filesystem(); + $locator = new DocumentationLocator(); + + $fixerFactory = new FixerFactory(); + $fixerFactory->registerBuiltInFixers(); + $fixers = $fixerFactory->getFixers(); + + $setDefinitions = RuleSets::getSetDefinitions(); + + $fixerDocumentGenerator = new FixerDocumentGenerator($locator); + $ruleSetDocumentationGenerator = new RuleSetDocumentationGenerator($locator); + + // Array of existing fixer docs. + // We first override existing files, and then we will delete files that are no longer needed. + // We cannot remove all files first, as generation of docs is re-using existing docs to extract code-samples for + // VersionSpecificCodeSample under incompatible PHP version. + $docForFixerRelativePaths = []; + + foreach ($fixers as $fixer) { + $docForFixerRelativePaths[] = $locator->getFixerDocumentationFileRelativePath($fixer); + $filesystem->dumpFile( + $locator->getFixerDocumentationFilePath($fixer), + $fixerDocumentGenerator->generateFixerDocumentation($fixer) + ); + } + + /** @var SplFileInfo $file */ + foreach ( + (new Finder())->files() + ->in($locator->getFixersDocumentationDirectoryPath()) + ->notPath($docForFixerRelativePaths) as $file + ) { + $filesystem->remove($file->getPathname()); + } + + // Fixer doc. index + + $filesystem->dumpFile( + $locator->getFixersDocumentationIndexFilePath(), + $fixerDocumentGenerator->generateFixersDocumentationIndex($fixers) + ); + + // RuleSet docs. + + /** @var SplFileInfo $file */ + foreach ((new Finder())->files()->in($locator->getRuleSetsDocumentationDirectoryPath()) as $file) { + $filesystem->remove($file->getPathname()); + } + + $paths = []; + + foreach ($setDefinitions as $name => $definition) { + $path = $locator->getRuleSetsDocumentationFilePath($name); + $paths[$name] = $path; + $filesystem->dumpFile($path, $ruleSetDocumentationGenerator->generateRuleSetsDocumentation($definition, $fixers)); + } + + // RuleSet doc. index + + $filesystem->dumpFile( + $locator->getRuleSetsDocumentationIndexFilePath(), + $ruleSetDocumentationGenerator->generateRuleSetsDocumentationIndex($paths) + ); + + $output->writeln('Docs updated.'); + + return 0; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommand.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommand.php new file mode 100644 index 00000000..65c408fd --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommand.php @@ -0,0 +1,359 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Config; +use PhpCsFixer\ConfigInterface; +use PhpCsFixer\ConfigurationException\InvalidConfigurationException; +use PhpCsFixer\Console\ConfigurationResolver; +use PhpCsFixer\Console\Output\ErrorOutput; +use PhpCsFixer\Console\Output\OutputContext; +use PhpCsFixer\Console\Output\Progress\ProgressOutputFactory; +use PhpCsFixer\Console\Output\Progress\ProgressOutputType; +use PhpCsFixer\Console\Report\FixReport\ReportSummary; +use PhpCsFixer\Error\ErrorsManager; +use PhpCsFixer\FixerFileProcessedEvent; +use PhpCsFixer\Runner\Runner; +use PhpCsFixer\ToolInfoInterface; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Terminal; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\Stopwatch\Stopwatch; + +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + * + * @final + * + * @internal + */ +#[AsCommand(name: 'fix', description: 'Fixes a directory or a file.')] +/* final */ class FixCommand extends Command +{ + protected static $defaultName = 'fix'; + protected static $defaultDescription = 'Fixes a directory or a file.'; + + private EventDispatcherInterface $eventDispatcher; + + private ErrorsManager $errorsManager; + + private Stopwatch $stopwatch; + + private ConfigInterface $defaultConfig; + + private ToolInfoInterface $toolInfo; + + private ProgressOutputFactory $progressOutputFactory; + + public function __construct(ToolInfoInterface $toolInfo) + { + parent::__construct(); + + $this->eventDispatcher = new EventDispatcher(); + $this->errorsManager = new ErrorsManager(); + $this->stopwatch = new Stopwatch(); + $this->defaultConfig = new Config(); + $this->toolInfo = $toolInfo; + $this->progressOutputFactory = new ProgressOutputFactory(); + } + + /** + * {@inheritdoc} + * + * Override here to only generate the help copy when used. + */ + public function getHelp(): string + { + return <<<'EOF' + The %command.name% command tries to %command.name% as much coding standards + problems as possible on a given file or files in a given directory and its subdirectories: + + $ php %command.full_name% /path/to/dir + $ php %command.full_name% /path/to/file + + By default --path-mode is set to `override`, which means, that if you specify the path to a file or a directory via + command arguments, then the paths provided to a `Finder` in config file will be ignored. You can use --path-mode=intersection + to merge paths from the config file and from the argument: + + $ php %command.full_name% --path-mode=intersection /path/to/dir + + The --format option for the output format. Supported formats are `txt` (default one), `json`, `xml`, `checkstyle`, `junit` and `gitlab`. + + NOTE: the output for the following formats are generated in accordance with schemas + + * `checkstyle` follows the common `"checkstyle" XML schema `_ + * `gitlab` follows the `codeclimate JSON schema `_ + * `json` follows the `own JSON schema `_ + * `junit` follows the `JUnit XML schema from Jenkins `_ + * `xml` follows the `own XML schema `_ + + The --quiet Do not output any message. + + The --verbose option will show the applied rules. When using the `txt` format it will also display progress notifications. + + NOTE: if there is an error like "errors reported during linting after fixing", you can use this to be even more verbose for debugging purpose + + * `-v`: verbose + * `-vv`: very verbose + * `-vvv`: debug + + The --rules option limits the rules to apply to the + project: + + EOF. /* @TODO: 4.0 - change to @PER */ <<<'EOF' + + $ php %command.full_name% /path/to/project --rules=@PSR12 + + By default the PSR-12 rules are used. + + The --rules option lets you choose the exact rules to + apply (the rule names must be separated by a comma): + + $ php %command.full_name% /path/to/dir --rules=line_ending,full_opening_tag,indentation_type + + You can also exclude the rules you don't want by placing a dash in front of the rule name, if this is more convenient, + using -name_of_fixer: + + $ php %command.full_name% /path/to/dir --rules=-full_opening_tag,-indentation_type + + When using combinations of exact and exclude rules, applying exact rules along with above excluded results: + + $ php %command.full_name% /path/to/project --rules=@Symfony,-@PSR1,-blank_line_before_statement,strict_comparison + + Complete configuration for rules can be supplied using a `json` formatted string. + + $ php %command.full_name% /path/to/project --rules='{"concat_space": {"spacing": "none"}}' + + The --dry-run flag will run the fixer without making changes to your files. + + The --diff flag can be used to let the fixer output all the changes it makes. + + The --allow-risky option (pass `yes` or `no`) allows you to set whether risky rules may run. Default value is taken from config file. + A rule is considered risky if it could change code behaviour. By default no risky rules are run. + + The --stop-on-violation flag stops the execution upon first file that needs to be fixed. + + The --show-progress option allows you to choose the way process progress is rendered: + + * none: disables progress output; + * dots: multiline progress output with number of files and percentage on each line. + + If the option is not provided, it defaults to dots unless a config file that disables output is used, in which case it defaults to none. This option has no effect if the verbosity of the command is less than verbose. + + $ php %command.full_name% --verbose --show-progress=dots + + By using --using-cache option with `yes` or `no` you can set if the caching + mechanism should be used. + + The command can also read from standard input, in which case it won't + automatically fix anything: + + $ cat foo.php | php %command.full_name% --diff - + + Finally, if you don't need BC kept on CLI level, you might use `PHP_CS_FIXER_FUTURE_MODE` to start using options that + would be default in next MAJOR release and to forbid using deprecated configuration: + + $ PHP_CS_FIXER_FUTURE_MODE=1 php %command.full_name% -v --diff + + Exit code + --------- + + Exit code of the `%command.name%` command is built using following bit flags: + + * 0 - OK. + * 1 - General error (or PHP minimal requirement not matched). + * 4 - Some files have invalid syntax (only in dry-run mode). + * 8 - Some files need fixing (only in dry-run mode). + * 16 - Configuration error of the application. + * 32 - Configuration error of a Fixer. + * 64 - Exception raised within the application. + + EOF; + } + + protected function configure(): void + { + $this->setDefinition( + [ + new InputArgument('path', InputArgument::IS_ARRAY, 'The path(s) that rules will be run against (each path can be a file or directory).'), + new InputOption('path-mode', '', InputOption::VALUE_REQUIRED, 'Specify path mode (can be `override` or `intersection`).', ConfigurationResolver::PATH_MODE_OVERRIDE), + new InputOption('allow-risky', '', InputOption::VALUE_REQUIRED, 'Are risky fixers allowed (can be `yes` or `no`).'), + new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a config file.'), + new InputOption('dry-run', '', InputOption::VALUE_NONE, 'Only shows which files would have been modified.'), + new InputOption('rules', '', InputOption::VALUE_REQUIRED, 'List of rules that should be run against configured paths.'), + new InputOption('using-cache', '', InputOption::VALUE_REQUIRED, 'Does cache should be used (can be `yes` or `no`).'), + new InputOption('cache-file', '', InputOption::VALUE_REQUIRED, 'The path to the cache file.'), + new InputOption('diff', '', InputOption::VALUE_NONE, 'Prints diff for each file.'), + new InputOption('format', '', InputOption::VALUE_REQUIRED, 'To output results in other formats.'), + new InputOption('stop-on-violation', '', InputOption::VALUE_NONE, 'Stop execution on first violation.'), + new InputOption('show-progress', '', InputOption::VALUE_REQUIRED, 'Type of progress indicator (none, dots).'), + ] + ); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $verbosity = $output->getVerbosity(); + + $passedConfig = $input->getOption('config'); + $passedRules = $input->getOption('rules'); + + if (null !== $passedConfig && null !== $passedRules) { + throw new InvalidConfigurationException('Passing both `--config` and `--rules` options is not allowed.'); + } + + $resolver = new ConfigurationResolver( + $this->defaultConfig, + [ + 'allow-risky' => $input->getOption('allow-risky'), + 'config' => $passedConfig, + 'dry-run' => $this->isDryRun($input), + 'rules' => $passedRules, + 'path' => $input->getArgument('path'), + 'path-mode' => $input->getOption('path-mode'), + 'using-cache' => $input->getOption('using-cache'), + 'cache-file' => $input->getOption('cache-file'), + 'format' => $input->getOption('format'), + 'diff' => $input->getOption('diff'), + 'stop-on-violation' => $input->getOption('stop-on-violation'), + 'verbosity' => $verbosity, + 'show-progress' => $input->getOption('show-progress'), + ], + getcwd(), + $this->toolInfo + ); + + $reporter = $resolver->getReporter(); + + $stdErr = $output instanceof ConsoleOutputInterface + ? $output->getErrorOutput() + : ('txt' === $reporter->getFormat() ? $output : null); + + if (null !== $stdErr) { + if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) { + $stdErr->writeln($this->getApplication()->getLongVersion()); + } + + $configFile = $resolver->getConfigFile(); + $stdErr->writeln(sprintf('Loaded config %s%s.', $resolver->getConfig()->getName(), null === $configFile ? '' : ' from "'.$configFile.'"')); + + if ($resolver->getUsingCache()) { + $cacheFile = $resolver->getCacheFile(); + + if (is_file($cacheFile)) { + $stdErr->writeln(sprintf('Using cache file "%s".', $cacheFile)); + } + } + } + + $finder = new \ArrayIterator(iterator_to_array($resolver->getFinder())); + + if (null !== $stdErr && $resolver->configFinderIsOverridden()) { + $stdErr->writeln( + sprintf($stdErr->isDecorated() ? '%s' : '%s', 'Paths from configuration file have been overridden by paths provided as command arguments.') + ); + } + + $progressType = $resolver->getProgressType(); + $progressOutput = $this->progressOutputFactory->create( + $progressType, + new OutputContext( + $stdErr, + (new Terminal())->getWidth(), + \count($finder) + ) + ); + + $runner = new Runner( + $finder, + $resolver->getFixers(), + $resolver->getDiffer(), + ProgressOutputType::NONE !== $progressType ? $this->eventDispatcher : null, + $this->errorsManager, + $resolver->getLinter(), + $resolver->isDryRun(), + $resolver->getCacheManager(), + $resolver->getDirectory(), + $resolver->shouldStopOnViolation() + ); + + $this->eventDispatcher->addListener(FixerFileProcessedEvent::NAME, [$progressOutput, 'onFixerFileProcessed']); + $this->stopwatch->start('fixFiles'); + $changed = $runner->fix(); + $this->stopwatch->stop('fixFiles'); + $this->eventDispatcher->removeListener(FixerFileProcessedEvent::NAME, [$progressOutput, 'onFixerFileProcessed']); + + $progressOutput->printLegend(); + + $fixEvent = $this->stopwatch->getEvent('fixFiles'); + + $reportSummary = new ReportSummary( + $changed, + \count($finder), + $fixEvent->getDuration(), + $fixEvent->getMemory(), + OutputInterface::VERBOSITY_VERBOSE <= $verbosity, + $resolver->isDryRun(), + $output->isDecorated() + ); + + $output->isDecorated() + ? $output->write($reporter->generate($reportSummary)) + : $output->write($reporter->generate($reportSummary), false, OutputInterface::OUTPUT_RAW); + + $invalidErrors = $this->errorsManager->getInvalidErrors(); + $exceptionErrors = $this->errorsManager->getExceptionErrors(); + $lintErrors = $this->errorsManager->getLintErrors(); + + if (null !== $stdErr) { + $errorOutput = new ErrorOutput($stdErr); + + if (\count($invalidErrors) > 0) { + $errorOutput->listErrors('linting before fixing', $invalidErrors); + } + + if (\count($exceptionErrors) > 0) { + $errorOutput->listErrors('fixing', $exceptionErrors); + } + + if (\count($lintErrors) > 0) { + $errorOutput->listErrors('linting after fixing', $lintErrors); + } + } + + $exitStatusCalculator = new FixCommandExitStatusCalculator(); + + return $exitStatusCalculator->calculate( + $resolver->isDryRun(), + \count($changed) > 0, + \count($invalidErrors) > 0, + \count($exceptionErrors) > 0, + \count($lintErrors) > 0 + ); + } + + protected function isDryRun(InputInterface $input): bool + { + return $input->getOption('dry-run'); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommandExitStatusCalculator.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommandExitStatusCalculator.php new file mode 100644 index 00000000..727dfff5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommandExitStatusCalculator.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class FixCommandExitStatusCalculator +{ + // Exit status 1 is reserved for environment constraints not matched. + public const EXIT_STATUS_FLAG_HAS_INVALID_FILES = 4; + public const EXIT_STATUS_FLAG_HAS_CHANGED_FILES = 8; + public const EXIT_STATUS_FLAG_HAS_INVALID_CONFIG = 16; + public const EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG = 32; + public const EXIT_STATUS_FLAG_EXCEPTION_IN_APP = 64; + + public function calculate(bool $isDryRun, bool $hasChangedFiles, bool $hasInvalidErrors, bool $hasExceptionErrors, bool $hasLintErrorsAfterFixing): int + { + $exitStatus = 0; + + if ($isDryRun) { + if ($hasChangedFiles) { + $exitStatus |= self::EXIT_STATUS_FLAG_HAS_CHANGED_FILES; + } + + if ($hasInvalidErrors) { + $exitStatus |= self::EXIT_STATUS_FLAG_HAS_INVALID_FILES; + } + } + + if ($hasExceptionErrors || $hasLintErrorsAfterFixing) { + $exitStatus |= self::EXIT_STATUS_FLAG_EXCEPTION_IN_APP; + } + + return $exitStatus; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/HelpCommand.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/HelpCommand.php new file mode 100644 index 00000000..6dace362 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/HelpCommand.php @@ -0,0 +1,76 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerOptionInterface; +use PhpCsFixer\Utils; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\HelpCommand as BaseHelpCommand; +use Symfony\Component\Console\Formatter\OutputFormatterStyle; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + * + * @internal + */ +#[AsCommand(name: 'help')] +final class HelpCommand extends BaseHelpCommand +{ + protected static $defaultName = 'help'; + + /** + * Returns the allowed values of the given option that can be converted to a string. + * + * @return null|list + */ + public static function getDisplayableAllowedValues(FixerOptionInterface $option): ?array + { + $allowed = $option->getAllowedValues(); + + if (null !== $allowed) { + $allowed = array_filter($allowed, static fn ($value): bool => !$value instanceof \Closure); + + usort($allowed, static function ($valueA, $valueB): int { + if ($valueA instanceof AllowedValueSubset) { + return -1; + } + + if ($valueB instanceof AllowedValueSubset) { + return 1; + } + + return strcasecmp( + Utils::toString($valueA), + Utils::toString($valueB) + ); + }); + + if (0 === \count($allowed)) { + $allowed = null; + } + } + + return $allowed; + } + + protected function initialize(InputInterface $input, OutputInterface $output): void + { + $output->getFormatter()->setStyle('url', new OutputFormatterStyle('blue')); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListFilesCommand.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListFilesCommand.php new file mode 100644 index 00000000..93549116 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListFilesCommand.php @@ -0,0 +1,91 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Config; +use PhpCsFixer\ConfigInterface; +use PhpCsFixer\Console\ConfigurationResolver; +use PhpCsFixer\ToolInfoInterface; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Filesystem\Path; + +/** + * @author Markus Staab + * + * @internal + */ +#[AsCommand(name: 'list-files')] +final class ListFilesCommand extends Command +{ + protected static $defaultName = 'list-files'; + + private ConfigInterface $defaultConfig; + + private ToolInfoInterface $toolInfo; + + public function __construct(ToolInfoInterface $toolInfo) + { + parent::__construct(); + + $this->defaultConfig = new Config(); + $this->toolInfo = $toolInfo; + } + + protected function configure(): void + { + $this + ->setDefinition( + [ + new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a .php-cs-fixer.php file.'), + ] + ) + ->setDescription('List all files being fixed by the given config.') + ; + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $passedConfig = $input->getOption('config'); + $cwd = getcwd(); + + $resolver = new ConfigurationResolver( + $this->defaultConfig, + [ + 'config' => $passedConfig, + ], + $cwd, + $this->toolInfo + ); + + $finder = $resolver->getFinder(); + + /** @var \SplFileInfo $file */ + foreach ($finder as $file) { + if ($file->isFile()) { + $relativePath = './'.Path::makeRelative($file->getRealPath(), $cwd); + // unify directory separators across operating system + $relativePath = str_replace('/', \DIRECTORY_SEPARATOR, $relativePath); + + $output->writeln(escapeshellarg($relativePath)); + } + } + + return 0; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListSetsCommand.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListSetsCommand.php new file mode 100644 index 00000000..4279c59a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListSetsCommand.php @@ -0,0 +1,87 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\ConfigurationException\InvalidConfigurationException; +use PhpCsFixer\Console\Report\ListSetsReport\ReporterFactory; +use PhpCsFixer\Console\Report\ListSetsReport\ReporterInterface; +use PhpCsFixer\Console\Report\ListSetsReport\ReportSummary; +use PhpCsFixer\Console\Report\ListSetsReport\TextReporter; +use PhpCsFixer\RuleSet\RuleSets; +use PhpCsFixer\Utils; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +#[AsCommand(name: 'list-sets')] +final class ListSetsCommand extends Command +{ + protected static $defaultName = 'list-sets'; + + protected function configure(): void + { + $this + ->setDefinition( + [ + new InputOption('format', '', InputOption::VALUE_REQUIRED, 'To output results in other formats.', (new TextReporter())->getFormat()), + ] + ) + ->setDescription('List all available RuleSets.') + ; + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $reporter = $this->resolveReporterWithFactory( + $input->getOption('format'), + new ReporterFactory() + ); + + $reportSummary = new ReportSummary( + array_values(RuleSets::getSetDefinitions()) + ); + + $report = $reporter->generate($reportSummary); + + $output->isDecorated() + ? $output->write(OutputFormatter::escape($report)) + : $output->write($report, false, OutputInterface::OUTPUT_RAW); + + return 0; + } + + private function resolveReporterWithFactory(string $format, ReporterFactory $factory): ReporterInterface + { + try { + $factory->registerBuiltInReporters(); + $reporter = $factory->getReporter($format); + } catch (\UnexpectedValueException $e) { + $formats = $factory->getFormats(); + sort($formats); + + throw new InvalidConfigurationException(sprintf('The format "%s" is not defined, supported are %s.', $format, Utils::naturalLanguageJoin($formats))); + } + + return $reporter; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/SelfUpdateCommand.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/SelfUpdateCommand.php new file mode 100644 index 00000000..5e4bddc9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Command/SelfUpdateCommand.php @@ -0,0 +1,171 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Console\SelfUpdate\NewVersionCheckerInterface; +use PhpCsFixer\PharCheckerInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\ToolInfoInterface; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Igor Wiedler + * @author Stephane PY + * @author Grégoire Pineau + * @author Dariusz Rumiński + * + * @internal + */ +#[AsCommand(name: 'self-update')] +final class SelfUpdateCommand extends Command +{ + protected static $defaultName = 'self-update'; + + private NewVersionCheckerInterface $versionChecker; + + private ToolInfoInterface $toolInfo; + + private PharCheckerInterface $pharChecker; + + public function __construct( + NewVersionCheckerInterface $versionChecker, + ToolInfoInterface $toolInfo, + PharCheckerInterface $pharChecker + ) { + parent::__construct(); + + $this->versionChecker = $versionChecker; + $this->toolInfo = $toolInfo; + $this->pharChecker = $pharChecker; + } + + protected function configure(): void + { + $this + ->setAliases(['selfupdate']) + ->setDefinition( + [ + new InputOption('--force', '-f', InputOption::VALUE_NONE, 'Force update to next major version if available.'), + ] + ) + ->setDescription('Update php-cs-fixer.phar to the latest stable version.') + ->setHelp( + <<<'EOT' + The %command.name% command replace your php-cs-fixer.phar by the + latest version released on: + https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/releases + + $ php php-cs-fixer.phar %command.name% + + EOT + ) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity() && $output instanceof ConsoleOutputInterface) { + $stdErr = $output->getErrorOutput(); + $stdErr->writeln($this->getApplication()->getLongVersion()); + } + + if (!$this->toolInfo->isInstalledAsPhar()) { + $output->writeln('Self-update is available only for PHAR version.'); + + return 1; + } + + $currentVersion = $this->getApplication()->getVersion(); + Preg::match('/^v?(?\d+)\./', $currentVersion, $matches); + $currentMajor = (int) $matches['major']; + + try { + $latestVersion = $this->versionChecker->getLatestVersion(); + $latestVersionOfCurrentMajor = $this->versionChecker->getLatestVersionOfMajor($currentMajor); + } catch (\Exception $exception) { + $output->writeln(sprintf( + 'Unable to determine newest version: %s', + $exception->getMessage() + )); + + return 1; + } + + if (1 !== $this->versionChecker->compareVersions($latestVersion, $currentVersion)) { + $output->writeln('PHP CS Fixer is already up-to-date.'); + + return 0; + } + + $remoteTag = $latestVersion; + + if ( + 0 !== $this->versionChecker->compareVersions($latestVersionOfCurrentMajor, $latestVersion) + && true !== $input->getOption('force') + ) { + $output->writeln(sprintf('A new major version of PHP CS Fixer is available (%s)', $latestVersion)); + $output->writeln(sprintf('Before upgrading please read https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/%s/UPGRADE-v%s.md', $latestVersion, $currentMajor + 1)); + $output->writeln('If you are ready to upgrade run this command with -f'); + $output->writeln('Checking for new minor/patch version...'); + + if (1 !== $this->versionChecker->compareVersions($latestVersionOfCurrentMajor, $currentVersion)) { + $output->writeln('No minor update for PHP CS Fixer.'); + + return 0; + } + + $remoteTag = $latestVersionOfCurrentMajor; + } + + $localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0]; + + if (!is_writable($localFilename)) { + $output->writeln(sprintf('No permission to update "%s" file.', $localFilename)); + + return 1; + } + + $tempFilename = \dirname($localFilename).'/'.basename($localFilename, '.phar').'-tmp.phar'; + $remoteFilename = $this->toolInfo->getPharDownloadUri($remoteTag); + + if (false === @copy($remoteFilename, $tempFilename)) { + $output->writeln(sprintf('Unable to download new version %s from the server.', $remoteTag)); + + return 1; + } + + chmod($tempFilename, 0777 & ~umask()); + + $pharInvalidityReason = $this->pharChecker->checkFileValidity($tempFilename); + if (null !== $pharInvalidityReason) { + unlink($tempFilename); + $output->writeln(sprintf('The download of %s is corrupt (%s).', $remoteTag, $pharInvalidityReason)); + $output->writeln('Please re-run the "self-update" command to try again.'); + + return 1; + } + + rename($tempFilename, $localFilename); + + $output->writeln(sprintf('PHP CS Fixer updated (%s -> %s)', $currentVersion, $remoteTag)); + + return 0; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/ConfigurationResolver.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/ConfigurationResolver.php new file mode 100644 index 00000000..5b2a398f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/ConfigurationResolver.php @@ -0,0 +1,953 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console; + +use PhpCsFixer\Cache\CacheManagerInterface; +use PhpCsFixer\Cache\Directory; +use PhpCsFixer\Cache\DirectoryInterface; +use PhpCsFixer\Cache\FileCacheManager; +use PhpCsFixer\Cache\FileHandler; +use PhpCsFixer\Cache\NullCacheManager; +use PhpCsFixer\Cache\Signature; +use PhpCsFixer\ConfigInterface; +use PhpCsFixer\ConfigurationException\InvalidConfigurationException; +use PhpCsFixer\Console\Output\Progress\ProgressOutputType; +use PhpCsFixer\Console\Report\FixReport\ReporterFactory; +use PhpCsFixer\Console\Report\FixReport\ReporterInterface; +use PhpCsFixer\Differ\DifferInterface; +use PhpCsFixer\Differ\NullDiffer; +use PhpCsFixer\Differ\UnifiedDiffer; +use PhpCsFixer\Finder; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\FixerFactory; +use PhpCsFixer\Linter\Linter; +use PhpCsFixer\Linter\LinterInterface; +use PhpCsFixer\RuleSet\RuleSet; +use PhpCsFixer\RuleSet\RuleSetInterface; +use PhpCsFixer\StdinFileInfo; +use PhpCsFixer\ToolInfoInterface; +use PhpCsFixer\Utils; +use PhpCsFixer\WhitespacesFixerConfig; +use PhpCsFixer\WordMatcher; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\Finder\Finder as SymfonyFinder; + +/** + * The resolver that resolves configuration to use by command line options and config. + * + * @author Fabien Potencier + * @author Katsuhiro Ogawa + * @author Dariusz Rumiński + * + * @internal + */ +final class ConfigurationResolver +{ + public const PATH_MODE_OVERRIDE = 'override'; + public const PATH_MODE_INTERSECTION = 'intersection'; + + /** + * @var null|bool + */ + private $allowRisky; + + /** + * @var null|ConfigInterface + */ + private $config; + + /** + * @var null|string + */ + private $configFile; + + private string $cwd; + + private ConfigInterface $defaultConfig; + + /** + * @var null|ReporterInterface + */ + private $reporter; + + /** + * @var null|bool + */ + private $isStdIn; + + /** + * @var null|bool + */ + private $isDryRun; + + /** + * @var null|FixerInterface[] + */ + private $fixers; + + /** + * @var null|bool + */ + private $configFinderIsOverridden; + + private ToolInfoInterface $toolInfo; + + /** + * @var array + */ + private array $options = [ + 'allow-risky' => null, + 'cache-file' => null, + 'config' => null, + 'diff' => null, + 'dry-run' => null, + 'format' => null, + 'path' => [], + 'path-mode' => self::PATH_MODE_OVERRIDE, + 'rules' => null, + 'show-progress' => null, + 'stop-on-violation' => null, + 'using-cache' => null, + 'verbosity' => null, + ]; + + /** + * @var null|string + */ + private $cacheFile; + + /** + * @var null|CacheManagerInterface + */ + private $cacheManager; + + /** + * @var null|DifferInterface + */ + private $differ; + + /** + * @var null|Directory + */ + private $directory; + + /** + * @var null|iterable<\SplFileInfo> + */ + private ?iterable $finder = null; + + private ?string $format = null; + + /** + * @var null|Linter + */ + private $linter; + + /** + * @var null|list + */ + private ?array $path = null; + + /** + * @var null|string + */ + private $progress; + + /** + * @var null|RuleSet + */ + private $ruleSet; + + /** + * @var null|bool + */ + private $usingCache; + + /** + * @var FixerFactory + */ + private $fixerFactory; + + /** + * @param array $options + */ + public function __construct( + ConfigInterface $config, + array $options, + string $cwd, + ToolInfoInterface $toolInfo + ) { + $this->defaultConfig = $config; + $this->cwd = $cwd; + $this->toolInfo = $toolInfo; + + foreach ($options as $name => $value) { + $this->setOption($name, $value); + } + } + + public function getCacheFile(): ?string + { + if (!$this->getUsingCache()) { + return null; + } + + if (null === $this->cacheFile) { + if (null === $this->options['cache-file']) { + $this->cacheFile = $this->getConfig()->getCacheFile(); + } else { + $this->cacheFile = $this->options['cache-file']; + } + } + + return $this->cacheFile; + } + + public function getCacheManager(): CacheManagerInterface + { + if (null === $this->cacheManager) { + $cacheFile = $this->getCacheFile(); + + if (null === $cacheFile) { + $this->cacheManager = new NullCacheManager(); + } else { + $this->cacheManager = new FileCacheManager( + new FileHandler($cacheFile), + new Signature( + PHP_VERSION, + $this->toolInfo->getVersion(), + $this->getConfig()->getIndent(), + $this->getConfig()->getLineEnding(), + $this->getRules() + ), + $this->isDryRun(), + $this->getDirectory() + ); + } + } + + return $this->cacheManager; + } + + public function getConfig(): ConfigInterface + { + if (null === $this->config) { + foreach ($this->computeConfigFiles() as $configFile) { + if (!file_exists($configFile)) { + continue; + } + + $configFileBasename = basename($configFile); + $deprecatedConfigs = [ + '.php_cs' => '.php-cs-fixer.php', + '.php_cs.dist' => '.php-cs-fixer.dist.php', + ]; + + if (isset($deprecatedConfigs[$configFileBasename])) { + throw new InvalidConfigurationException("Configuration file `{$configFileBasename}` is outdated, rename to `{$deprecatedConfigs[$configFileBasename]}`."); + } + + $this->config = self::separatedContextLessInclude($configFile); + $this->configFile = $configFile; + + break; + } + + if (null === $this->config) { + $this->config = $this->defaultConfig; + } + } + + return $this->config; + } + + public function getConfigFile(): ?string + { + if (null === $this->configFile) { + $this->getConfig(); + } + + return $this->configFile; + } + + public function getDiffer(): DifferInterface + { + if (null === $this->differ) { + $this->differ = (true === $this->options['diff']) ? new UnifiedDiffer() : new NullDiffer(); + } + + return $this->differ; + } + + public function getDirectory(): DirectoryInterface + { + if (null === $this->directory) { + $path = $this->getCacheFile(); + if (null === $path) { + $absolutePath = $this->cwd; + } else { + $filesystem = new Filesystem(); + + $absolutePath = $filesystem->isAbsolutePath($path) + ? $path + : $this->cwd.\DIRECTORY_SEPARATOR.$path; + $absolutePath = \dirname($absolutePath); + } + + $this->directory = new Directory($absolutePath); + } + + return $this->directory; + } + + /** + * @return FixerInterface[] An array of FixerInterface + */ + public function getFixers(): array + { + if (null === $this->fixers) { + $this->fixers = $this->createFixerFactory() + ->useRuleSet($this->getRuleSet()) + ->setWhitespacesConfig(new WhitespacesFixerConfig($this->config->getIndent(), $this->config->getLineEnding())) + ->getFixers() + ; + + if (false === $this->getRiskyAllowed()) { + $riskyFixers = array_map( + static fn (FixerInterface $fixer): string => $fixer->getName(), + array_filter( + $this->fixers, + static fn (FixerInterface $fixer): bool => $fixer->isRisky() + ) + ); + + if (\count($riskyFixers) > 0) { + throw new InvalidConfigurationException(sprintf('The rules contain risky fixers (%s), but they are not allowed to run. Perhaps you forget to use --allow-risky=yes option?', Utils::naturalLanguageJoin($riskyFixers))); + } + } + } + + return $this->fixers; + } + + public function getLinter(): LinterInterface + { + if (null === $this->linter) { + $this->linter = new Linter(); + } + + return $this->linter; + } + + /** + * Returns path. + * + * @return string[] + */ + public function getPath(): array + { + if (null === $this->path) { + $filesystem = new Filesystem(); + $cwd = $this->cwd; + + if (1 === \count($this->options['path']) && '-' === $this->options['path'][0]) { + $this->path = $this->options['path']; + } else { + $this->path = array_map( + static function (string $rawPath) use ($cwd, $filesystem): string { + $path = trim($rawPath); + + if ('' === $path) { + throw new InvalidConfigurationException("Invalid path: \"{$rawPath}\"."); + } + + $absolutePath = $filesystem->isAbsolutePath($path) + ? $path + : $cwd.\DIRECTORY_SEPARATOR.$path; + + if (!file_exists($absolutePath)) { + throw new InvalidConfigurationException(sprintf( + 'The path "%s" is not readable.', + $path + )); + } + + return $absolutePath; + }, + $this->options['path'] + ); + } + } + + return $this->path; + } + + /** + * @throws InvalidConfigurationException + */ + public function getProgressType(): string + { + if (null === $this->progress) { + if (OutputInterface::VERBOSITY_VERBOSE <= $this->options['verbosity'] && 'txt' === $this->getFormat()) { + $progressType = $this->options['show-progress']; + + if (null === $progressType) { + $progressType = $this->getConfig()->getHideProgress() + ? ProgressOutputType::NONE + : ProgressOutputType::DOTS; + } elseif (!\in_array($progressType, ProgressOutputType::AVAILABLE, true)) { + throw new InvalidConfigurationException(sprintf( + 'The progress type "%s" is not defined, supported are %s.', + $progressType, + Utils::naturalLanguageJoin(ProgressOutputType::AVAILABLE) + )); + } + + $this->progress = $progressType; + } else { + $this->progress = ProgressOutputType::NONE; + } + } + + return $this->progress; + } + + public function getReporter(): ReporterInterface + { + if (null === $this->reporter) { + $reporterFactory = new ReporterFactory(); + $reporterFactory->registerBuiltInReporters(); + + $format = $this->getFormat(); + + try { + $this->reporter = $reporterFactory->getReporter($format); + } catch (\UnexpectedValueException $e) { + $formats = $reporterFactory->getFormats(); + sort($formats); + + throw new InvalidConfigurationException(sprintf('The format "%s" is not defined, supported are %s.', $format, Utils::naturalLanguageJoin($formats))); + } + } + + return $this->reporter; + } + + public function getRiskyAllowed(): bool + { + if (null === $this->allowRisky) { + if (null === $this->options['allow-risky']) { + $this->allowRisky = $this->getConfig()->getRiskyAllowed(); + } else { + $this->allowRisky = $this->resolveOptionBooleanValue('allow-risky'); + } + } + + return $this->allowRisky; + } + + /** + * Returns rules. + * + * @return array|bool> + */ + public function getRules(): array + { + return $this->getRuleSet()->getRules(); + } + + public function getUsingCache(): bool + { + if (null === $this->usingCache) { + if (null === $this->options['using-cache']) { + $this->usingCache = $this->getConfig()->getUsingCache(); + } else { + $this->usingCache = $this->resolveOptionBooleanValue('using-cache'); + } + } + + $this->usingCache = $this->usingCache && ($this->toolInfo->isInstalledAsPhar() || $this->toolInfo->isInstalledByComposer()); + + return $this->usingCache; + } + + /** + * @return iterable<\SplFileInfo> + */ + public function getFinder(): iterable + { + if (null === $this->finder) { + $this->finder = $this->resolveFinder(); + } + + return $this->finder; + } + + /** + * Returns dry-run flag. + */ + public function isDryRun(): bool + { + if (null === $this->isDryRun) { + if ($this->isStdIn()) { + // Can't write to STDIN + $this->isDryRun = true; + } else { + $this->isDryRun = $this->options['dry-run']; + } + } + + return $this->isDryRun; + } + + public function shouldStopOnViolation(): bool + { + return $this->options['stop-on-violation']; + } + + public function configFinderIsOverridden(): bool + { + if (null === $this->configFinderIsOverridden) { + $this->resolveFinder(); + } + + return $this->configFinderIsOverridden; + } + + /** + * Compute file candidates for config file. + * + * @return string[] + */ + private function computeConfigFiles(): array + { + $configFile = $this->options['config']; + + if (null !== $configFile) { + if (false === file_exists($configFile) || false === is_readable($configFile)) { + throw new InvalidConfigurationException(sprintf('Cannot read config file "%s".', $configFile)); + } + + return [$configFile]; + } + + $path = $this->getPath(); + + if ($this->isStdIn() || 0 === \count($path)) { + $configDir = $this->cwd; + } elseif (1 < \count($path)) { + throw new InvalidConfigurationException('For multiple paths config parameter is required.'); + } elseif (!is_file($path[0])) { + $configDir = $path[0]; + } else { + $dirName = pathinfo($path[0], PATHINFO_DIRNAME); + $configDir = $dirName ?: $path[0]; + } + + $candidates = [ + $configDir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php', + $configDir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php', + $configDir.\DIRECTORY_SEPARATOR.'.php_cs', // old v2 config, present here only to throw nice error message later + $configDir.\DIRECTORY_SEPARATOR.'.php_cs.dist', // old v2 config, present here only to throw nice error message later + ]; + + if ($configDir !== $this->cwd) { + $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php'; + $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php'; + $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php_cs'; // old v2 config, present here only to throw nice error message later + $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php_cs.dist'; // old v2 config, present here only to throw nice error message later + } + + return $candidates; + } + + private function createFixerFactory(): FixerFactory + { + if (null === $this->fixerFactory) { + $fixerFactory = new FixerFactory(); + $fixerFactory->registerBuiltInFixers(); + $fixerFactory->registerCustomFixers($this->getConfig()->getCustomFixers()); + + $this->fixerFactory = $fixerFactory; + } + + return $this->fixerFactory; + } + + private function getFormat(): string + { + if (null === $this->format) { + $this->format = $this->options['format'] ?? $this->getConfig()->getFormat(); + } + + return $this->format; + } + + private function getRuleSet(): RuleSetInterface + { + if (null === $this->ruleSet) { + $rules = $this->parseRules(); + $this->validateRules($rules); + + $this->ruleSet = new RuleSet($rules); + } + + return $this->ruleSet; + } + + private function isStdIn(): bool + { + if (null === $this->isStdIn) { + $this->isStdIn = 1 === \count($this->options['path']) && '-' === $this->options['path'][0]; + } + + return $this->isStdIn; + } + + /** + * @template T + * + * @param iterable $iterable + * + * @return \Traversable + */ + private function iterableToTraversable(iterable $iterable): \Traversable + { + return \is_array($iterable) ? new \ArrayIterator($iterable) : $iterable; + } + + /** + * @return array + */ + private function parseRules(): array + { + if (null === $this->options['rules']) { + return $this->getConfig()->getRules(); + } + + $rules = trim($this->options['rules']); + if ('' === $rules) { + throw new InvalidConfigurationException('Empty rules value is not allowed.'); + } + + if (str_starts_with($rules, '{')) { + $rules = json_decode($rules, true); + + if (JSON_ERROR_NONE !== json_last_error()) { + throw new InvalidConfigurationException(sprintf('Invalid JSON rules input: "%s".', json_last_error_msg())); + } + + return $rules; + } + + $rules = []; + + foreach (explode(',', $this->options['rules']) as $rule) { + $rule = trim($rule); + + if ('' === $rule) { + throw new InvalidConfigurationException('Empty rule name is not allowed.'); + } + + if (str_starts_with($rule, '-')) { + $rules[substr($rule, 1)] = false; + } else { + $rules[$rule] = true; + } + } + + return $rules; + } + + /** + * @param array $rules + * + * @throws InvalidConfigurationException + */ + private function validateRules(array $rules): void + { + /** + * Create a ruleset that contains all configured rules, even when they originally have been disabled. + * + * @see RuleSet::resolveSet() + */ + $ruleSet = []; + + foreach ($rules as $key => $value) { + if (\is_int($key)) { + throw new InvalidConfigurationException(sprintf('Missing value for "%s" rule/set.', $value)); + } + + $ruleSet[$key] = true; + } + + $ruleSet = new RuleSet($ruleSet); + + $configuredFixers = array_keys($ruleSet->getRules()); + + $fixers = $this->createFixerFactory()->getFixers(); + + $availableFixers = array_map(static fn (FixerInterface $fixer): string => $fixer->getName(), $fixers); + + $unknownFixers = array_diff($configuredFixers, $availableFixers); + + if (\count($unknownFixers) > 0) { + $renamedRules = [ + 'blank_line_before_return' => [ + 'new_name' => 'blank_line_before_statement', + 'config' => ['statements' => ['return']], + ], + 'final_static_access' => [ + 'new_name' => 'self_static_accessor', + ], + 'hash_to_slash_comment' => [ + 'new_name' => 'single_line_comment_style', + 'config' => ['comment_types' => ['hash']], + ], + 'lowercase_constants' => [ + 'new_name' => 'constant_case', + 'config' => ['case' => 'lower'], + ], + 'no_extra_consecutive_blank_lines' => [ + 'new_name' => 'no_extra_blank_lines', + ], + 'no_multiline_whitespace_before_semicolons' => [ + 'new_name' => 'multiline_whitespace_before_semicolons', + ], + 'no_short_echo_tag' => [ + 'new_name' => 'echo_tag_syntax', + 'config' => ['format' => 'long'], + ], + 'php_unit_ordered_covers' => [ + 'new_name' => 'phpdoc_order_by_value', + 'config' => ['annotations' => ['covers']], + ], + 'phpdoc_inline_tag' => [ + 'new_name' => 'general_phpdoc_tag_rename, phpdoc_inline_tag_normalizer and phpdoc_tag_type', + ], + 'pre_increment' => [ + 'new_name' => 'increment_style', + 'config' => ['style' => 'pre'], + ], + 'psr0' => [ + 'new_name' => 'psr_autoloading', + 'config' => ['dir' => 'x'], + ], + 'psr4' => [ + 'new_name' => 'psr_autoloading', + ], + 'silenced_deprecation_error' => [ + 'new_name' => 'error_suppression', + ], + 'trailing_comma_in_multiline_array' => [ + 'new_name' => 'trailing_comma_in_multiline', + 'config' => ['elements' => ['arrays']], + ], + ]; + + $message = 'The rules contain unknown fixers: '; + $hasOldRule = false; + + foreach ($unknownFixers as $unknownFixer) { + if (isset($renamedRules[$unknownFixer])) { // Check if present as old renamed rule + $hasOldRule = true; + $message .= sprintf( + '"%s" is renamed (did you mean "%s"?%s), ', + $unknownFixer, + $renamedRules[$unknownFixer]['new_name'], + isset($renamedRules[$unknownFixer]['config']) ? ' (note: use configuration "'.Utils::toString($renamedRules[$unknownFixer]['config']).'")' : '' + ); + } else { // Go to normal matcher if it is not a renamed rule + $matcher = new WordMatcher($availableFixers); + $alternative = $matcher->match($unknownFixer); + $message .= sprintf( + '"%s"%s, ', + $unknownFixer, + null === $alternative ? '' : ' (did you mean "'.$alternative.'"?)' + ); + } + } + + $message = substr($message, 0, -2).'.'; + + if ($hasOldRule) { + $message .= "\nFor more info about updating see: https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/v3.0.0/UPGRADE-v3.md#renamed-ruless."; + } + + throw new InvalidConfigurationException($message); + } + + foreach ($fixers as $fixer) { + $fixerName = $fixer->getName(); + if (isset($rules[$fixerName]) && $fixer instanceof DeprecatedFixerInterface) { + $successors = $fixer->getSuccessorsNames(); + $messageEnd = [] === $successors + ? sprintf(' and will be removed in version %d.0.', Application::getMajorVersion() + 1) + : sprintf('. Use %s instead.', str_replace('`', '"', Utils::naturalLanguageJoinWithBackticks($successors))); + + Utils::triggerDeprecation(new \RuntimeException("Rule \"{$fixerName}\" is deprecated{$messageEnd}")); + } + } + } + + /** + * Apply path on config instance. + * + * @return iterable<\SplFileInfo> + */ + private function resolveFinder(): iterable + { + $this->configFinderIsOverridden = false; + + if ($this->isStdIn()) { + return new \ArrayIterator([new StdinFileInfo()]); + } + + $modes = [self::PATH_MODE_OVERRIDE, self::PATH_MODE_INTERSECTION]; + + if (!\in_array( + $this->options['path-mode'], + $modes, + true + )) { + throw new InvalidConfigurationException(sprintf( + 'The path-mode "%s" is not defined, supported are %s.', + $this->options['path-mode'], + Utils::naturalLanguageJoin($modes) + )); + } + + $isIntersectionPathMode = self::PATH_MODE_INTERSECTION === $this->options['path-mode']; + + $paths = array_filter(array_map( + static fn (string $path) => realpath($path), + $this->getPath() + )); + + if (0 === \count($paths)) { + if ($isIntersectionPathMode) { + return new \ArrayIterator([]); + } + + return $this->iterableToTraversable($this->getConfig()->getFinder()); + } + + $pathsByType = [ + 'file' => [], + 'dir' => [], + ]; + + foreach ($paths as $path) { + if (is_file($path)) { + $pathsByType['file'][] = $path; + } else { + $pathsByType['dir'][] = $path.\DIRECTORY_SEPARATOR; + } + } + + $nestedFinder = null; + $currentFinder = $this->iterableToTraversable($this->getConfig()->getFinder()); + + try { + $nestedFinder = $currentFinder instanceof \IteratorAggregate ? $currentFinder->getIterator() : $currentFinder; + } catch (\Exception $e) { + } + + if ($isIntersectionPathMode) { + if (null === $nestedFinder) { + throw new InvalidConfigurationException( + 'Cannot create intersection with not-fully defined Finder in configuration file.' + ); + } + + return new \CallbackFilterIterator( + new \IteratorIterator($nestedFinder), + static function (\SplFileInfo $current) use ($pathsByType): bool { + $currentRealPath = $current->getRealPath(); + + if (\in_array($currentRealPath, $pathsByType['file'], true)) { + return true; + } + + foreach ($pathsByType['dir'] as $path) { + if (str_starts_with($currentRealPath, $path)) { + return true; + } + } + + return false; + } + ); + } + + if (null !== $this->getConfigFile() && null !== $nestedFinder) { + $this->configFinderIsOverridden = true; + } + + if ($currentFinder instanceof SymfonyFinder && null === $nestedFinder) { + // finder from configuration Symfony finder and it is not fully defined, we may fulfill it + return $currentFinder->in($pathsByType['dir'])->append($pathsByType['file']); + } + + return Finder::create()->in($pathsByType['dir'])->append($pathsByType['file']); + } + + /** + * Set option that will be resolved. + * + * @param mixed $value + */ + private function setOption(string $name, $value): void + { + if (!\array_key_exists($name, $this->options)) { + throw new InvalidConfigurationException(sprintf('Unknown option name: "%s".', $name)); + } + + $this->options[$name] = $value; + } + + private function resolveOptionBooleanValue(string $optionName): bool + { + $value = $this->options[$optionName]; + + if (!\is_string($value)) { + throw new InvalidConfigurationException(sprintf('Expected boolean or string value for option "%s".', $optionName)); + } + + if ('yes' === $value) { + return true; + } + + if ('no' === $value) { + return false; + } + + throw new InvalidConfigurationException(sprintf('Expected "yes" or "no" for option "%s", got "%s".', $optionName, $value)); + } + + private static function separatedContextLessInclude(string $path): ConfigInterface + { + $config = include $path; + + // verify that the config has an instance of Config + if (!$config instanceof ConfigInterface) { + throw new InvalidConfigurationException(sprintf('The config file: "%s" does not return a "PhpCsFixer\ConfigInterface" instance. Got: "%s".', $path, \is_object($config) ? \get_class($config) : \gettype($config))); + } + + return $config; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/ErrorOutput.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/ErrorOutput.php new file mode 100644 index 00000000..5cb8adb3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/ErrorOutput.php @@ -0,0 +1,155 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Output; + +use PhpCsFixer\Differ\DiffConsoleFormatter; +use PhpCsFixer\Error\Error; +use PhpCsFixer\Linter\LintingException; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @internal + */ +final class ErrorOutput +{ + private OutputInterface $output; + + /** + * @var bool + */ + private $isDecorated; + + public function __construct(OutputInterface $output) + { + $this->output = $output; + $this->isDecorated = $output->isDecorated(); + } + + /** + * @param Error[] $errors + */ + public function listErrors(string $process, array $errors): void + { + $this->output->writeln(['', sprintf( + 'Files that were not fixed due to errors reported during %s:', + $process + )]); + + $showDetails = $this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE; + $showTrace = $this->output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG; + foreach ($errors as $i => $error) { + $this->output->writeln(sprintf('%4d) %s', $i + 1, $error->getFilePath())); + $e = $error->getSource(); + if (!$showDetails || null === $e) { + continue; + } + + $class = sprintf('[%s]', \get_class($e)); + $message = $e->getMessage(); + $code = $e->getCode(); + if (0 !== $code) { + $message .= " ({$code})"; + } + + $length = max(\strlen($class), \strlen($message)); + $lines = [ + '', + $class, + $message, + '', + ]; + + $this->output->writeln(''); + + foreach ($lines as $line) { + if (\strlen($line) < $length) { + $line .= str_repeat(' ', $length - \strlen($line)); + } + + $this->output->writeln(sprintf(' %s ', $this->prepareOutput($line))); + } + + if ($showTrace && !$e instanceof LintingException) { // stack trace of lint exception is of no interest + $this->output->writeln(''); + $stackTrace = $e->getTrace(); + foreach ($stackTrace as $trace) { + if (isset($trace['class']) && \Symfony\Component\Console\Command\Command::class === $trace['class'] && 'run' === $trace['function']) { + $this->output->writeln(' [ ... ]'); + + break; + } + + $this->outputTrace($trace); + } + } + + if (Error::TYPE_LINT === $error->getType() && 0 < \count($error->getAppliedFixers())) { + $this->output->writeln(''); + $this->output->writeln(sprintf(' Applied fixers: %s', implode(', ', $error->getAppliedFixers()))); + + $diff = $error->getDiff(); + if (null !== $diff) { + $diffFormatter = new DiffConsoleFormatter( + $this->isDecorated, + sprintf( + ' ---------- begin diff ----------%s%%s%s ----------- end diff -----------', + PHP_EOL, + PHP_EOL + ) + ); + + $this->output->writeln($diffFormatter->format($diff)); + } + } + } + } + + /** + * @param array{ + * function?: string, + * line?: int, + * file?: string, + * class?: class-string, + * type?: '::'|'->', + * args?: mixed[], + * object?: object, + * } $trace + */ + private function outputTrace(array $trace): void + { + if (isset($trace['class'], $trace['type'], $trace['function'])) { + $this->output->writeln(sprintf( + ' %s%s%s()', + $this->prepareOutput($trace['class']), + $this->prepareOutput($trace['type']), + $this->prepareOutput($trace['function']) + )); + } elseif (isset($trace['function'])) { + $this->output->writeln(sprintf(' %s()', $this->prepareOutput($trace['function']))); + } + + if (isset($trace['file'])) { + $this->output->writeln(sprintf(' in %s at line %d', $this->prepareOutput($trace['file']), $trace['line'])); + } + } + + private function prepareOutput(string $string): string + { + return $this->isDecorated + ? OutputFormatter::escape($string) + : $string; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/OutputContext.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/OutputContext.php new file mode 100644 index 00000000..84a0ea6f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/OutputContext.php @@ -0,0 +1,52 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Output; + +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @internal + */ +final class OutputContext +{ + private ?OutputInterface $output; + private int $terminalWidth; + private int $filesCount; + + public function __construct( + ?OutputInterface $output, + int $terminalWidth, + int $filesCount + ) { + $this->output = $output; + $this->terminalWidth = $terminalWidth; + $this->filesCount = $filesCount; + } + + public function getOutput(): ?OutputInterface + { + return $this->output; + } + + public function getTerminalWidth(): int + { + return $this->terminalWidth; + } + + public function getFilesCount(): int + { + return $this->filesCount; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/DotsOutput.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/DotsOutput.php new file mode 100644 index 00000000..4df85f81 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/DotsOutput.php @@ -0,0 +1,127 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Output\Progress; + +use PhpCsFixer\Console\Output\OutputContext; +use PhpCsFixer\FixerFileProcessedEvent; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Output writer to show the progress of a FixCommand using dots and meaningful letters. + * + * @internal + */ +final class DotsOutput implements ProgressOutputInterface +{ + /** + * File statuses map. + * + * @var array + */ + private static array $eventStatusMap = [ + FixerFileProcessedEvent::STATUS_NO_CHANGES => ['symbol' => '.', 'format' => '%s', 'description' => 'no changes'], + FixerFileProcessedEvent::STATUS_FIXED => ['symbol' => 'F', 'format' => '%s', 'description' => 'fixed'], + FixerFileProcessedEvent::STATUS_SKIPPED => ['symbol' => 'S', 'format' => '%s', 'description' => 'skipped (cached or empty file)'], + FixerFileProcessedEvent::STATUS_INVALID => ['symbol' => 'I', 'format' => '%s', 'description' => 'invalid file syntax (file ignored)'], + FixerFileProcessedEvent::STATUS_EXCEPTION => ['symbol' => 'E', 'format' => '%s', 'description' => 'error'], + FixerFileProcessedEvent::STATUS_LINT => ['symbol' => 'E', 'format' => '%s', 'description' => 'error'], + ]; + + /** @readonly */ + private OutputContext $context; + + private int $processedFiles = 0; + + /** + * @var int + */ + private $symbolsPerLine; + + public function __construct(OutputContext $context) + { + $this->context = $context; + + // max number of characters per line + // - total length x 2 (e.g. " 1 / 123" => 6 digits and padding spaces) + // - 11 (extra spaces, parentheses and percentage characters, e.g. " x / x (100%)") + $this->symbolsPerLine = max(1, $context->getTerminalWidth() - \strlen((string) $context->getFilesCount()) * 2 - 11); + } + + /** + * This class is not intended to be serialized, + * and cannot be deserialized (see __wakeup method). + */ + public function __sleep(): array + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + /** + * Disable the deserialization of the class to prevent attacker executing + * code by leveraging the __destruct method. + * + * @see https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection + */ + public function __wakeup(): void + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + public function onFixerFileProcessed(FixerFileProcessedEvent $event): void + { + $status = self::$eventStatusMap[$event->getStatus()]; + $this->getOutput()->write($this->getOutput()->isDecorated() ? sprintf($status['format'], $status['symbol']) : $status['symbol']); + + ++$this->processedFiles; + + $symbolsOnCurrentLine = $this->processedFiles % $this->symbolsPerLine; + $isLast = $this->processedFiles === $this->context->getFilesCount(); + + if (0 === $symbolsOnCurrentLine || $isLast) { + $this->getOutput()->write(sprintf( + '%s %'.\strlen((string) $this->context->getFilesCount()).'d / %d (%3d%%)', + $isLast && 0 !== $symbolsOnCurrentLine ? str_repeat(' ', $this->symbolsPerLine - $symbolsOnCurrentLine) : '', + $this->processedFiles, + $this->context->getFilesCount(), + round($this->processedFiles / $this->context->getFilesCount() * 100) + )); + + if (!$isLast) { + $this->getOutput()->writeln(''); + } + } + } + + public function printLegend(): void + { + $symbols = []; + + foreach (self::$eventStatusMap as $status) { + $symbol = $status['symbol']; + if ('' === $symbol || isset($symbols[$symbol])) { + continue; + } + + $symbols[$symbol] = sprintf('%s-%s', $this->getOutput()->isDecorated() ? sprintf($status['format'], $symbol) : $symbol, $status['description']); + } + + $this->getOutput()->write(sprintf("\nLegend: %s\n", implode(', ', $symbols))); + } + + private function getOutput(): OutputInterface + { + return $this->context->getOutput(); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/NullOutput.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/NullOutput.php new file mode 100644 index 00000000..3af7ee44 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/NullOutput.php @@ -0,0 +1,27 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Output\Progress; + +use PhpCsFixer\FixerFileProcessedEvent; + +/** + * @internal + */ +final class NullOutput implements ProgressOutputInterface +{ + public function printLegend(): void {} + + public function onFixerFileProcessed(FixerFileProcessedEvent $event): void {} +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputFactory.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputFactory.php new file mode 100644 index 00000000..703170fd --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputFactory.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Output\Progress; + +use PhpCsFixer\Console\Output\OutputContext; + +/** + * @internal + */ +final class ProgressOutputFactory +{ + public function create(string $outputType, OutputContext $context): ProgressOutputInterface + { + if (null === $context->getOutput()) { + $outputType = ProgressOutputType::NONE; + } + + if (!$this->isBuiltInType($outputType)) { + throw new \InvalidArgumentException( + sprintf( + 'Something went wrong, "%s" output type is not supported', + $outputType + ) + ); + } + + return ProgressOutputType::NONE === $outputType + ? new NullOutput() + : new DotsOutput($context); + } + + private function isBuiltInType(string $outputType): bool + { + return \in_array($outputType, [ + ProgressOutputType::NONE, + ProgressOutputType::DOTS, + ], true); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputInterface.php new file mode 100644 index 00000000..b5ab9517 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputInterface.php @@ -0,0 +1,27 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Output\Progress; + +use PhpCsFixer\FixerFileProcessedEvent; + +/** + * @internal + */ +interface ProgressOutputInterface +{ + public function printLegend(): void; + + public function onFixerFileProcessed(FixerFileProcessedEvent $event): void; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputType.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputType.php new file mode 100644 index 00000000..4c005f89 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputType.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Output\Progress; + +/** + * @internal + */ +final class ProgressOutputType +{ + public const NONE = 'none'; + public const DOTS = 'dots'; + + public const AVAILABLE = [ + self::NONE, + self::DOTS, + ]; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/CheckstyleReporter.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/CheckstyleReporter.php new file mode 100644 index 00000000..a6770f60 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/CheckstyleReporter.php @@ -0,0 +1,65 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * @author Kévin Gomez + * + * @internal + */ +final class CheckstyleReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'checkstyle'; + } + + public function generate(ReportSummary $reportSummary): string + { + if (!\extension_loaded('dom')) { + throw new \RuntimeException('Cannot generate report! `ext-dom` is not available!'); + } + + $dom = new \DOMDocument('1.0', 'UTF-8'); + $checkstyles = $dom->appendChild($dom->createElement('checkstyle')); + + foreach ($reportSummary->getChanged() as $filePath => $fixResult) { + /** @var \DOMElement $file */ + $file = $checkstyles->appendChild($dom->createElement('file')); + $file->setAttribute('name', $filePath); + + foreach ($fixResult['appliedFixers'] as $appliedFixer) { + $error = $this->createError($dom, $appliedFixer); + $file->appendChild($error); + } + } + + $dom->formatOutput = true; + + return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($dom->saveXML()) : $dom->saveXML(); + } + + private function createError(\DOMDocument $dom, string $appliedFixer): \DOMElement + { + $error = $dom->createElement('error'); + $error->setAttribute('severity', 'warning'); + $error->setAttribute('source', 'PHP-CS-Fixer.'.$appliedFixer); + $error->setAttribute('message', 'Found violation(s) of type: '.$appliedFixer); + + return $error; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/GitlabReporter.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/GitlabReporter.php new file mode 100644 index 00000000..0e6c1881 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/GitlabReporter.php @@ -0,0 +1,76 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +use SebastianBergmann\Diff\Chunk; +use SebastianBergmann\Diff\Parser; +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * Generates a report according to gitlabs subset of codeclimate json files. + * + * @see https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#data-types + * + * @author Hans-Christian Otto + * + * @internal + */ +final class GitlabReporter implements ReporterInterface +{ + private Parser $diffParser; + + public function __construct() + { + $this->diffParser = new Parser(); + } + + public function getFormat(): string + { + return 'gitlab'; + } + + /** + * Process changed files array. Returns generated report. + */ + public function generate(ReportSummary $reportSummary): string + { + $report = []; + foreach ($reportSummary->getChanged() as $fileName => $change) { + $diffs = $this->diffParser->parse($change['diff']); + $firstChunk = isset($diffs[0]) ? $diffs[0]->getChunks() : []; + $firstChunk = array_shift($firstChunk); + foreach ($change['appliedFixers'] as $fixerName) { + $report[] = [ + 'check_name' => $fixerName, + 'description' => $fixerName, + 'categories' => ['Style'], + 'fingerprint' => md5($fileName.$fixerName), + 'severity' => 'minor', + 'location' => [ + 'path' => $fileName, + 'lines' => [ + 'begin' => $firstChunk instanceof Chunk ? $firstChunk->getStart() : 0, + 'end' => $firstChunk instanceof Chunk ? $firstChunk->getStartRange() : 0, + ], + ], + ]; + } + } + + $jsonString = json_encode($report, JSON_THROW_ON_ERROR); + + return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($jsonString) : $jsonString; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JsonReporter.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JsonReporter.php new file mode 100644 index 00000000..2bb5b95a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JsonReporter.php @@ -0,0 +1,61 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * @author Boris Gorbylev + * + * @internal + */ +final class JsonReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'json'; + } + + public function generate(ReportSummary $reportSummary): string + { + $jsonFiles = []; + + foreach ($reportSummary->getChanged() as $file => $fixResult) { + $jsonFile = ['name' => $file]; + + if ($reportSummary->shouldAddAppliedFixers()) { + $jsonFile['appliedFixers'] = $fixResult['appliedFixers']; + } + + if ('' !== $fixResult['diff']) { + $jsonFile['diff'] = $fixResult['diff']; + } + + $jsonFiles[] = $jsonFile; + } + + $json = [ + 'files' => $jsonFiles, + 'time' => [ + 'total' => round($reportSummary->getTime() / 1000, 3), + ], + 'memory' => round($reportSummary->getMemory() / 1024 / 1024, 3), + ]; + + $json = json_encode($json, JSON_THROW_ON_ERROR); + + return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($json) : $json; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JunitReporter.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JunitReporter.php new file mode 100644 index 00000000..631b28e9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JunitReporter.php @@ -0,0 +1,135 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +use PhpCsFixer\Preg; +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * @author Boris Gorbylev + * + * @internal + */ +final class JunitReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'junit'; + } + + public function generate(ReportSummary $reportSummary): string + { + if (!\extension_loaded('dom')) { + throw new \RuntimeException('Cannot generate report! `ext-dom` is not available!'); + } + + $dom = new \DOMDocument('1.0', 'UTF-8'); + $testsuites = $dom->appendChild($dom->createElement('testsuites')); + + /** @var \DOMElement $testsuite */ + $testsuite = $testsuites->appendChild($dom->createElement('testsuite')); + $testsuite->setAttribute('name', 'PHP CS Fixer'); + + if (\count($reportSummary->getChanged()) > 0) { + $this->createFailedTestCases($dom, $testsuite, $reportSummary); + } else { + $this->createSuccessTestCase($dom, $testsuite); + } + + if ($reportSummary->getTime() > 0) { + $testsuite->setAttribute( + 'time', + sprintf( + '%.3f', + $reportSummary->getTime() / 1000 + ) + ); + } + + $dom->formatOutput = true; + + return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($dom->saveXML()) : $dom->saveXML(); + } + + private function createSuccessTestCase(\DOMDocument $dom, \DOMElement $testsuite): void + { + $testcase = $dom->createElement('testcase'); + $testcase->setAttribute('name', 'All OK'); + $testcase->setAttribute('assertions', '1'); + + $testsuite->appendChild($testcase); + $testsuite->setAttribute('tests', '1'); + $testsuite->setAttribute('assertions', '1'); + $testsuite->setAttribute('failures', '0'); + $testsuite->setAttribute('errors', '0'); + } + + private function createFailedTestCases(\DOMDocument $dom, \DOMElement $testsuite, ReportSummary $reportSummary): void + { + $assertionsCount = 0; + foreach ($reportSummary->getChanged() as $file => $fixResult) { + $testcase = $this->createFailedTestCase( + $dom, + $file, + $fixResult, + $reportSummary->shouldAddAppliedFixers() + ); + $testsuite->appendChild($testcase); + $assertionsCount += (int) $testcase->getAttribute('assertions'); + } + + $testsuite->setAttribute('tests', (string) \count($reportSummary->getChanged())); + $testsuite->setAttribute('assertions', (string) $assertionsCount); + $testsuite->setAttribute('failures', (string) $assertionsCount); + $testsuite->setAttribute('errors', '0'); + } + + /** + * @param array{appliedFixers: list, diff: string} $fixResult + */ + private function createFailedTestCase(\DOMDocument $dom, string $file, array $fixResult, bool $shouldAddAppliedFixers): \DOMElement + { + $appliedFixersCount = \count($fixResult['appliedFixers']); + + $testName = str_replace('.', '_DOT_', Preg::replace('@\.'.pathinfo($file, PATHINFO_EXTENSION).'$@', '', $file)); + + $testcase = $dom->createElement('testcase'); + $testcase->setAttribute('name', $testName); + $testcase->setAttribute('file', $file); + $testcase->setAttribute('assertions', (string) $appliedFixersCount); + + $failure = $dom->createElement('failure'); + $failure->setAttribute('type', 'code_style'); + $testcase->appendChild($failure); + + if ($shouldAddAppliedFixers) { + $failureContent = "applied fixers:\n---------------\n"; + + foreach ($fixResult['appliedFixers'] as $appliedFixer) { + $failureContent .= "* {$appliedFixer}\n"; + } + } else { + $failureContent = "Wrong code style\n"; + } + + if ('' !== $fixResult['diff']) { + $failureContent .= "\nDiff:\n---------------\n\n".$fixResult['diff']; + } + + $failure->appendChild($dom->createCDATASection(trim($failureContent))); + + return $testcase; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReportSummary.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReportSummary.php new file mode 100644 index 00000000..ccdfefb3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReportSummary.php @@ -0,0 +1,101 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class ReportSummary +{ + /** + * @var array, diff: string}> + */ + private array $changed; + + private int $filesCount; + + private int $time; + + private int $memory; + + private bool $addAppliedFixers; + + private bool $isDryRun; + + private bool $isDecoratedOutput; + + /** + * @param array, diff: string}> $changed + * @param int $time duration in milliseconds + * @param int $memory memory usage in bytes + */ + public function __construct( + array $changed, + int $filesCount, + int $time, + int $memory, + bool $addAppliedFixers, + bool $isDryRun, + bool $isDecoratedOutput + ) { + $this->changed = $changed; + $this->filesCount = $filesCount; + $this->time = $time; + $this->memory = $memory; + $this->addAppliedFixers = $addAppliedFixers; + $this->isDryRun = $isDryRun; + $this->isDecoratedOutput = $isDecoratedOutput; + } + + public function isDecoratedOutput(): bool + { + return $this->isDecoratedOutput; + } + + public function isDryRun(): bool + { + return $this->isDryRun; + } + + /** + * @return array, diff: string}> + */ + public function getChanged(): array + { + return $this->changed; + } + + public function getMemory(): int + { + return $this->memory; + } + + public function getTime(): int + { + return $this->time; + } + + public function getFilesCount(): int + { + return $this->filesCount; + } + + public function shouldAddAppliedFixers(): bool + { + return $this->addAppliedFixers; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterFactory.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterFactory.php new file mode 100644 index 00000000..e4efd990 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterFactory.php @@ -0,0 +1,90 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +use Symfony\Component\Finder\Finder as SymfonyFinder; + +/** + * @author Boris Gorbylev + * + * @internal + */ +final class ReporterFactory +{ + /** @var array */ + private array $reporters = []; + + public function registerBuiltInReporters(): self + { + /** @var null|list $builtInReporters */ + static $builtInReporters; + + if (null === $builtInReporters) { + $builtInReporters = []; + + foreach (SymfonyFinder::create()->files()->name('*Reporter.php')->in(__DIR__) as $file) { + $relativeNamespace = $file->getRelativePath(); + $builtInReporters[] = sprintf( + '%s\\%s%s', + __NAMESPACE__, + '' !== $relativeNamespace ? $relativeNamespace.'\\' : '', + $file->getBasename('.php') + ); + } + } + + foreach ($builtInReporters as $reporterClass) { + $this->registerReporter(new $reporterClass()); + } + + return $this; + } + + /** + * @return $this + */ + public function registerReporter(ReporterInterface $reporter): self + { + $format = $reporter->getFormat(); + + if (isset($this->reporters[$format])) { + throw new \UnexpectedValueException(sprintf('Reporter for format "%s" is already registered.', $format)); + } + + $this->reporters[$format] = $reporter; + + return $this; + } + + /** + * @return list + */ + public function getFormats(): array + { + $formats = array_keys($this->reporters); + sort($formats); + + return $formats; + } + + public function getReporter(string $format): ReporterInterface + { + if (!isset($this->reporters[$format])) { + throw new \UnexpectedValueException(sprintf('Reporter for format "%s" is not registered.', $format)); + } + + return $this->reporters[$format]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterInterface.php new file mode 100644 index 00000000..44fab560 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterInterface.php @@ -0,0 +1,30 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +/** + * @author Boris Gorbylev + * + * @internal + */ +interface ReporterInterface +{ + public function getFormat(): string; + + /** + * Process changed files array. Returns generated report. + */ + public function generate(ReportSummary $reportSummary): string; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/TextReporter.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/TextReporter.php new file mode 100644 index 00000000..f5394742 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/TextReporter.php @@ -0,0 +1,102 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +use PhpCsFixer\Differ\DiffConsoleFormatter; + +/** + * @author Boris Gorbylev + * + * @internal + */ +final class TextReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'txt'; + } + + public function generate(ReportSummary $reportSummary): string + { + $output = ''; + + $identifiedFiles = 0; + foreach ($reportSummary->getChanged() as $file => $fixResult) { + ++$identifiedFiles; + $output .= sprintf('%4d) %s', $identifiedFiles, $file); + + if ($reportSummary->shouldAddAppliedFixers()) { + $output .= $this->getAppliedFixers( + $reportSummary->isDecoratedOutput(), + $fixResult['appliedFixers'], + ); + } + + $output .= $this->getDiff($reportSummary->isDecoratedOutput(), $fixResult['diff']); + $output .= PHP_EOL; + } + + return $output.$this->getFooter( + $reportSummary->getTime(), + $identifiedFiles, + $reportSummary->getFilesCount(), + $reportSummary->getMemory(), + $reportSummary->isDryRun() + ); + } + + /** + * @param list $appliedFixers + */ + private function getAppliedFixers(bool $isDecoratedOutput, array $appliedFixers): string + { + return sprintf( + $isDecoratedOutput ? ' (%s)' : ' (%s)', + implode(', ', $appliedFixers) + ); + } + + private function getDiff(bool $isDecoratedOutput, string $diff): string + { + if ('' === $diff) { + return ''; + } + + $diffFormatter = new DiffConsoleFormatter($isDecoratedOutput, sprintf( + ' ---------- begin diff ----------%s%%s%s ----------- end diff -----------', + PHP_EOL, + PHP_EOL + )); + + return PHP_EOL.$diffFormatter->format($diff).PHP_EOL; + } + + private function getFooter(int $time, int $identifiedFiles, int $files, int $memory, bool $isDryRun): string + { + if (0 === $time || 0 === $memory) { + return ''; + } + + return PHP_EOL.sprintf( + '%s %d of %d %s in %.3f seconds, %.3f MB memory used'.PHP_EOL, + $isDryRun ? 'Found' : 'Fixed', + $identifiedFiles, + $files, + $isDryRun ? 'files that can be fixed' : 'files', + $time / 1000, + $memory / 1024 / 1024 + ); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/XmlReporter.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/XmlReporter.php new file mode 100644 index 00000000..28236827 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/XmlReporter.php @@ -0,0 +1,123 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * @author Boris Gorbylev + * + * @internal + */ +final class XmlReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'xml'; + } + + public function generate(ReportSummary $reportSummary): string + { + if (!\extension_loaded('dom')) { + throw new \RuntimeException('Cannot generate report! `ext-dom` is not available!'); + } + + $dom = new \DOMDocument('1.0', 'UTF-8'); + // new nodes should be added to this or existing children + $root = $dom->createElement('report'); + $dom->appendChild($root); + + $filesXML = $dom->createElement('files'); + $root->appendChild($filesXML); + + $i = 1; + foreach ($reportSummary->getChanged() as $file => $fixResult) { + $fileXML = $dom->createElement('file'); + $fileXML->setAttribute('id', (string) $i++); + $fileXML->setAttribute('name', $file); + $filesXML->appendChild($fileXML); + + if ($reportSummary->shouldAddAppliedFixers()) { + $fileXML->appendChild( + $this->createAppliedFixersElement($dom, $fixResult['appliedFixers']), + ); + } + + if ('' !== $fixResult['diff']) { + $fileXML->appendChild($this->createDiffElement($dom, $fixResult['diff'])); + } + } + + if (0 !== $reportSummary->getTime()) { + $root->appendChild($this->createTimeElement($reportSummary->getTime(), $dom)); + } + + if (0 !== $reportSummary->getMemory()) { + $root->appendChild($this->createMemoryElement($reportSummary->getMemory(), $dom)); + } + + $dom->formatOutput = true; + + return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($dom->saveXML()) : $dom->saveXML(); + } + + /** + * @param list $appliedFixers + */ + private function createAppliedFixersElement(\DOMDocument $dom, array $appliedFixers): \DOMElement + { + $appliedFixersXML = $dom->createElement('applied_fixers'); + + foreach ($appliedFixers as $appliedFixer) { + $appliedFixerXML = $dom->createElement('applied_fixer'); + $appliedFixerXML->setAttribute('name', $appliedFixer); + $appliedFixersXML->appendChild($appliedFixerXML); + } + + return $appliedFixersXML; + } + + private function createDiffElement(\DOMDocument $dom, string $diff): \DOMElement + { + $diffXML = $dom->createElement('diff'); + $diffXML->appendChild($dom->createCDATASection($diff)); + + return $diffXML; + } + + private function createTimeElement(float $time, \DOMDocument $dom): \DOMElement + { + $time = round($time / 1000, 3); + + $timeXML = $dom->createElement('time'); + $timeXML->setAttribute('unit', 's'); + $timeTotalXML = $dom->createElement('total'); + $timeTotalXML->setAttribute('value', (string) $time); + $timeXML->appendChild($timeTotalXML); + + return $timeXML; + } + + private function createMemoryElement(float $memory, \DOMDocument $dom): \DOMElement + { + $memory = round($memory / 1024 / 1024, 3); + + $memoryXML = $dom->createElement('memory'); + $memoryXML->setAttribute('value', (string) $memory); + $memoryXML->setAttribute('unit', 'MB'); + + return $memoryXML; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/JsonReporter.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/JsonReporter.php new file mode 100644 index 00000000..ceebd89e --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/JsonReporter.php @@ -0,0 +1,50 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\ListSetsReport; + +use PhpCsFixer\RuleSet\RuleSetDescriptionInterface; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class JsonReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'json'; + } + + public function generate(ReportSummary $reportSummary): string + { + $sets = $reportSummary->getSets(); + + usort($sets, static fn (RuleSetDescriptionInterface $a, RuleSetDescriptionInterface $b): int => $a->getName() <=> $b->getName()); + + $json = ['sets' => []]; + + foreach ($sets as $set) { + $setName = $set->getName(); + $json['sets'][$setName] = [ + 'description' => $set->getDescription(), + 'isRisky' => $set->isRisky(), + 'name' => $setName, + ]; + } + + return json_encode($json, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReportSummary.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReportSummary.php new file mode 100644 index 00000000..c7d66e71 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReportSummary.php @@ -0,0 +1,46 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\ListSetsReport; + +use PhpCsFixer\RuleSet\RuleSetDescriptionInterface; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class ReportSummary +{ + /** + * @var list + */ + private array $sets; + + /** + * @param list $sets + */ + public function __construct(array $sets) + { + $this->sets = $sets; + } + + /** + * @return list + */ + public function getSets(): array + { + return $this->sets; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterFactory.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterFactory.php new file mode 100644 index 00000000..45f2a26f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterFactory.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\ListSetsReport; + +use Symfony\Component\Finder\Finder as SymfonyFinder; + +/** + * @author Boris Gorbylev + * + * @internal + */ +final class ReporterFactory +{ + /** + * @var array + */ + private array $reporters = []; + + public function registerBuiltInReporters(): self + { + /** @var null|list $builtInReporters */ + static $builtInReporters; + + if (null === $builtInReporters) { + $builtInReporters = []; + + foreach (SymfonyFinder::create()->files()->name('*Reporter.php')->in(__DIR__) as $file) { + $relativeNamespace = $file->getRelativePath(); + $builtInReporters[] = sprintf( + '%s\\%s%s', + __NAMESPACE__, + '' !== $relativeNamespace ? $relativeNamespace.'\\' : '', + $file->getBasename('.php') + ); + } + } + + foreach ($builtInReporters as $reporterClass) { + $this->registerReporter(new $reporterClass()); + } + + return $this; + } + + public function registerReporter(ReporterInterface $reporter): self + { + $format = $reporter->getFormat(); + + if (isset($this->reporters[$format])) { + throw new \UnexpectedValueException(sprintf('Reporter for format "%s" is already registered.', $format)); + } + + $this->reporters[$format] = $reporter; + + return $this; + } + + /** + * @return list + */ + public function getFormats(): array + { + $formats = array_keys($this->reporters); + sort($formats); + + return $formats; + } + + public function getReporter(string $format): ReporterInterface + { + if (!isset($this->reporters[$format])) { + throw new \UnexpectedValueException(sprintf('Reporter for format "%s" is not registered.', $format)); + } + + return $this->reporters[$format]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterInterface.php new file mode 100644 index 00000000..4a03f330 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterInterface.php @@ -0,0 +1,30 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\ListSetsReport; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +interface ReporterInterface +{ + public function getFormat(): string; + + /** + * Process changed files array. Returns generated report. + */ + public function generate(ReportSummary $reportSummary): string; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/TextReporter.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/TextReporter.php new file mode 100644 index 00000000..9c851ef3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/TextReporter.php @@ -0,0 +1,49 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\ListSetsReport; + +use PhpCsFixer\RuleSet\RuleSetDescriptionInterface; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class TextReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'txt'; + } + + public function generate(ReportSummary $reportSummary): string + { + $sets = $reportSummary->getSets(); + + usort($sets, static fn (RuleSetDescriptionInterface $a, RuleSetDescriptionInterface $b): int => $a->getName() <=> $b->getName()); + + $output = ''; + + foreach ($sets as $i => $set) { + $output .= sprintf('%2d) %s', $i + 1, $set->getName()).PHP_EOL.' '.$set->getDescription().PHP_EOL; + + if ($set->isRisky()) { + $output .= ' Set contains risky rules.'.PHP_EOL; + } + } + + return $output; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClient.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClient.php new file mode 100644 index 00000000..e2268d7f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClient.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\SelfUpdate; + +/** + * @internal + */ +final class GithubClient implements GithubClientInterface +{ + public function getTags(): array + { + $url = 'https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/tags'; + + $result = @file_get_contents( + $url, + false, + stream_context_create([ + 'http' => [ + 'header' => 'User-Agent: PHP-CS-Fixer/PHP-CS-Fixer', + ], + ]) + ); + + if (false === $result) { + throw new \RuntimeException(sprintf('Failed to load tags at "%s".', $url)); + } + + $result = json_decode($result, true); + if (JSON_ERROR_NONE !== json_last_error()) { + throw new \RuntimeException(sprintf( + 'Failed to read response from "%s" as JSON: %s.', + $url, + json_last_error_msg() + )); + } + + return $result; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClientInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClientInterface.php new file mode 100644 index 00000000..38178a22 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClientInterface.php @@ -0,0 +1,31 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\SelfUpdate; + +/** + * @internal + */ +interface GithubClientInterface +{ + /** + * @return list + */ + public function getTags(): array; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionChecker.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionChecker.php new file mode 100644 index 00000000..06bd1229 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionChecker.php @@ -0,0 +1,101 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\SelfUpdate; + +use Composer\Semver\Comparator; +use Composer\Semver\Semver; +use Composer\Semver\VersionParser; + +/** + * @internal + */ +final class NewVersionChecker implements NewVersionCheckerInterface +{ + private GithubClientInterface $githubClient; + + private VersionParser $versionParser; + + /** + * @var null|string[] + */ + private $availableVersions; + + public function __construct(GithubClientInterface $githubClient) + { + $this->githubClient = $githubClient; + $this->versionParser = new VersionParser(); + } + + public function getLatestVersion(): string + { + $this->retrieveAvailableVersions(); + + return $this->availableVersions[0]; + } + + public function getLatestVersionOfMajor(int $majorVersion): ?string + { + $this->retrieveAvailableVersions(); + + $semverConstraint = '^'.$majorVersion; + + foreach ($this->availableVersions as $availableVersion) { + if (Semver::satisfies($availableVersion, $semverConstraint)) { + return $availableVersion; + } + } + + return null; + } + + public function compareVersions(string $versionA, string $versionB): int + { + $versionA = $this->versionParser->normalize($versionA); + $versionB = $this->versionParser->normalize($versionB); + + if (Comparator::lessThan($versionA, $versionB)) { + return -1; + } + + if (Comparator::greaterThan($versionA, $versionB)) { + return 1; + } + + return 0; + } + + private function retrieveAvailableVersions(): void + { + if (null !== $this->availableVersions) { + return; + } + + foreach ($this->githubClient->getTags() as $tag) { + $version = $tag['name']; + + try { + $this->versionParser->normalize($version); + + if ('stable' === VersionParser::parseStability($version)) { + $this->availableVersions[] = $version; + } + } catch (\UnexpectedValueException $exception) { + // not a valid version tag + } + } + + $this->availableVersions = Semver::rsort($this->availableVersions); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionCheckerInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionCheckerInterface.php new file mode 100644 index 00000000..c63b2a20 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionCheckerInterface.php @@ -0,0 +1,37 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\SelfUpdate; + +/** + * @internal + */ +interface NewVersionCheckerInterface +{ + /** + * Returns the tag of the latest version. + */ + public function getLatestVersion(): string; + + /** + * Returns the tag of the latest minor/patch version of the given major version. + */ + public function getLatestVersionOfMajor(int $majorVersion): ?string; + + /** + * Returns -1, 0, or 1 if the first version is respectively less than, + * equal to, or greater than the second. + */ + public function compareVersions(string $versionA, string $versionB): int; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/WarningsDetector.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/WarningsDetector.php new file mode 100644 index 00000000..f5ce04c2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Console/WarningsDetector.php @@ -0,0 +1,76 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console; + +use PhpCsFixer\ToolInfo; +use PhpCsFixer\ToolInfoInterface; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class WarningsDetector +{ + private ToolInfoInterface $toolInfo; + + /** + * @var string[] + */ + private array $warnings = []; + + public function __construct(ToolInfoInterface $toolInfo) + { + $this->toolInfo = $toolInfo; + } + + public function detectOldMajor(): void + { + // @TODO 3.99 to be activated with new MAJOR release 4.0 + // $currentMajorVersion = \intval(explode('.', Application::VERSION)[0], 10); + // $nextMajorVersion = $currentMajorVersion + 1; + // $this->warnings[] = "You are running PHP CS Fixer v{$currentMajorVersion}, which is not maintained anymore. Please update to v{$nextMajorVersion}."; + // $this->warnings[] = "You may find an UPGRADE guide at https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/v{$nextMajorVersion}.0.0/UPGRADE-v{$nextMajorVersion}.md ."; + } + + public function detectOldVendor(): void + { + if ($this->toolInfo->isInstalledByComposer()) { + $details = $this->toolInfo->getComposerInstallationDetails(); + if (ToolInfo::COMPOSER_LEGACY_PACKAGE_NAME === $details['name']) { + $this->warnings[] = sprintf( + 'You are running PHP CS Fixer installed with old vendor `%s`. Please update to `%s`.', + ToolInfo::COMPOSER_LEGACY_PACKAGE_NAME, + ToolInfo::COMPOSER_PACKAGE_NAME + ); + } + } + } + + /** + * @return string[] + */ + public function getWarnings(): array + { + if (0 === \count($this->warnings)) { + return []; + } + + return array_unique(array_merge( + $this->warnings, + ['If you need help while solving warnings, ask at https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/discussions/, we will help you!'] + )); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Differ/DiffConsoleFormatter.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Differ/DiffConsoleFormatter.php new file mode 100644 index 00000000..f2896253 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Differ/DiffConsoleFormatter.php @@ -0,0 +1,83 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Differ; + +use PhpCsFixer\Preg; +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class DiffConsoleFormatter +{ + private bool $isDecoratedOutput; + + private string $template; + + public function __construct(bool $isDecoratedOutput, string $template = '%s') + { + $this->isDecoratedOutput = $isDecoratedOutput; + $this->template = $template; + } + + public function format(string $diff, string $lineTemplate = '%s'): string + { + $isDecorated = $this->isDecoratedOutput; + + $template = $isDecorated + ? $this->template + : Preg::replace('/<[^<>]+>/', '', $this->template); + + return sprintf( + $template, + implode( + PHP_EOL, + array_map( + static function (string $line) use ($isDecorated, $lineTemplate): string { + if ($isDecorated) { + $count = 0; + $line = Preg::replaceCallback( + '/^([+\-@].*)/', + static function (array $matches): string { + if ('+' === $matches[0][0]) { + $colour = 'green'; + } elseif ('-' === $matches[0][0]) { + $colour = 'red'; + } else { + $colour = 'cyan'; + } + + return sprintf('%s', $colour, OutputFormatter::escape($matches[0]), $colour); + }, + $line, + 1, + $count + ); + + if (0 === $count) { + $line = OutputFormatter::escape($line); + } + } + + return sprintf($lineTemplate, $line); + }, + Preg::split('#\R#u', $diff) + ) + ) + ); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Differ/DifferInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Differ/DifferInterface.php new file mode 100644 index 00000000..a66f165c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Differ/DifferInterface.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Differ; + +/** + * @author Dariusz Rumiński + */ +interface DifferInterface +{ + /** + * Create diff. + */ + public function diff(string $old, string $new, ?\SplFileInfo $file = null): string; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Differ/FullDiffer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Differ/FullDiffer.php new file mode 100644 index 00000000..a927ede4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Differ/FullDiffer.php @@ -0,0 +1,44 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Differ; + +use SebastianBergmann\Diff\Differ; +use SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class FullDiffer implements DifferInterface +{ + private Differ $differ; + + public function __construct() + { + $this->differ = new Differ(new StrictUnifiedDiffOutputBuilder([ + 'collapseRanges' => false, + 'commonLineThreshold' => 100, + 'contextLines' => 100, + 'fromFile' => 'Original', + 'toFile' => 'New', + ])); + } + + public function diff(string $old, string $new, ?\SplFileInfo $file = null): string + { + return $this->differ->diff($old, $new); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Differ/NullDiffer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Differ/NullDiffer.php new file mode 100644 index 00000000..cf07f9e7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Differ/NullDiffer.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Differ; + +/** + * @author Dariusz Rumiński + */ +final class NullDiffer implements DifferInterface +{ + public function diff(string $old, string $new, ?\SplFileInfo $file = null): string + { + return ''; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Differ/UnifiedDiffer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Differ/UnifiedDiffer.php new file mode 100644 index 00000000..36663aa1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Differ/UnifiedDiffer.php @@ -0,0 +1,47 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Differ; + +use PhpCsFixer\Preg; +use SebastianBergmann\Diff\Differ; +use SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder; + +final class UnifiedDiffer implements DifferInterface +{ + public function diff(string $old, string $new, ?\SplFileInfo $file = null): string + { + if (null === $file) { + $options = [ + 'fromFile' => 'Original', + 'toFile' => 'New', + ]; + } else { + $filePath = $file->getRealPath(); + + if (Preg::match('/\s/', $filePath)) { + $filePath = '"'.$filePath.'"'; + } + + $options = [ + 'fromFile' => $filePath, + 'toFile' => $filePath, + ]; + } + + $differ = new Differ(new StrictUnifiedDiffOutputBuilder($options)); + + return $differ->diff($old, $new); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Annotation.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Annotation.php new file mode 100644 index 00000000..c4a0444c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Annotation.php @@ -0,0 +1,311 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\DocBlock; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; + +/** + * This represents an entire annotation from a docblock. + * + * @author Graham Campbell + * @author Dariusz Rumiński + */ +final class Annotation +{ + /** + * All the annotation tag names with types. + * + * @var string[] + */ + private static array $tags = [ + 'method', + 'param', + 'property', + 'property-read', + 'property-write', + 'return', + 'throws', + 'type', + 'var', + ]; + + /** + * The lines that make up the annotation. + * + * @var Line[] + */ + private array $lines; + + /** + * The position of the first line of the annotation in the docblock. + * + * @var int + */ + private $start; + + /** + * The position of the last line of the annotation in the docblock. + * + * @var int + */ + private $end; + + /** + * The associated tag. + * + * @var null|Tag + */ + private $tag; + + /** + * Lazy loaded, cached types content. + * + * @var null|string + */ + private $typesContent; + + /** + * The cached types. + * + * @var null|string[] + */ + private $types; + + /** + * @var null|NamespaceAnalysis + */ + private $namespace; + + /** + * @var NamespaceUseAnalysis[] + */ + private array $namespaceUses; + + /** + * Create a new line instance. + * + * @param Line[] $lines + * @param null|NamespaceAnalysis $namespace + * @param NamespaceUseAnalysis[] $namespaceUses + */ + public function __construct(array $lines, $namespace = null, array $namespaceUses = []) + { + $this->lines = array_values($lines); + $this->namespace = $namespace; + $this->namespaceUses = $namespaceUses; + + $keys = array_keys($lines); + + $this->start = $keys[0]; + $this->end = end($keys); + } + + /** + * Get the string representation of object. + */ + public function __toString(): string + { + return $this->getContent(); + } + + /** + * Get all the annotation tag names with types. + * + * @return string[] + */ + public static function getTagsWithTypes(): array + { + return self::$tags; + } + + /** + * Get the start position of this annotation. + */ + public function getStart(): int + { + return $this->start; + } + + /** + * Get the end position of this annotation. + */ + public function getEnd(): int + { + return $this->end; + } + + /** + * Get the associated tag. + */ + public function getTag(): Tag + { + if (null === $this->tag) { + $this->tag = new Tag($this->lines[0]); + } + + return $this->tag; + } + + /** + * @internal + */ + public function getTypeExpression(): ?TypeExpression + { + $typesContent = $this->getTypesContent(); + + return null === $typesContent + ? null + : new TypeExpression($typesContent, $this->namespace, $this->namespaceUses); + } + + /** + * @return null|string + * + * @internal + */ + public function getVariableName() + { + $type = preg_quote($this->getTypesContent() ?? '', '/'); + $regex = "/@{$this->tag->getName()}\\s+({$type}\\s*)?(&\\s*)?(\\.{3}\\s*)?(?\\$.+?)(?:[\\s*]|$)/"; + + if (Preg::match($regex, $this->lines[0]->getContent(), $matches)) { + return $matches['variable']; + } + + return null; + } + + /** + * Get the types associated with this annotation. + * + * @return string[] + */ + public function getTypes(): array + { + if (null === $this->types) { + $typeExpression = $this->getTypeExpression(); + $this->types = null === $typeExpression + ? [] + : $typeExpression->getTypes(); + } + + return $this->types; + } + + /** + * Set the types associated with this annotation. + * + * @param string[] $types + */ + public function setTypes(array $types): void + { + $pattern = '/'.preg_quote($this->getTypesContent(), '/').'/'; + + $this->lines[0]->setContent(Preg::replace($pattern, implode($this->getTypeExpression()->getTypesGlue(), $types), $this->lines[0]->getContent(), 1)); + + $this->clearCache(); + } + + /** + * Get the normalized types associated with this annotation, so they can easily be compared. + * + * @return string[] + */ + public function getNormalizedTypes(): array + { + $normalized = array_map(static fn (string $type): string => strtolower($type), $this->getTypes()); + + sort($normalized); + + return $normalized; + } + + /** + * Remove this annotation by removing all its lines. + */ + public function remove(): void + { + foreach ($this->lines as $line) { + if ($line->isTheStart() && $line->isTheEnd()) { + // Single line doc block, remove entirely + $line->remove(); + } elseif ($line->isTheStart()) { + // Multi line doc block, but start is on the same line as the first annotation, keep only the start + $content = Preg::replace('#(\s*/\*\*).*#', '$1', $line->getContent()); + + $line->setContent($content); + } elseif ($line->isTheEnd()) { + // Multi line doc block, but end is on the same line as the last annotation, keep only the end + $content = Preg::replace('#(\s*)\S.*(\*/.*)#', '$1$2', $line->getContent()); + + $line->setContent($content); + } else { + // Multi line doc block, neither start nor end on this line, can be removed safely + $line->remove(); + } + } + + $this->clearCache(); + } + + /** + * Get the annotation content. + */ + public function getContent(): string + { + return implode('', $this->lines); + } + + public function supportTypes(): bool + { + return \in_array($this->getTag()->getName(), self::$tags, true); + } + + /** + * Get the current types content. + * + * Be careful modifying the underlying line as that won't flush the cache. + */ + private function getTypesContent(): ?string + { + if (null === $this->typesContent) { + $name = $this->getTag()->getName(); + + if (!$this->supportTypes()) { + throw new \RuntimeException('This tag does not support types.'); + } + + $matchingResult = Preg::match( + '{^(?:\s*\*|/\*\*)[\s\*]*@'.$name.'\s+'.TypeExpression::REGEX_TYPES.'(?:(?:[*\h\v]|\&?[\.\$]).*)?\r?$}is', + $this->lines[0]->getContent(), + $matches + ); + + $this->typesContent = $matchingResult + ? $matches['types'] + : null; + } + + return $this->typesContent; + } + + private function clearCache(): void + { + $this->types = null; + $this->typesContent = null; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/DocBlock.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/DocBlock.php new file mode 100644 index 00000000..b4ae53e2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/DocBlock.php @@ -0,0 +1,250 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\DocBlock; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; + +/** + * This class represents a docblock. + * + * It internally splits it up into "lines" that we can manipulate. + * + * @author Graham Campbell + */ +final class DocBlock +{ + /** + * @var list + */ + private array $lines = []; + + /** + * @var null|list + */ + private ?array $annotations = null; + + private ?NamespaceAnalysis $namespace; + + /** + * @var list + */ + private array $namespaceUses; + + /** + * @param list $namespaceUses + */ + public function __construct(string $content, ?NamespaceAnalysis $namespace = null, array $namespaceUses = []) + { + foreach (Preg::split('/([^\n\r]+\R*)/', $content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $line) { + $this->lines[] = new Line($line); + } + + $this->namespace = $namespace; + $this->namespaceUses = $namespaceUses; + } + + public function __toString(): string + { + return $this->getContent(); + } + + /** + * Get this docblock's lines. + * + * @return list + */ + public function getLines(): array + { + return $this->lines; + } + + /** + * Get a single line. + */ + public function getLine(int $pos): ?Line + { + return $this->lines[$pos] ?? null; + } + + /** + * Get this docblock's annotations. + * + * @return list + */ + public function getAnnotations(): array + { + if (null !== $this->annotations) { + return $this->annotations; + } + + $this->annotations = []; + $total = \count($this->lines); + + for ($index = 0; $index < $total; ++$index) { + if ($this->lines[$index]->containsATag()) { + // get all the lines that make up the annotation + $lines = \array_slice($this->lines, $index, $this->findAnnotationLength($index), true); + $annotation = new Annotation($lines, $this->namespace, $this->namespaceUses); + // move the index to the end of the annotation to avoid + // checking it again because we know the lines inside the + // current annotation cannot be part of another annotation + $index = $annotation->getEnd(); + // add the current annotation to the list of annotations + $this->annotations[] = $annotation; + } + } + + return $this->annotations; + } + + public function isMultiLine(): bool + { + return 1 !== \count($this->lines); + } + + /** + * Take a one line doc block, and turn it into a multi line doc block. + */ + public function makeMultiLine(string $indent, string $lineEnd): void + { + if ($this->isMultiLine()) { + return; + } + + $lineContent = $this->getSingleLineDocBlockEntry($this->lines[0]); + + if ('' === $lineContent) { + $this->lines = [ + new Line('/**'.$lineEnd), + new Line($indent.' *'.$lineEnd), + new Line($indent.' */'), + ]; + + return; + } + + $this->lines = [ + new Line('/**'.$lineEnd), + new Line($indent.' * '.$lineContent.$lineEnd), + new Line($indent.' */'), + ]; + } + + public function makeSingleLine(): void + { + if (!$this->isMultiLine()) { + return; + } + + $usefulLines = array_filter( + $this->lines, + static fn (Line $line): bool => $line->containsUsefulContent() + ); + + if (1 < \count($usefulLines)) { + return; + } + + $lineContent = ''; + if (\count($usefulLines) > 0) { + $lineContent = $this->getSingleLineDocBlockEntry(array_shift($usefulLines)); + } + + $this->lines = [new Line('/** '.$lineContent.' */')]; + } + + public function getAnnotation(int $pos): ?Annotation + { + $annotations = $this->getAnnotations(); + + return $annotations[$pos] ?? null; + } + + /** + * Get specific types of annotations only. + * + * @param list|string $types + * + * @return list + */ + public function getAnnotationsOfType($types): array + { + $typesToSearchFor = (array) $types; + + $annotations = []; + + foreach ($this->getAnnotations() as $annotation) { + $tagName = $annotation->getTag()->getName(); + if (\in_array($tagName, $typesToSearchFor, true)) { + $annotations[] = $annotation; + } + } + + return $annotations; + } + + /** + * Get the actual content of this docblock. + */ + public function getContent(): string + { + return implode('', $this->lines); + } + + private function findAnnotationLength(int $start): int + { + $index = $start; + + while ($line = $this->getLine(++$index)) { + if ($line->containsATag()) { + // we've 100% reached the end of the description if we get here + break; + } + + if (!$line->containsUsefulContent()) { + // if next line is also non-useful, or contains a tag, then we're done here + $next = $this->getLine($index + 1); + if (null === $next || !$next->containsUsefulContent() || $next->containsATag()) { + break; + } + // otherwise, continue, the annotation must have contained a blank line in its description + } + } + + return $index - $start; + } + + private function getSingleLineDocBlockEntry(Line $line): string + { + $lineString = $line->getContent(); + + if ('' === $lineString) { + return $lineString; + } + + $lineString = str_replace('*/', '', $lineString); + $lineString = trim($lineString); + + if (str_starts_with($lineString, '/**')) { + $lineString = substr($lineString, 3); + } elseif (str_starts_with($lineString, '*')) { + $lineString = substr($lineString, 1); + } + + return trim($lineString); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Line.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Line.php new file mode 100644 index 00000000..1e6fa5b9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Line.php @@ -0,0 +1,128 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\DocBlock; + +use PhpCsFixer\Preg; + +/** + * This represents a line of a docblock. + * + * @author Graham Campbell + */ +final class Line +{ + /** + * The content of this line. + */ + private string $content; + + /** + * Create a new line instance. + */ + public function __construct(string $content) + { + $this->content = $content; + } + + /** + * Get the string representation of object. + */ + public function __toString(): string + { + return $this->content; + } + + /** + * Get the content of this line. + */ + public function getContent(): string + { + return $this->content; + } + + /** + * Does this line contain useful content? + * + * If the line contains text or tags, then this is true. + */ + public function containsUsefulContent(): bool + { + return Preg::match('/\\*\s*\S+/', $this->content) && '' !== trim(str_replace(['/', '*'], ' ', $this->content)); + } + + /** + * Does the line contain a tag? + * + * If this is true, then it must be the first line of an annotation. + */ + public function containsATag(): bool + { + return Preg::match('/\\*\s*@/', $this->content); + } + + /** + * Is the line the start of a docblock? + */ + public function isTheStart(): bool + { + return str_contains($this->content, '/**'); + } + + /** + * Is the line the end of a docblock? + */ + public function isTheEnd(): bool + { + return str_contains($this->content, '*/'); + } + + /** + * Set the content of this line. + */ + public function setContent(string $content): void + { + $this->content = $content; + } + + /** + * Remove this line by clearing its contents. + * + * Note that this method technically brakes the internal state of the + * docblock, but is useful when we need to retain the indices of lines + * during the execution of an algorithm. + */ + public function remove(): void + { + $this->content = ''; + } + + /** + * Append a blank docblock line to this line's contents. + * + * Note that this method technically brakes the internal state of the + * docblock, but is useful when we need to retain the indices of lines + * during the execution of an algorithm. + */ + public function addBlank(): void + { + $matched = Preg::match('/^(\h*\*)[^\r\n]*(\r?\n)$/', $this->content, $matches); + + if (!$matched) { + return; + } + + $this->content .= $matches[1].$matches[2]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/ShortDescription.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/ShortDescription.php new file mode 100644 index 00000000..dbd9e5da --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/ShortDescription.php @@ -0,0 +1,63 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\DocBlock; + +/** + * This class represents a short description (aka summary) of a docblock. + * + * @internal + */ +final class ShortDescription +{ + /** + * The docblock containing the short description. + */ + private DocBlock $doc; + + public function __construct(DocBlock $doc) + { + $this->doc = $doc; + } + + /** + * Get the line index of the line containing the end of the short + * description, if present. + */ + public function getEnd(): ?int + { + $reachedContent = false; + + foreach ($this->doc->getLines() as $index => $line) { + // we went past a description, then hit a tag or blank line, so + // the last line of the description must be the one before this one + if ($reachedContent && ($line->containsATag() || !$line->containsUsefulContent())) { + return $index - 1; + } + + // no short description was found + if ($line->containsATag()) { + return null; + } + + // we've reached content, but need to check the next lines too + // in case the short description is multi-line + if ($line->containsUsefulContent()) { + $reachedContent = true; + } + } + + return null; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Tag.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Tag.php new file mode 100644 index 00000000..6206718d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Tag.php @@ -0,0 +1,102 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\DocBlock; + +use PhpCsFixer\Preg; + +/** + * This represents a tag, as defined by the proposed PSR PHPDoc standard. + * + * @author Graham Campbell + * @author Jakub Kwaśniewski + */ +final class Tag +{ + /** + * All the tags defined by the proposed PSR PHPDoc standard. + */ + public const PSR_STANDARD_TAGS = [ + 'api', 'author', 'category', 'copyright', 'deprecated', 'example', + 'global', 'internal', 'license', 'link', 'method', 'package', 'param', + 'property', 'property-read', 'property-write', 'return', 'see', + 'since', 'subpackage', 'throws', 'todo', 'uses', 'var', 'version', + ]; + + /** + * The line containing the tag. + */ + private Line $line; + + /** + * The cached tag name. + */ + private ?string $name = null; + + /** + * Create a new tag instance. + */ + public function __construct(Line $line) + { + $this->line = $line; + } + + /** + * Get the tag name. + * + * This may be "param", or "return", etc. + */ + public function getName(): string + { + if (null === $this->name) { + Preg::matchAll('/@[a-zA-Z0-9_-]+(?=\s|$)/', $this->line->getContent(), $matches); + + if (isset($matches[0][0])) { + $this->name = ltrim($matches[0][0], '@'); + } else { + $this->name = 'other'; + } + } + + return $this->name; + } + + /** + * Set the tag name. + * + * This will also be persisted to the upstream line and annotation. + */ + public function setName(string $name): void + { + $current = $this->getName(); + + if ('other' === $current) { + throw new \RuntimeException('Cannot set name on unknown tag.'); + } + + $this->line->setContent(Preg::replace("/@{$current}/", "@{$name}", $this->line->getContent(), 1)); + + $this->name = $name; + } + + /** + * Is the tag a known tag? + * + * This is defined by if it exists in the proposed PSR PHPDoc standard. + */ + public function valid(): bool + { + return \in_array($this->getName(), self::PSR_STANDARD_TAGS, true); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TagComparator.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TagComparator.php new file mode 100644 index 00000000..578fd3a7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TagComparator.php @@ -0,0 +1,64 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\DocBlock; + +/** + * This class is responsible for comparing tags to see if they should be kept + * together, or kept apart. + * + * @author Graham Campbell + * @author Jakub Kwaśniewski + * + * @deprecated + */ +final class TagComparator +{ + /** + * Groups of tags that should be allowed to immediately follow each other. + * + * @internal + */ + public const DEFAULT_GROUPS = [ + ['deprecated', 'link', 'see', 'since'], + ['author', 'copyright', 'license'], + ['category', 'package', 'subpackage'], + ['property', 'property-read', 'property-write'], + ]; + + /** + * Should the given tags be kept together, or kept apart? + * + * @param string[][] $groups + */ + public static function shouldBeTogether(Tag $first, Tag $second, array $groups = self::DEFAULT_GROUPS): bool + { + @trigger_error('Method '.__METHOD__.' is deprecated and will be removed in version 4.0.', E_USER_DEPRECATED); + + $firstName = $first->getName(); + $secondName = $second->getName(); + + if ($firstName === $secondName) { + return true; + } + + foreach ($groups as $group) { + if (\in_array($firstName, $group, true) && \in_array($secondName, $group, true)) { + return true; + } + } + + return false; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TypeExpression.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TypeExpression.php new file mode 100644 index 00000000..505e0b3d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TypeExpression.php @@ -0,0 +1,612 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\DocBlock; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Utils; + +/** + * @internal + */ +final class TypeExpression +{ + /** + * Regex to match any PHP identifier. + * + * @internal + */ + public const REGEX_IDENTIFIER = '(?:(?!(?(?x) # one or several types separated by `|` or `&` +'.self::REGEX_TYPE.' + (?: + \h*(?[|&])\h* + (?&type) + )*+ + )'; + + private const REGEX_TYPE = '(?(?x) # single type + (?\??\h*) + (?: + (? + (?(?i)(?:array|list|object)(?-i)\h*\{\h*) + (? + (? + (?(?:(?&constant)|(?&identifier))\h*\??\h*:\h*|) + (?(?&types_inner)) + ) + (?: + \h*,\h* + (?&array_shape_inner) + )* + (?:\h*,\h*)? + |) + \h*\} + ) + | + (? # callable syntax, e.g. `callable(string, int...): bool` + (?(?&name)\h*\(\h*) + (? + (? + (?(?&types_inner)) + (?\h*&|) + (?\h*\.\.\.|) + (?\h*\$(?&identifier)|) + (?\h*=|) + ) + (?: + \h*,\h* + (?&callable_argument) + )* + (?:\h*,\h*)? + |) + \h*\) + (?: + \h*\:\h* + (?(?&type)) + )? + ) + | + (? # generic syntax, e.g.: `array` + (?(?&name)\h*<\h*) + (? + (?&types_inner) + (?: + \h*,\h* + (?&types_inner) + )* + (?:\h*,\h*)? + ) + \h*> + ) + | + (? # class constants with optional wildcard, e.g.: `Foo::*`, `Foo::CONST_A`, `FOO::CONST_*` + (?&name)::\*?(?:(?&identifier)\*?)* + ) + | + (? # single constant value (case insensitive), e.g.: 1, -1.8E+6, `\'a\'` + (?i) + # all sorts of numbers: with or without sign, supports literal separator and several numeric systems, + # e.g.: 1, +1.1, 1., .1, -1, 123E+8, 123_456_789, 0x7Fb4, 0b0110, 0o777 + [+-]?(?: + (?:0b[01]++(?:_[01]++)*+) + | (?:0o[0-7]++(?:_[0-7]++)*+) + | (?:0x[\da-f]++(?:_[\da-f]++)*+) + | (?:(?\d++(?:_\d++)*+)|(?=\.\d)) + (?:\.(?&constant_digits)|(?<=\d)\.)?+ + (?:e[+-]?(?&constant_digits))?+ + ) + | \'(?:[^\'\\\\]|\\\\.)*+\' + | "(?:[^"\\\\]|\\\\.)*+" + (?-i) + ) + | + (? # self reference, e.g.: $this, $self, @static + (?i) + [@$](?:this | self | static) + (?-i) + ) + | + (? # full name, e.g.: `int`, `\DateTime`, `\Foo\Bar`, `positive-int` + \\\\?+ + (?'.self::REGEX_IDENTIFIER.') + (?:[\\\\\-](?&identifier))*+ + ) + | + (? # parenthesized type, e.g.: `(int)`, `(int|\stdClass)` + (? + \(\h* + ) + (?: + (? + (?&types_inner) + ) + | + (? # conditional type, e.g.: `$foo is \Throwable ? false : $foo` + (? + (?:\$(?&identifier)) + | + (?(?&types_inner)) + ) + (? + \h+(?i)is(?:\h+not)?(?-i)\h+ + ) + (?(?&types_inner)) + (?\h*\?\h*) + (?(?&types_inner)) + (?\h*:\h*) + (?(?&types_inner)) + ) + ) + \h*\) + ) + ) + (? # array, e.g.: `string[]`, `array[][]` + (\h*\[\h*\])* + ) + (?:(?=1)0 + (? + (?&type) + (?: + \h*[|&]\h* + (?&type) + )*+ + ) + |) + )'; + + private string $value; + + private bool $isUnionType = false; + + private string $typesGlue = '|'; + + /** + * @var list + */ + private array $innerTypeExpressions = []; + + private ?NamespaceAnalysis $namespace; + + /** + * @var NamespaceUseAnalysis[] + */ + private array $namespaceUses; + + /** + * @param NamespaceUseAnalysis[] $namespaceUses + */ + public function __construct(string $value, ?NamespaceAnalysis $namespace, array $namespaceUses) + { + $this->value = $value; + $this->namespace = $namespace; + $this->namespaceUses = $namespaceUses; + + $this->parse(); + } + + public function toString(): string + { + return $this->value; + } + + /** + * @return string[] + */ + public function getTypes(): array + { + if ($this->isUnionType) { + return array_map( + static fn (array $type) => $type['expression']->toString(), + $this->innerTypeExpressions, + ); + } + + return [$this->value]; + } + + public function isUnionType(): bool + { + return $this->isUnionType; + } + + public function getTypesGlue(): string + { + return $this->typesGlue; + } + + /** + * @param \Closure(self): void $callback + */ + public function walkTypes(\Closure $callback): void + { + foreach ($this->innerTypeExpressions as [ + 'start_index' => $startIndex, + 'expression' => $inner, + ]) { + $initialValueLength = \strlen($inner->toString()); + + $inner->walkTypes($callback); + + $this->value = substr_replace( + $this->value, + $inner->toString(), + $startIndex, + $initialValueLength + ); + } + + $callback($this); + } + + /** + * @param \Closure(self, self): (-1|0|1) $compareCallback + */ + public function sortTypes(\Closure $compareCallback): void + { + $this->walkTypes(static function (self $type) use ($compareCallback): void { + if ($type->isUnionType) { + $type->innerTypeExpressions = Utils::stableSort( + $type->innerTypeExpressions, + static fn (array $type): self => $type['expression'], + $compareCallback, + ); + + $type->value = implode($type->getTypesGlue(), $type->getTypes()); + } + }); + } + + public function getCommonType(): ?string + { + $aliases = $this->getAliases(); + + $mainType = null; + + foreach ($this->getTypes() as $type) { + if ('null' === $type) { + continue; + } + + if (str_starts_with($type, '?')) { + $type = substr($type, 1); + } + + if (Preg::match('/\[\h*\]$/', $type)) { + $type = 'array'; + } elseif (Preg::match('/^(.+?)\h*[<{(]/', $type, $matches)) { + $type = $matches[1]; + } + + if (isset($aliases[$type])) { + $type = $aliases[$type]; + } + + if (null === $mainType || $type === $mainType) { + $mainType = $type; + + continue; + } + + $mainType = $this->getParentType($type, $mainType); + + if (null === $mainType) { + return null; + } + } + + return $mainType; + } + + public function allowsNull(): bool + { + foreach ($this->getTypes() as $type) { + if (\in_array($type, ['null', 'mixed'], true) || str_starts_with($type, '?')) { + return true; + } + } + + return false; + } + + private function parse(): void + { + $index = 0; + while (true) { + Preg::match( + '{\G'.self::REGEX_TYPE.'(?:\h*(?[|&])\h*|$)}', + $this->value, + $matches, + PREG_OFFSET_CAPTURE, + $index + ); + + if ([] === $matches) { + throw new \Exception('Unable to parse phpdoc type '.var_export($this->value, true)); + } + + if (!$this->isUnionType) { + if (($matches['glue'][0] ?? '') === '') { + break; + } + + $this->isUnionType = true; + $this->typesGlue = $matches['glue'][0]; + } + + $this->innerTypeExpressions[] = [ + 'start_index' => $index, + 'expression' => $this->inner($matches['type'][0]), + ]; + + $consumedValueLength = \strlen($matches[0][0]); + $index += $consumedValueLength; + + if (\strlen($this->value) === $index) { + return; + } + } + + $nullableLength = \strlen($matches['nullable'][0]); + $index = $nullableLength; + + if ('' !== ($matches['generic'][0] ?? '') && $matches['generic'][1] === $nullableLength) { + $this->parseCommaSeparatedInnerTypes( + $index + \strlen($matches['generic_start'][0]), + $matches['generic_types'][0] + ); + } elseif ('' !== ($matches['callable'][0] ?? '') && $matches['callable'][1] === $nullableLength) { + $this->parseCallableArgumentTypes( + $index + \strlen($matches['callable_start'][0]), + $matches['callable_arguments'][0] + ); + + if ('' !== ($matches['callable_return'][0] ?? '')) { + $this->innerTypeExpressions[] = [ + 'start_index' => \strlen($this->value) - \strlen($matches['callable_return'][0]), + 'expression' => $this->inner($matches['callable_return'][0]), + ]; + } + } elseif ('' !== ($matches['array_shape'][0] ?? '') && $matches['array_shape'][1] === $nullableLength) { + $this->parseArrayShapeInnerTypes( + $index + \strlen($matches['array_shape_start'][0]), + $matches['array_shape_inners'][0] + ); + } elseif ('' !== ($matches['parenthesized'][0] ?? '') && $matches['parenthesized'][1] === $nullableLength) { + $index += \strlen($matches['parenthesized_start'][0]); + + if ('' !== ($matches['conditional'][0] ?? '')) { + if ('' !== ($matches['conditional_cond_left_types'][0] ?? '')) { + $this->innerTypeExpressions[] = [ + 'start_index' => $index, + 'expression' => $this->inner($matches['conditional_cond_left_types'][0]), + ]; + } + + $index += \strlen($matches['conditional_cond_left'][0]) + \strlen($matches['conditional_cond_middle'][0]); + + $this->innerTypeExpressions[] = [ + 'start_index' => $index, + 'expression' => $this->inner($matches['conditional_cond_right_types'][0]), + ]; + + $index += \strlen($matches['conditional_cond_right_types'][0]) + \strlen($matches['conditional_true_start'][0]); + + $this->innerTypeExpressions[] = [ + 'start_index' => $index, + 'expression' => $this->inner($matches['conditional_true_types'][0]), + ]; + + $index += \strlen($matches['conditional_true_types'][0]) + \strlen($matches['conditional_false_start'][0]); + + $this->innerTypeExpressions[] = [ + 'start_index' => $index, + 'expression' => $this->inner($matches['conditional_false_types'][0]), + ]; + } else { + $this->innerTypeExpressions[] = [ + 'start_index' => $index, + 'expression' => $this->inner($matches['parenthesized_types'][0]), + ]; + } + } + } + + private function parseCommaSeparatedInnerTypes(int $startIndex, string $value): void + { + $index = 0; + while (\strlen($value) !== $index) { + Preg::match( + '{\G'.self::REGEX_TYPES.'(?:\h*,\h*|$)}', + $value, + $matches, + 0, + $index + ); + + $this->innerTypeExpressions[] = [ + 'start_index' => $startIndex + $index, + 'expression' => $this->inner($matches['types']), + ]; + + $index += \strlen($matches[0]); + } + } + + private function parseCallableArgumentTypes(int $startIndex, string $value): void + { + $index = 0; + while (\strlen($value) !== $index) { + Preg::match( + '{\G(?:(?=1)0'.self::REGEX_TYPES.'|(?<_callable_argument>(?&callable_argument))(?:\h*,\h*|$))}', + $value, + $prematches, + 0, + $index + ); + $consumedValue = $prematches['_callable_argument']; + $consumedValueLength = \strlen($consumedValue); + $consumedCommaLength = \strlen($prematches[0]) - $consumedValueLength; + + $addedPrefix = 'Closure('; + Preg::match( + '{^'.self::REGEX_TYPES.'$}', + $addedPrefix.$consumedValue.'): void', + $matches, + PREG_OFFSET_CAPTURE + ); + + $this->innerTypeExpressions[] = [ + 'start_index' => $startIndex + $index, + 'expression' => $this->inner($matches['callable_argument_type'][0]), + ]; + + $index += $consumedValueLength + $consumedCommaLength; + } + } + + private function parseArrayShapeInnerTypes(int $startIndex, string $value): void + { + $index = 0; + while (\strlen($value) !== $index) { + Preg::match( + '{\G(?:(?=1)0'.self::REGEX_TYPES.'|(?<_array_shape_inner>(?&array_shape_inner))(?:\h*,\h*|$))}', + $value, + $prematches, + 0, + $index + ); + $consumedValue = $prematches['_array_shape_inner']; + $consumedValueLength = \strlen($consumedValue); + $consumedCommaLength = \strlen($prematches[0]) - $consumedValueLength; + + $addedPrefix = 'array{'; + Preg::match( + '{^'.self::REGEX_TYPES.'$}', + $addedPrefix.$consumedValue.'}', + $matches, + PREG_OFFSET_CAPTURE + ); + + $this->innerTypeExpressions[] = [ + 'start_index' => $startIndex + $index + $matches['array_shape_inner_value'][1] - \strlen($addedPrefix), + 'expression' => $this->inner($matches['array_shape_inner_value'][0]), + ]; + + $index += $consumedValueLength + $consumedCommaLength; + } + } + + private function inner(string $value): self + { + return new self($value, $this->namespace, $this->namespaceUses); + } + + private function getParentType(string $type1, string $type2): ?string + { + $types = [ + $this->normalize($type1), + $this->normalize($type2), + ]; + natcasesort($types); + $types = implode('|', $types); + + $parents = [ + 'array|Traversable' => 'iterable', + 'array|iterable' => 'iterable', + 'iterable|Traversable' => 'iterable', + 'self|static' => 'self', + ]; + + return $parents[$types] ?? null; + } + + private function normalize(string $type): string + { + $aliases = $this->getAliases(); + + if (isset($aliases[$type])) { + return $aliases[$type]; + } + + if (\in_array($type, [ + 'array', + 'bool', + 'callable', + 'false', + 'float', + 'int', + 'iterable', + 'mixed', + 'never', + 'null', + 'object', + 'resource', + 'string', + 'true', + 'void', + ], true)) { + return $type; + } + + if (Preg::match('/\[\]$/', $type)) { + return 'array'; + } + + if (Preg::match('/^(.+?)namespaceUses as $namespaceUse) { + if ($namespaceUse->getShortName() === $type) { + return $namespaceUse->getFullName(); + } + } + + if (null === $this->namespace || $this->namespace->isGlobalNamespace()) { + return $type; + } + + return "{$this->namespace->getFullName()}\\{$type}"; + } + + /** + * @return array + */ + private function getAliases(): array + { + return [ + 'boolean' => 'bool', + 'callback' => 'callable', + 'double' => 'float', + 'false' => 'bool', + 'integer' => 'int', + 'list' => 'array', + 'real' => 'float', + 'true' => 'bool', + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/DocLexer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/DocLexer.php new file mode 100644 index 00000000..b451d00b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/DocLexer.php @@ -0,0 +1,173 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Doctrine\Annotation; + +use PhpCsFixer\Preg; + +/** + * Copyright (c) 2006-2013 Doctrine Project. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is furnished to do + * so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * @internal + */ +final class DocLexer +{ + public const T_NONE = 1; + public const T_INTEGER = 2; + public const T_STRING = 3; + public const T_FLOAT = 4; + + // All tokens that are also identifiers should be >= 100 + public const T_IDENTIFIER = 100; + public const T_AT = 101; + public const T_CLOSE_CURLY_BRACES = 102; + public const T_CLOSE_PARENTHESIS = 103; + public const T_COMMA = 104; + public const T_EQUALS = 105; + public const T_FALSE = 106; + public const T_NAMESPACE_SEPARATOR = 107; + public const T_OPEN_CURLY_BRACES = 108; + public const T_OPEN_PARENTHESIS = 109; + public const T_TRUE = 110; + public const T_NULL = 111; + public const T_COLON = 112; + public const T_MINUS = 113; + + /** @var array */ + private array $noCase = [ + '@' => self::T_AT, + ',' => self::T_COMMA, + '(' => self::T_OPEN_PARENTHESIS, + ')' => self::T_CLOSE_PARENTHESIS, + '{' => self::T_OPEN_CURLY_BRACES, + '}' => self::T_CLOSE_CURLY_BRACES, + '=' => self::T_EQUALS, + ':' => self::T_COLON, + '-' => self::T_MINUS, + '\\' => self::T_NAMESPACE_SEPARATOR, + ]; + + /** @var list */ + private array $tokens = []; + + private int $position = 0; + + private int $peek = 0; + + private ?string $regex; + + public function setInput(string $input): void + { + $this->tokens = []; + $this->reset(); + $this->scan($input); + } + + public function reset(): void + { + $this->peek = 0; + $this->position = 0; + } + + public function peek(): ?Token + { + if (isset($this->tokens[$this->position + $this->peek])) { + return $this->tokens[$this->position + $this->peek++]; + } + + return null; + } + + /** + * @return list + */ + private function getCatchablePatterns(): array + { + return [ + '[a-z_\\\][a-z0-9_\:\\\]*[a-z_][a-z0-9_]*', + '(?:[+-]?[0-9]+(?:[\.][0-9]+)*)(?:[eE][+-]?[0-9]+)?', + '"(?:""|[^"])*+"', + ]; + } + + /** + * @return list + */ + private function getNonCatchablePatterns(): array + { + return ['\s+', '\*+', '(.)']; + } + + /** + * @return self::T_* + */ + private function getType(string &$value): int + { + $type = self::T_NONE; + + if ('"' === $value[0]) { + $value = str_replace('""', '"', substr($value, 1, \strlen($value) - 2)); + + return self::T_STRING; + } + + if (isset($this->noCase[$value])) { + return $this->noCase[$value]; + } + + if ('_' === $value[0] || '\\' === $value[0] || !Preg::match('/[^A-Za-z]/', $value[0])) { + return self::T_IDENTIFIER; + } + + if (is_numeric($value)) { + return str_contains($value, '.') || false !== stripos($value, 'e') + ? self::T_FLOAT : self::T_INTEGER; + } + + return $type; + } + + private function scan(string $input): void + { + if (!isset($this->regex)) { + $this->regex = sprintf( + '/(%s)|%s/%s', + implode(')|(', $this->getCatchablePatterns()), + implode('|', $this->getNonCatchablePatterns()), + 'iu' + ); + } + + $flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE; + $matches = Preg::split($this->regex, $input, -1, $flags); + + foreach ($matches as $match) { + // Must remain before 'value' assignment since it can change content + $firstMatch = $match[0]; + $type = $this->getType($firstMatch); + + $this->tokens[] = new Token($type, $firstMatch, (int) $match[1]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Token.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Token.php new file mode 100644 index 00000000..314df6b2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Token.php @@ -0,0 +1,87 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Doctrine\Annotation; + +/** + * A Doctrine annotation token. + * + * @internal + */ +final class Token +{ + private int $type; + + private string $content; + + private int $position; + + /** + * @param int $type The type + * @param string $content The content + */ + public function __construct(int $type = DocLexer::T_NONE, string $content = '', int $position = 0) + { + $this->type = $type; + $this->content = $content; + $this->position = $position; + } + + public function getType(): int + { + return $this->type; + } + + public function setType(int $type): void + { + $this->type = $type; + } + + public function getContent(): string + { + return $this->content; + } + + public function setContent(string $content): void + { + $this->content = $content; + } + + public function getPosition(): int + { + return $this->position; + } + + /** + * Returns whether the token type is one of the given types. + * + * @param int|int[] $types + */ + public function isType($types): bool + { + if (!\is_array($types)) { + $types = [$types]; + } + + return \in_array($this->getType(), $types, true); + } + + /** + * Overrides the content with an empty string. + */ + public function clear(): void + { + $this->setContent(''); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Tokens.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Tokens.php new file mode 100644 index 00000000..a388cf4c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Tokens.php @@ -0,0 +1,304 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Doctrine\Annotation; + +use PhpCsFixer\Doctrine\Annotation\Token as AnnotationToken; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token as PhpToken; + +/** + * A list of Doctrine annotation tokens. + * + * @internal + * + * @extends \SplFixedArray + */ +final class Tokens extends \SplFixedArray +{ + /** + * @param string[] $ignoredTags + * + * @throws \InvalidArgumentException + */ + public static function createFromDocComment(PhpToken $input, array $ignoredTags = []): self + { + if (!$input->isGivenKind(T_DOC_COMMENT)) { + throw new \InvalidArgumentException('Input must be a T_DOC_COMMENT token.'); + } + + $tokens = []; + + $content = $input->getContent(); + $ignoredTextPosition = 0; + $currentPosition = 0; + $token = null; + while (false !== $nextAtPosition = strpos($content, '@', $currentPosition)) { + if (0 !== $nextAtPosition && !Preg::match('/\s/', $content[$nextAtPosition - 1])) { + $currentPosition = $nextAtPosition + 1; + + continue; + } + + $lexer = new DocLexer(); + $lexer->setInput(substr($content, $nextAtPosition)); + + $scannedTokens = []; + $index = 0; + $nbScannedTokensToUse = 0; + $nbScopes = 0; + while (null !== $token = $lexer->peek()) { + if (0 === $index && !$token->isType(DocLexer::T_AT)) { + break; + } + + if (1 === $index) { + if (!$token->isType(DocLexer::T_IDENTIFIER) || \in_array($token->getContent(), $ignoredTags, true)) { + break; + } + + $nbScannedTokensToUse = 2; + } + + if ($index >= 2 && 0 === $nbScopes && !$token->isType([DocLexer::T_NONE, DocLexer::T_OPEN_PARENTHESIS])) { + break; + } + + $scannedTokens[] = $token; + + if ($token->isType(DocLexer::T_OPEN_PARENTHESIS)) { + ++$nbScopes; + } elseif ($token->isType(DocLexer::T_CLOSE_PARENTHESIS)) { + if (0 === --$nbScopes) { + $nbScannedTokensToUse = \count($scannedTokens); + + break; + } + } + + ++$index; + } + + if (0 !== $nbScopes) { + break; + } + + if (0 !== $nbScannedTokensToUse) { + $ignoredTextLength = $nextAtPosition - $ignoredTextPosition; + if (0 !== $ignoredTextLength) { + $tokens[] = new Token(DocLexer::T_NONE, substr($content, $ignoredTextPosition, $ignoredTextLength)); + } + + $lastTokenEndIndex = 0; + foreach (\array_slice($scannedTokens, 0, $nbScannedTokensToUse) as $token) { + if ($token->isType(DocLexer::T_STRING)) { + $token = new AnnotationToken( + $token->getType(), + '"'.str_replace('"', '""', $token->getContent()).'"', + $token->getPosition() + ); + } + + $missingTextLength = $token->getPosition() - $lastTokenEndIndex; + if ($missingTextLength > 0) { + $tokens[] = new Token(DocLexer::T_NONE, substr( + $content, + $nextAtPosition + $lastTokenEndIndex, + $missingTextLength + )); + } + + $tokens[] = new Token($token->getType(), $token->getContent()); + $lastTokenEndIndex = $token->getPosition() + \strlen($token->getContent()); + } + + $currentPosition = $ignoredTextPosition = $nextAtPosition + $token->getPosition() + \strlen($token->getContent()); + } else { + $currentPosition = $nextAtPosition + 1; + } + } + + if ($ignoredTextPosition < \strlen($content)) { + $tokens[] = new Token(DocLexer::T_NONE, substr($content, $ignoredTextPosition)); + } + + return self::fromArray($tokens); + } + + /** + * Create token collection from array. + * + * @param Token[] $array the array to import + * @param ?bool $saveIndices save the numeric indices used in the original array, default is yes + */ + public static function fromArray($array, $saveIndices = null): self + { + $tokens = new self(\count($array)); + + if (null === $saveIndices || $saveIndices) { + foreach ($array as $key => $val) { + $tokens[$key] = $val; + } + } else { + $index = 0; + + foreach ($array as $val) { + $tokens[$index++] = $val; + } + } + + return $tokens; + } + + /** + * Returns the index of the closest next token that is neither a comment nor a whitespace token. + */ + public function getNextMeaningfulToken(int $index): ?int + { + return $this->getMeaningfulTokenSibling($index, 1); + } + + /** + * Returns the index of the closest previous token that is neither a comment nor a whitespace token. + */ + public function getPreviousMeaningfulToken(int $index): ?int + { + return $this->getMeaningfulTokenSibling($index, -1); + } + + /** + * Returns the index of the last token that is part of the annotation at the given index. + */ + public function getAnnotationEnd(int $index): ?int + { + $currentIndex = null; + + if (isset($this[$index + 2])) { + if ($this[$index + 2]->isType(DocLexer::T_OPEN_PARENTHESIS)) { + $currentIndex = $index + 2; + } elseif ( + isset($this[$index + 3]) + && $this[$index + 2]->isType(DocLexer::T_NONE) + && $this[$index + 3]->isType(DocLexer::T_OPEN_PARENTHESIS) + && Preg::match('/^(\R\s*\*\s*)*\s*$/', $this[$index + 2]->getContent()) + ) { + $currentIndex = $index + 3; + } + } + + if (null !== $currentIndex) { + $level = 0; + for ($max = \count($this); $currentIndex < $max; ++$currentIndex) { + if ($this[$currentIndex]->isType(DocLexer::T_OPEN_PARENTHESIS)) { + ++$level; + } elseif ($this[$currentIndex]->isType(DocLexer::T_CLOSE_PARENTHESIS)) { + --$level; + } + + if (0 === $level) { + return $currentIndex; + } + } + + return null; + } + + return $index + 1; + } + + /** + * Returns the code from the tokens. + */ + public function getCode(): string + { + $code = ''; + foreach ($this as $token) { + $code .= $token->getContent(); + } + + return $code; + } + + /** + * Inserts a token at the given index. + */ + public function insertAt(int $index, Token $token): void + { + $this->setSize($this->getSize() + 1); + + for ($i = $this->getSize() - 1; $i > $index; --$i) { + $this[$i] = $this[$i - 1] ?? new Token(); + } + + $this[$index] = $token; + } + + public function offsetSet($index, $token): void + { + if (null === $token) { + throw new \InvalidArgumentException('Token must be an instance of PhpCsFixer\\Doctrine\\Annotation\\Token, "null" given.'); + } + + if (!$token instanceof Token) { + $type = \gettype($token); + + if ('object' === $type) { + $type = \get_class($token); + } + + throw new \InvalidArgumentException(sprintf('Token must be an instance of PhpCsFixer\\Doctrine\\Annotation\\Token, "%s" given.', $type)); + } + + parent::offsetSet($index, $token); + } + + /** + * @param mixed $index + * + * @throws \OutOfBoundsException + */ + public function offsetUnset($index): void + { + if (!isset($this[$index])) { + throw new \OutOfBoundsException(sprintf('Index "%s" is invalid or does not exist.', $index)); + } + + $max = \count($this) - 1; + while ($index < $max) { + $this[$index] = $this[$index + 1]; + ++$index; + } + + parent::offsetUnset($index); + + $this->setSize($max); + } + + private function getMeaningfulTokenSibling(int $index, int $direction): ?int + { + while (true) { + $index += $direction; + + if (!$this->offsetExists($index)) { + break; + } + + if (!$this[$index]->isType(DocLexer::T_NONE)) { + return $index; + } + } + + return null; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationLocator.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationLocator.php new file mode 100644 index 00000000..f384e48c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationLocator.php @@ -0,0 +1,85 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Documentation; + +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Utils; + +/** + * @internal + */ +final class DocumentationLocator +{ + private string $path; + + public function __construct() + { + $this->path = \dirname(__DIR__, 2).'/doc'; + } + + public function getFixersDocumentationDirectoryPath(): string + { + return $this->path.'/rules'; + } + + public function getFixersDocumentationIndexFilePath(): string + { + return $this->getFixersDocumentationDirectoryPath().'/index.rst'; + } + + public function getFixerDocumentationFilePath(FixerInterface $fixer): string + { + return $this->getFixersDocumentationDirectoryPath().'/'.Preg::replaceCallback( + '/^.*\\\\(.+)\\\\(.+)Fixer$/', + static fn (array $matches): string => Utils::camelCaseToUnderscore($matches[1]).'/'.Utils::camelCaseToUnderscore($matches[2]), + \get_class($fixer) + ).'.rst'; + } + + public function getFixerDocumentationFileRelativePath(FixerInterface $fixer): string + { + return Preg::replace( + '#^'.preg_quote($this->getFixersDocumentationDirectoryPath(), '#').'/#', + '', + $this->getFixerDocumentationFilePath($fixer) + ); + } + + public function getRuleSetsDocumentationDirectoryPath(): string + { + return $this->path.'/ruleSets'; + } + + public function getRuleSetsDocumentationIndexFilePath(): string + { + return $this->getRuleSetsDocumentationDirectoryPath().'/index.rst'; + } + + public function getRuleSetsDocumentationFilePath(string $name): string + { + return $this->getRuleSetsDocumentationDirectoryPath().'/'.str_replace(':risky', 'Risky', ucfirst(substr($name, 1))).'.rst'; + } + + public function getListingFilePath(): string + { + return $this->path.'/list.rst'; + } + + public function getUsageFilePath(): string + { + return $this->path.'/usage.rst'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Documentation/FixerDocumentGenerator.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Documentation/FixerDocumentGenerator.php new file mode 100644 index 00000000..25070dd4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Documentation/FixerDocumentGenerator.php @@ -0,0 +1,384 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Documentation; + +use PhpCsFixer\Console\Command\HelpCommand; +use PhpCsFixer\Differ\FullDiffer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\FixerConfiguration\AliasedFixerOption; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\DeprecatedFixerOptionInterface; +use PhpCsFixer\FixerDefinition\CodeSampleInterface; +use PhpCsFixer\FixerDefinition\FileSpecificCodeSampleInterface; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\RuleSet\RuleSet; +use PhpCsFixer\RuleSet\RuleSets; +use PhpCsFixer\StdinFileInfo; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Utils; + +/** + * @internal + */ +final class FixerDocumentGenerator +{ + private DocumentationLocator $locator; + + private FullDiffer $differ; + + public function __construct(DocumentationLocator $locator) + { + $this->locator = $locator; + $this->differ = new FullDiffer(); + } + + public function generateFixerDocumentation(FixerInterface $fixer): string + { + $name = $fixer->getName(); + $title = "Rule ``{$name}``"; + $titleLine = str_repeat('=', \strlen($title)); + $doc = "{$titleLine}\n{$title}\n{$titleLine}"; + + $definition = $fixer->getDefinition(); + $doc .= "\n\n".RstUtils::toRst($definition->getSummary()); + + $description = $definition->getDescription(); + + if (null !== $description) { + $description = RstUtils::toRst($description); + $doc .= <<getSuccessorsNames(); + + if (0 !== \count($alternatives)) { + $deprecationDescription .= RstUtils::toRst(sprintf( + "\n\nYou should use %s instead.", + Utils::naturalLanguageJoinWithBackticks($alternatives) + ), 0); + } + } + + $riskyDescription = ''; + $riskyDescriptionRaw = $definition->getRiskyDescription(); + + if (null !== $riskyDescriptionRaw) { + $riskyDescriptionRaw = RstUtils::toRst($riskyDescriptionRaw, 0); + $riskyDescription = <<getConfigurationDefinition(); + + foreach ($configurationDefinition->getOptions() as $option) { + $optionInfo = "``{$option->getName()}``"; + $optionInfo .= "\n".str_repeat('~', \strlen($optionInfo)); + + if ($option instanceof DeprecatedFixerOptionInterface) { + $deprecationMessage = RstUtils::toRst($option->getDeprecationMessage()); + $optionInfo .= "\n\n.. warning:: This option is deprecated and will be removed in the next major version. {$deprecationMessage}"; + } + + $optionInfo .= "\n\n".RstUtils::toRst($option->getDescription()); + + if ($option instanceof AliasedFixerOption) { + $optionInfo .= "\n\n.. note:: The previous name of this option was ``{$option->getAlias()}`` but it is now deprecated and will be removed in the next major version."; + } + + $allowed = HelpCommand::getDisplayableAllowedValues($option); + + if (null === $allowed) { + $allowedKind = 'Allowed types'; + $allowed = array_map( + static fn ($value): string => '``'.$value.'``', + $option->getAllowedTypes(), + ); + } else { + $allowedKind = 'Allowed values'; + $allowed = array_map(static fn ($value): string => $value instanceof AllowedValueSubset + ? 'a subset of ``'.Utils::toString($value->getAllowedValues()).'``' + : '``'.Utils::toString($value).'``', $allowed); + } + + $allowed = Utils::naturalLanguageJoin($allowed, ''); + $optionInfo .= "\n\n{$allowedKind}: {$allowed}"; + + if ($option->hasDefault()) { + $default = Utils::toString($option->getDefault()); + $optionInfo .= "\n\nDefault value: ``{$default}``"; + } else { + $optionInfo .= "\n\nThis option is required."; + } + + $doc .= "\n\n{$optionInfo}"; + } + } + + $samples = $definition->getCodeSamples(); + + if (0 !== \count($samples)) { + $doc .= <<<'RST' + + + Examples + -------- + RST; + + foreach ($samples as $index => $sample) { + $title = sprintf('Example #%d', $index + 1); + $titleLine = str_repeat('~', \strlen($title)); + $doc .= "\n\n{$title}\n{$titleLine}"; + + if ($fixer instanceof ConfigurableFixerInterface) { + if (null === $sample->getConfiguration()) { + $doc .= "\n\n*Default* configuration."; + } else { + $doc .= sprintf( + "\n\nWith configuration: ``%s``.", + Utils::toString($sample->getConfiguration()) + ); + } + } + + $doc .= "\n".$this->generateSampleDiff($fixer, $sample, $index + 1, $name); + } + } + + $ruleSetConfigs = self::getSetsOfRule($name); + + if ([] !== $ruleSetConfigs) { + $plural = 1 !== \count($ruleSetConfigs) ? 's' : ''; + $doc .= << $config) { + $ruleSetPath = $this->locator->getRuleSetsDocumentationFilePath($set); + $ruleSetPath = substr($ruleSetPath, strrpos($ruleSetPath, '/')); + + $configInfo = (null !== $config) + ? " with config:\n\n ``".Utils::toString($config)."``\n" + : ''; + + $doc .= <<`_{$configInfo}\n + RST; + } + } + + $reflectionObject = new \ReflectionObject($fixer); + $className = str_replace('\\', '\\\\', $reflectionObject->getName()); + $fileName = $reflectionObject->getFileName(); + $fileName = str_replace('\\', '/', $fileName); + $fileName = substr($fileName, strrpos($fileName, '/src/Fixer/') + 1); + $fileName = "`{$className} <./../../../{$fileName}>`_"; + + $doc .= <<', $doc); + + return "{$doc}\n"; + } + + /** + * @internal + * + * @return array> + */ + public static function getSetsOfRule(string $ruleName): array + { + $ruleSetConfigs = []; + + foreach (RuleSets::getSetDefinitionNames() as $set) { + $ruleSet = new RuleSet([$set => true]); + + if ($ruleSet->hasRule($ruleName)) { + $ruleSetConfigs[$set] = $ruleSet->getRuleConfiguration($ruleName); + } + } + + return $ruleSetConfigs; + } + + /** + * @param FixerInterface[] $fixers + */ + public function generateFixersDocumentationIndex(array $fixers): string + { + $overrideGroups = [ + 'PhpUnit' => 'PHPUnit', + 'PhpTag' => 'PHP Tag', + 'Phpdoc' => 'PHPDoc', + ]; + + usort($fixers, static fn (FixerInterface $a, FixerInterface $b): int => \get_class($a) <=> \get_class($b)); + + $documentation = <<<'RST' + ======================= + List of Available Rules + ======================= + RST; + + $currentGroup = null; + + foreach ($fixers as $fixer) { + $namespace = Preg::replace('/^.*\\\\(.+)\\\\.+Fixer$/', '$1', \get_class($fixer)); + $group = $overrideGroups[$namespace] ?? Preg::replace('/(?<=[[:lower:]])(?=[[:upper:]])/', ' ', $namespace); + + if ($group !== $currentGroup) { + $underline = str_repeat('-', \strlen($group)); + $documentation .= "\n\n{$group}\n{$underline}\n"; + + $currentGroup = $group; + } + + $path = './'.$this->locator->getFixerDocumentationFileRelativePath($fixer); + + $attributes = []; + + if ($fixer instanceof DeprecatedFixerInterface) { + $attributes[] = 'deprecated'; + } + + if ($fixer->isRisky()) { + $attributes[] = 'risky'; + } + + $attributes = 0 === \count($attributes) + ? '' + : ' *('.implode(', ', $attributes).')*'; + + $summary = str_replace('`', '``', $fixer->getDefinition()->getSummary()); + + $documentation .= <<getName()} <{$path}>`_{$attributes} + + {$summary} + RST; + } + + return "{$documentation}\n"; + } + + private function generateSampleDiff(FixerInterface $fixer, CodeSampleInterface $sample, int $sampleNumber, string $ruleName): string + { + if ($sample instanceof VersionSpecificCodeSampleInterface && !$sample->isSuitableFor(\PHP_VERSION_ID)) { + $existingFile = @file_get_contents($this->locator->getFixerDocumentationFilePath($fixer)); + + if (false !== $existingFile) { + Preg::match("/\\RExample #{$sampleNumber}\\R.+?(?\\R\\.\\. code-block:: diff\\R\\R.*?)\\R(?:\\R\\S|$)/s", $existingFile, $matches); + + if (isset($matches['diff'])) { + return $matches['diff']; + } + } + + $error = <<getCode(); + + $tokens = Tokens::fromCode($old); + $file = $sample instanceof FileSpecificCodeSampleInterface + ? $sample->getSplFileInfo() + : new StdinFileInfo(); + + if ($fixer instanceof ConfigurableFixerInterface) { + $fixer->configure($sample->getConfiguration() ?? []); + } + + $fixer->fix($file, $tokens); + + $diff = $this->differ->diff($old, $tokens->generateCode()); + $diff = Preg::replace('/@@[ \+\-\d,]+@@\n/', '', $diff); + $diff = Preg::replace('/\r/', '^M', $diff); + $diff = Preg::replace('/^ $/m', '', $diff); + $diff = Preg::replace('/\n$/', '', $diff); + $diff = RstUtils::indent($diff, 3); + + return << + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Documentation; + +use PhpCsFixer\Preg; + +/** + * @internal + */ +final class RstUtils +{ + private function __construct() + { + // cannot create instance of util. class + } + + public static function toRst(string $string, int $indent = 0): string + { + $string = wordwrap(self::ensureProperInlineCode($string), 80 - $indent); + + return 0 === $indent ? $string : self::indent($string, $indent); + } + + public static function ensureProperInlineCode(string $string): string + { + return Preg::replace('/(? + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Documentation; + +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\RuleSet\RuleSetDescriptionInterface; +use PhpCsFixer\Utils; + +/** + * @internal + */ +final class RuleSetDocumentationGenerator +{ + private DocumentationLocator $locator; + + public function __construct(DocumentationLocator $locator) + { + $this->locator = $locator; + } + + /** + * @param FixerInterface[] $fixers + */ + public function generateRuleSetsDocumentation(RuleSetDescriptionInterface $definition, array $fixers): string + { + $fixerNames = []; + + foreach ($fixers as $fixer) { + $fixerNames[$fixer->getName()] = $fixer; + } + + $title = "Rule set ``{$definition->getName()}``"; + $titleLine = str_repeat('=', \strlen($title)); + $doc = "{$titleLine}\n{$title}\n{$titleLine}\n\n".$definition->getDescription(); + + if ($definition->isRisky()) { + $doc .= ' This set contains rules that are risky.'; + } + + $rules = $definition->getRules(); + + if ([] === $rules) { + $doc .= "\n\nThis is an empty set."; + } else { + $enabledRules = array_filter($rules, static fn ($config) => false !== $config); + $disabledRules = array_filter($rules, static fn ($config) => false === $config); + + $listRules = function (array $rules) use (&$doc, $fixerNames): void { + foreach ($rules as $rule => $config) { + if (str_starts_with($rule, '@')) { + $ruleSetPath = $this->locator->getRuleSetsDocumentationFilePath($rule); + $ruleSetPath = substr($ruleSetPath, strrpos($ruleSetPath, '/')); + + $doc .= "\n- `{$rule} <.{$ruleSetPath}>`_"; + } else { + $path = Preg::replace( + '#^'.preg_quote($this->locator->getFixersDocumentationDirectoryPath(), '#').'/#', + './../rules/', + $this->locator->getFixerDocumentationFilePath($fixerNames[$rule]) + ); + + $doc .= "\n- `{$rule} <{$path}>`_"; + } + + if (!\is_bool($config)) { + $doc .= " with config:\n\n ``".Utils::toString($config)."``\n"; + } + } + }; + + if ([] !== $enabledRules) { + $doc .= "\n\nRules\n-----\n"; + $listRules($enabledRules); + } + + if ([] !== $disabledRules) { + $doc .= "\n\nDisabled rules\n--------------\n"; + $listRules($disabledRules); + } + } + + return $doc."\n"; + } + + /** + * @param array $setDefinitions + */ + public function generateRuleSetsDocumentationIndex(array $setDefinitions): string + { + $documentation = <<<'RST' + =========================== + List of Available Rule sets + =========================== + RST; + foreach ($setDefinitions as $name => $path) { + $path = substr($path, strrpos($path, '/')); + $documentation .= "\n- `{$name} <.{$path}>`_"; + } + + return $documentation."\n"; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Error/Error.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Error/Error.php new file mode 100644 index 00000000..1f14ed9f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Error/Error.php @@ -0,0 +1,93 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Error; + +/** + * An abstraction for errors that can occur before and during fixing. + * + * @author Andreas Möller + * + * @internal + */ +final class Error +{ + /** + * Error which has occurred in linting phase, before applying any fixers. + */ + public const TYPE_INVALID = 1; + + /** + * Error which has occurred during fixing phase. + */ + public const TYPE_EXCEPTION = 2; + + /** + * Error which has occurred in linting phase, after applying any fixers. + */ + public const TYPE_LINT = 3; + + private int $type; + + private string $filePath; + + private ?\Throwable $source; + + /** + * @var list + */ + private array $appliedFixers; + + private ?string $diff; + + /** + * @param list $appliedFixers + */ + public function __construct(int $type, string $filePath, ?\Throwable $source = null, array $appliedFixers = [], ?string $diff = null) + { + $this->type = $type; + $this->filePath = $filePath; + $this->source = $source; + $this->appliedFixers = $appliedFixers; + $this->diff = $diff; + } + + public function getFilePath(): string + { + return $this->filePath; + } + + public function getSource(): ?\Throwable + { + return $this->source; + } + + public function getType(): int + { + return $this->type; + } + + /** + * @return list + */ + public function getAppliedFixers(): array + { + return $this->appliedFixers; + } + + public function getDiff(): ?string + { + return $this->diff; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Error/ErrorsManager.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Error/ErrorsManager.php new file mode 100644 index 00000000..3d787a3f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Error/ErrorsManager.php @@ -0,0 +1,73 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Error; + +/** + * Manager of errors that occur during fixing. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class ErrorsManager +{ + /** + * @var Error[] + */ + private array $errors = []; + + /** + * Returns errors reported during linting before fixing. + * + * @return Error[] + */ + public function getInvalidErrors(): array + { + return array_filter($this->errors, static fn (Error $error): bool => Error::TYPE_INVALID === $error->getType()); + } + + /** + * Returns errors reported during fixing. + * + * @return Error[] + */ + public function getExceptionErrors(): array + { + return array_filter($this->errors, static fn (Error $error): bool => Error::TYPE_EXCEPTION === $error->getType()); + } + + /** + * Returns errors reported during linting after fixing. + * + * @return Error[] + */ + public function getLintErrors(): array + { + return array_filter($this->errors, static fn (Error $error): bool => Error::TYPE_LINT === $error->getType()); + } + + /** + * Returns true if no errors were reported. + */ + public function isEmpty(): bool + { + return [] === $this->errors; + } + + public function report(Error $error): void + { + $this->errors[] = $error; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FileReader.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FileReader.php new file mode 100644 index 00000000..d4fb752c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FileReader.php @@ -0,0 +1,73 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * File reader that unify access to regular file and stdin-alike file. + * + * Regular file could be read multiple times with `file_get_contents`, but file provided on stdin cannot. + * Consecutive try will provide empty content for stdin-alike file. + * This reader unifies access to them. + * + * @internal + */ +final class FileReader +{ + /** + * @var null|string + */ + private $stdinContent; + + public static function createSingleton(): self + { + static $instance = null; + + if (!$instance) { + $instance = new self(); + } + + return $instance; + } + + public function read(string $filePath): string + { + if ('php://stdin' === $filePath) { + if (null === $this->stdinContent) { + $this->stdinContent = $this->readRaw($filePath); + } + + return $this->stdinContent; + } + + return $this->readRaw($filePath); + } + + private function readRaw(string $realPath): string + { + $content = @file_get_contents($realPath); + + if (false === $content) { + $error = error_get_last(); + + throw new \RuntimeException(sprintf( + 'Failed to read content from "%s".%s', + $realPath, + null !== $error ? ' '.$error['message'] : '' + )); + } + + return $content; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FileRemoval.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FileRemoval.php new file mode 100644 index 00000000..dce4d924 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FileRemoval.php @@ -0,0 +1,100 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * Handles files removal with possibility to remove them on shutdown. + * + * @author Adam Klvač + * @author Dariusz Rumiński + * + * @internal + */ +final class FileRemoval +{ + /** + * List of observed files to be removed. + * + * @var array + */ + private array $files = []; + + public function __construct() + { + register_shutdown_function([$this, 'clean']); + } + + public function __destruct() + { + $this->clean(); + } + + /** + * This class is not intended to be serialized, + * and cannot be deserialized (see __wakeup method). + */ + public function __sleep(): array + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + /** + * Disable the deserialization of the class to prevent attacker executing + * code by leveraging the __destruct method. + * + * @see https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection + */ + public function __wakeup(): void + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + /** + * Adds a file to be removed. + */ + public function observe(string $path): void + { + $this->files[$path] = true; + } + + /** + * Removes a file from shutdown removal. + */ + public function delete(string $path): void + { + if (isset($this->files[$path])) { + unset($this->files[$path]); + } + + $this->unlink($path); + } + + /** + * Removes attached files. + */ + public function clean(): void + { + foreach ($this->files as $file => $value) { + $this->unlink($file); + } + + $this->files = []; + } + + private function unlink(string $path): void + { + @unlink($path); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Finder.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Finder.php new file mode 100644 index 00000000..419354ef --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Finder.php @@ -0,0 +1,35 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use Symfony\Component\Finder\Finder as BaseFinder; + +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + */ +class Finder extends BaseFinder +{ + public function __construct() + { + parent::__construct(); + + $this + ->files() + ->name('/\.php$/') + ->exclude('vendor') + ; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractIncrementOperatorFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractIncrementOperatorFixer.php new file mode 100644 index 00000000..3a2db980 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractIncrementOperatorFixer.php @@ -0,0 +1,58 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Tokenizer\Tokens; + +abstract class AbstractIncrementOperatorFixer extends AbstractFixer +{ + final protected function findStart(Tokens $tokens, int $index): int + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + $token = $tokens[$index]; + + $blockType = Tokens::detectBlockType($token); + if (null !== $blockType && !$blockType['isStart']) { + $index = $tokens->findBlockStart($blockType['type'], $index); + $token = $tokens[$index]; + } + } while (!$token->equalsAny(['$', [T_VARIABLE]])); + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $prevToken = $tokens[$prevIndex]; + + if ($prevToken->equals('$')) { + return $this->findStart($tokens, $index); + } + + if ($prevToken->isObjectOperator()) { + return $this->findStart($tokens, $prevIndex); + } + + if ($prevToken->isGivenKind(T_PAAMAYIM_NEKUDOTAYIM)) { + $prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + if (!$tokens[$prevPrevIndex]->isGivenKind([T_STATIC, T_STRING])) { + return $this->findStart($tokens, $prevIndex); + } + + $index = $tokens->getTokenNotOfKindsSibling($prevIndex, -1, [T_NS_SEPARATOR, T_STATIC, T_STRING]); + $index = $tokens->getNextMeaningfulToken($index); + } + + return $index; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractPhpUnitFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractPhpUnitFixer.php new file mode 100644 index 00000000..9d90aba1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractPhpUnitFixer.php @@ -0,0 +1,164 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\Indicator\PhpUnitTestCaseIndicator; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + */ +abstract class AbstractPhpUnitFixer extends AbstractFixer +{ + final public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAllTokenKindsFound([T_CLASS, T_STRING]); + } + + final protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $phpUnitTestCaseIndicator = new PhpUnitTestCaseIndicator(); + + foreach ($phpUnitTestCaseIndicator->findPhpUnitClasses($tokens) as $indices) { + $this->applyPhpUnitClassFix($tokens, $indices[0], $indices[1]); + } + } + + abstract protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void; + + final protected function getDocBlockIndex(Tokens $tokens, int $index): int + { + $modifiers = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FINAL, T_ABSTRACT, T_COMMENT]; + + if (\defined('T_ATTRIBUTE')) { // @TODO: drop condition when PHP 8.0+ is required + $modifiers[] = T_ATTRIBUTE; + } + + if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.2+ is required + $modifiers[] = T_READONLY; + } + + do { + $index = $tokens->getPrevNonWhitespace($index); + + if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $index = $tokens->getPrevTokenOfKind($index, [[T_ATTRIBUTE]]); + } + } while ($tokens[$index]->isGivenKind($modifiers)); + + return $index; + } + + /** + * @param array $preventingAnnotations + */ + final protected function ensureIsDockBlockWithAnnotation( + Tokens $tokens, + int $index, + string $annotation, + array $preventingAnnotations + ): void { + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + + if ($this->isPHPDoc($tokens, $docBlockIndex)) { + $this->updateDocBlockIfNeeded($tokens, $docBlockIndex, $annotation, $preventingAnnotations); + } else { + $this->createDocBlock($tokens, $docBlockIndex, $annotation); + } + } + + final protected function isPHPDoc(Tokens $tokens, int $index): bool + { + return $tokens[$index]->isGivenKind(T_DOC_COMMENT); + } + + private function createDocBlock(Tokens $tokens, int $docBlockIndex, string $annotation): void + { + $lineEnd = $this->whitespacesConfig->getLineEnding(); + $originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); + $toInsert = [ + new Token([T_DOC_COMMENT, "/**{$lineEnd}{$originalIndent} * @{$annotation}{$lineEnd}{$originalIndent} */"]), + new Token([T_WHITESPACE, $lineEnd.$originalIndent]), + ]; + $index = $tokens->getNextMeaningfulToken($docBlockIndex); + $tokens->insertAt($index, $toInsert); + + if (!$tokens[$index - 1]->isGivenKind(T_WHITESPACE)) { + $extraNewLines = $this->whitespacesConfig->getLineEnding(); + + if (!$tokens[$index - 1]->isGivenKind(T_OPEN_TAG)) { + $extraNewLines .= $this->whitespacesConfig->getLineEnding(); + } + + $tokens->insertAt($index, [ + new Token([T_WHITESPACE, $extraNewLines.WhitespacesAnalyzer::detectIndent($tokens, $index)]), + ]); + } + } + + /** + * @param array $preventingAnnotations + */ + private function updateDocBlockIfNeeded( + Tokens $tokens, + int $docBlockIndex, + string $annotation, + array $preventingAnnotations + ): void { + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + foreach ($preventingAnnotations as $preventingAnnotation) { + if ([] !== $doc->getAnnotationsOfType($preventingAnnotation)) { + return; + } + } + $doc = $this->makeDocBlockMultiLineIfNeeded($doc, $tokens, $docBlockIndex, $annotation); + $lines = $this->addInternalAnnotation($doc, $tokens, $docBlockIndex, $annotation); + $lines = implode('', $lines); + + $tokens[$docBlockIndex] = new Token([T_DOC_COMMENT, $lines]); + } + + /** + * @return array + */ + private function addInternalAnnotation(DocBlock $docBlock, Tokens $tokens, int $docBlockIndex, string $annotation): array + { + $lines = $docBlock->getLines(); + $originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $docBlockIndex); + $lineEnd = $this->whitespacesConfig->getLineEnding(); + array_splice($lines, -1, 0, $originalIndent.' * @'.$annotation.$lineEnd); + + return $lines; + } + + private function makeDocBlockMultiLineIfNeeded(DocBlock $doc, Tokens $tokens, int $docBlockIndex, string $annotation): DocBlock + { + $lines = $doc->getLines(); + if (1 === \count($lines) && [] === $doc->getAnnotationsOfType($annotation)) { + $indent = WhitespacesAnalyzer::detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); + $doc->makeMultiLine($indent, $this->whitespacesConfig->getLineEnding()); + + return $doc; + } + + return $doc; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractShortOperatorFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractShortOperatorFixer.php new file mode 100644 index 00000000..0653e195 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractShortOperatorFixer.php @@ -0,0 +1,264 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\RangeAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + */ +abstract class AbstractShortOperatorFixer extends AbstractFixer +{ + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer(); + + for ($index = \count($tokens) - 1; $index > 3; --$index) { + if (!$this->isOperatorTokenCandidate($tokens, $index)) { + continue; + } + + // get what is before the operator + + $beforeRange = $this->getBeforeOperatorRange($tokens, $index); + $equalsIndex = $tokens->getPrevMeaningfulToken($beforeRange['start']); + + // make sure that before that is '=' + + if (!$tokens[$equalsIndex]->equals('=')) { + continue; + } + + // get and check what is before '=' + + $assignRange = $this->getBeforeOperatorRange($tokens, $equalsIndex); + $beforeAssignmentIndex = $tokens->getPrevMeaningfulToken($assignRange['start']); + + if ($tokens[$beforeAssignmentIndex]->equals(':')) { + if (!$this->belongsToSwitchOrAlternativeSyntax($alternativeSyntaxAnalyzer, $tokens, $beforeAssignmentIndex)) { + continue; + } + } elseif (!$tokens[$beforeAssignmentIndex]->equalsAny([';', '{', '}', '(', ')', ',', [T_OPEN_TAG], [T_RETURN]])) { + continue; + } + + // check if "assign" and "before" the operator are (functionally) the same + + if (RangeAnalyzer::rangeEqualsRange($tokens, $assignRange, $beforeRange)) { + $this->shortenOperation($tokens, $equalsIndex, $index, $assignRange, $beforeRange); + + continue; + } + + if (!$this->isOperatorCommutative($tokens[$index])) { + continue; + } + + $afterRange = $this->getAfterOperatorRange($tokens, $index); + + // check if "assign" and "after" the operator are (functionally) the same + if (!RangeAnalyzer::rangeEqualsRange($tokens, $assignRange, $afterRange)) { + continue; + } + + $this->shortenOperation($tokens, $equalsIndex, $index, $assignRange, $afterRange); + } + } + + abstract protected function getReplacementToken(Token $token): Token; + + abstract protected function isOperatorTokenCandidate(Tokens $tokens, int $index): bool; + + /** + * @param array{start: int, end: int} $assignRange + * @param array{start: int, end: int} $operatorRange + */ + private function shortenOperation( + Tokens $tokens, + int $equalsIndex, + int $operatorIndex, + array $assignRange, + array $operatorRange + ): void { + $tokens[$equalsIndex] = $this->getReplacementToken($tokens[$operatorIndex]); + $tokens->clearTokenAndMergeSurroundingWhitespace($operatorIndex); + $this->clearMeaningfulFromRange($tokens, $operatorRange); + + foreach ([$equalsIndex, $assignRange['end']] as $i) { + $i = $tokens->getNonEmptySibling($i, 1); + + if ($tokens[$i]->isWhitespace(" \t")) { + $tokens[$i] = new Token([T_WHITESPACE, ' ']); + } elseif (!$tokens[$i]->isWhitespace()) { + $tokens->insertAt($i, new Token([T_WHITESPACE, ' '])); + } + } + } + + /** + * @return array{start: int, end: int} + */ + private function getAfterOperatorRange(Tokens $tokens, int $index): array + { + $index = $tokens->getNextMeaningfulToken($index); + $range = ['start' => $index]; + + while (true) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if (null === $nextIndex || $tokens[$nextIndex]->equalsAny([';', ',', [T_CLOSE_TAG]])) { + break; + } + + $blockType = Tokens::detectBlockType($tokens[$nextIndex]); + + if (null === $blockType) { + $index = $nextIndex; + + continue; + } + + if (false === $blockType['isStart']) { + break; + } + + $index = $tokens->findBlockEnd($blockType['type'], $nextIndex); + } + + $range['end'] = $index; + + return $range; + } + + /** + * @return array{start: int, end: int} + */ + private function getBeforeOperatorRange(Tokens $tokens, int $index): array + { + static $blockOpenTypes; + + if (null === $blockOpenTypes) { + $blockOpenTypes = [',']; // not a true "block type", but speeds up things + + foreach (Tokens::getBlockEdgeDefinitions() as $definition) { + $blockOpenTypes[] = $definition['start']; + } + } + + $controlStructureWithoutBracesTypes = [T_IF, T_ELSE, T_ELSEIF, T_FOR, T_FOREACH, T_WHILE]; + + $previousIndex = $tokens->getPrevMeaningfulToken($index); + $previousToken = $tokens[$previousIndex]; + + if ($tokens[$previousIndex]->equalsAny($blockOpenTypes)) { + return ['start' => $index, 'end' => $index]; + } + + $range = ['end' => $previousIndex]; + $index = $previousIndex; + + while ($previousToken->equalsAny([ + '$', + ']', + ')', + [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], + [CT::T_DYNAMIC_PROP_BRACE_CLOSE], + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + [T_NS_SEPARATOR], + [T_STRING], + [T_VARIABLE], + ])) { + $blockType = Tokens::detectBlockType($previousToken); + + if (null !== $blockType) { + $blockStart = $tokens->findBlockStart($blockType['type'], $previousIndex); + + if ($tokens[$previousIndex]->equals(')') && $tokens[$tokens->getPrevMeaningfulToken($blockStart)]->isGivenKind($controlStructureWithoutBracesTypes)) { + break; // we went too far back + } + + $previousIndex = $blockStart; + } + + $index = $previousIndex; + $previousIndex = $tokens->getPrevMeaningfulToken($previousIndex); + $previousToken = $tokens[$previousIndex]; + } + + if ($previousToken->isGivenKind(T_OBJECT_OPERATOR)) { + $index = $this->getBeforeOperatorRange($tokens, $previousIndex)['start']; + } elseif ($previousToken->isGivenKind(T_PAAMAYIM_NEKUDOTAYIM)) { + $index = $this->getBeforeOperatorRange($tokens, $tokens->getPrevMeaningfulToken($previousIndex))['start']; + } + + $range['start'] = $index; + + return $range; + } + + /** + * @param array{start: int, end: int} $range + */ + private function clearMeaningfulFromRange(Tokens $tokens, array $range): void + { + // $range['end'] must be meaningful! + for ($i = $range['end']; $i >= $range['start']; $i = $tokens->getPrevMeaningfulToken($i)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } + + private function isOperatorCommutative(Token $operatorToken): bool + { + static $commutativeKinds = ['*', '|', '&', '^']; // note that for arrays in PHP `+` is not commutative + static $nonCommutativeKinds = ['-', '/', '.', '%', '+']; + + if ($operatorToken->isGivenKind(T_COALESCE)) { + return false; + } + + if ($operatorToken->equalsAny($commutativeKinds)) { + return true; + } + + if ($operatorToken->equalsAny($nonCommutativeKinds)) { + return false; + } + + throw new \InvalidArgumentException(sprintf('Not supported operator "%s".', $operatorToken->toJson())); + } + + private function belongsToSwitchOrAlternativeSyntax(AlternativeSyntaxAnalyzer $alternativeSyntaxAnalyzer, Tokens $tokens, int $index): bool + { + $candidate = $index; + $index = $tokens->getPrevMeaningfulToken($candidate); + + if ($tokens[$index]->isGivenKind(T_DEFAULT)) { + return true; + } + + $index = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(T_CASE)) { + return true; + } + + return $alternativeSyntaxAnalyzer->belongsToAlternativeSyntax($tokens, $candidate); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ArrayPushFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ArrayPushFixer.php new file mode 100644 index 00000000..9023bbd3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ArrayPushFixer.php @@ -0,0 +1,207 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class ArrayPushFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts simple usages of `array_push($x, $y);` to `$x[] = $y;`.', + [new CodeSample("isTokenKindFound(T_STRING) && $tokens->count() > 7; + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + for ($index = $tokens->count() - 7; $index > 0; --$index) { + if (!$tokens[$index]->equals([T_STRING, 'array_push'], false)) { + continue; + } + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; // redeclare/override + } + + // meaningful before must be `getPrevMeaningfulToken($index); + $namespaceSeparatorIndex = null; + + if ($tokens[$index]->isGivenKind(T_NS_SEPARATOR)) { + $namespaceSeparatorIndex = $index; + $index = $tokens->getPrevMeaningfulToken($index); + } + + if (!$tokens[$index]->equalsAny([';', '{', '}', ')', [T_OPEN_TAG]])) { + continue; + } + + // figure out where the arguments list opens + + $openBraceIndex = $tokens->getNextMeaningfulToken($callIndex); + $blockType = Tokens::detectBlockType($tokens[$openBraceIndex]); + + if (null === $blockType || Tokens::BLOCK_TYPE_PARENTHESIS_BRACE !== $blockType['type']) { + continue; + } + + // figure out where the arguments list closes + + $closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openBraceIndex); + + // meaningful after `)` must be `;`, `? >` or nothing + + $afterCloseBraceIndex = $tokens->getNextMeaningfulToken($closeBraceIndex); + + if (null !== $afterCloseBraceIndex && !$tokens[$afterCloseBraceIndex]->equalsAny([';', [T_CLOSE_TAG]])) { + continue; + } + + // must have 2 arguments + + // first argument must be a variable (with possibly array indexing etc.), + // after that nothing meaningful should be there till the next `,` or `)` + // if `)` than we cannot fix it (it is a single argument call) + + $firstArgumentStop = $this->getFirstArgumentEnd($tokens, $openBraceIndex); + $firstArgumentStop = $tokens->getNextMeaningfulToken($firstArgumentStop); + + if (!$tokens[$firstArgumentStop]->equals(',')) { + return; + } + + // second argument can be about anything but ellipsis, we must make sure there is not + // a third argument (or more) passed to `array_push` + + $secondArgumentStart = $tokens->getNextMeaningfulToken($firstArgumentStop); + $secondArgumentStop = $this->getSecondArgumentEnd($tokens, $secondArgumentStart, $closeBraceIndex); + + if (null === $secondArgumentStop) { + continue; + } + + // candidate is valid, replace tokens + + $tokens->clearTokenAndMergeSurroundingWhitespace($closeBraceIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($firstArgumentStop); + $tokens->insertAt( + $firstArgumentStop, + [ + new Token('['), + new Token(']'), + new Token([T_WHITESPACE, ' ']), + new Token('='), + ] + ); + $tokens->clearTokenAndMergeSurroundingWhitespace($openBraceIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($callIndex); + + if (null !== $namespaceSeparatorIndex) { + $tokens->clearTokenAndMergeSurroundingWhitespace($namespaceSeparatorIndex); + } + } + } + + private function getFirstArgumentEnd(Tokens $tokens, int $index): int + { + $nextIndex = $tokens->getNextMeaningfulToken($index); + $nextToken = $tokens[$nextIndex]; + + while ($nextToken->equalsAny([ + '$', + '[', + '(', + [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN], + [CT::T_DYNAMIC_PROP_BRACE_OPEN], + [CT::T_DYNAMIC_VAR_BRACE_OPEN], + [CT::T_NAMESPACE_OPERATOR], + [T_NS_SEPARATOR], + [T_STATIC], + [T_STRING], + [T_VARIABLE], + ])) { + $blockType = Tokens::detectBlockType($nextToken); + + if (null !== $blockType) { + $nextIndex = $tokens->findBlockEnd($blockType['type'], $nextIndex); + } + + $index = $nextIndex; + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + $nextToken = $tokens[$nextIndex]; + } + + if ($nextToken->isGivenKind(T_OBJECT_OPERATOR)) { + return $this->getFirstArgumentEnd($tokens, $nextIndex); + } + + if ($nextToken->isGivenKind(T_PAAMAYIM_NEKUDOTAYIM)) { + return $this->getFirstArgumentEnd($tokens, $tokens->getNextMeaningfulToken($nextIndex)); + } + + return $index; + } + + /** + * @param int $endIndex boundary, i.e. tokens index of `)` + */ + private function getSecondArgumentEnd(Tokens $tokens, int $index, int $endIndex): ?int + { + if ($tokens[$index]->isGivenKind(T_ELLIPSIS)) { + return null; + } + + for (; $index <= $endIndex; ++$index) { + $blockType = Tokens::detectBlockType($tokens[$index]); + + while (null !== $blockType && $blockType['isStart']) { + $index = $tokens->findBlockEnd($blockType['type'], $index); + $index = $tokens->getNextMeaningfulToken($index); + $blockType = Tokens::detectBlockType($tokens[$index]); + } + + if ($tokens[$index]->equals(',') || $tokens[$index]->isGivenKind([T_YIELD, T_YIELD_FROM, T_LOGICAL_AND, T_LOGICAL_OR, T_LOGICAL_XOR])) { + return null; + } + } + + return $endIndex; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/BacktickToShellExecFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/BacktickToShellExecFixer.php new file mode 100644 index 00000000..351cdad7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/BacktickToShellExecFixer.php @@ -0,0 +1,150 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + */ +final class BacktickToShellExecFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound('`'); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts backtick operators to `shell_exec` calls.', + [ + new CodeSample( + <<<'EOT' + call()}`; + + EOT + ), + ], + 'Conversion is done only when it is non risky, so when special chars like single-quotes, double-quotes and backticks are not used inside the command.' + ); + } + + /** + * {@inheritdoc} + * + * Must run before EscapeImplicitBackslashesFixer, ExplicitStringVariableFixer, NativeFunctionInvocationFixer, SingleQuoteFixer. + */ + public function getPriority(): int + { + return 17; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $backtickStarted = false; + $backtickTokens = []; + for ($index = $tokens->count() - 1; $index > 0; --$index) { + $token = $tokens[$index]; + + if (!$token->equals('`')) { + if ($backtickStarted) { + $backtickTokens[$index] = $token; + } + + continue; + } + + $backtickTokens[$index] = $token; + + if ($backtickStarted) { + $this->fixBackticks($tokens, $backtickTokens); + $backtickTokens = []; + } + + $backtickStarted = !$backtickStarted; + } + } + + /** + * Override backtick code with corresponding double-quoted string. + * + * @param array $backtickTokens + */ + private function fixBackticks(Tokens $tokens, array $backtickTokens): void + { + // Track indices for final override + ksort($backtickTokens); + $openingBacktickIndex = key($backtickTokens); + end($backtickTokens); + $closingBacktickIndex = key($backtickTokens); + + // Strip enclosing backticks + array_shift($backtickTokens); + array_pop($backtickTokens); + + // Double-quoted strings are parsed differently if they contain + // variables or not, so we need to build the new token array accordingly + $count = \count($backtickTokens); + + $newTokens = [ + new Token([T_STRING, 'shell_exec']), + new Token('('), + ]; + + if (1 !== $count) { + $newTokens[] = new Token('"'); + } + + foreach ($backtickTokens as $token) { + if (!$token->isGivenKind(T_ENCAPSED_AND_WHITESPACE)) { + $newTokens[] = $token; + + continue; + } + + $content = $token->getContent(); + // Escaping special chars depends on the context: too tricky + if (Preg::match('/[`"\']/u', $content)) { + return; + } + + $kind = T_ENCAPSED_AND_WHITESPACE; + + if (1 === $count) { + $content = '"'.$content.'"'; + $kind = T_CONSTANT_ENCAPSED_STRING; + } + + $newTokens[] = new Token([$kind, $content]); + } + + if (1 !== $count) { + $newTokens[] = new Token('"'); + } + + $newTokens[] = new Token(')'); + + $tokens->overrideRange($openingBacktickIndex, $closingBacktickIndex, $newTokens); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/EregToPregFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/EregToPregFixer.php new file mode 100644 index 00000000..c9366294 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/EregToPregFixer.php @@ -0,0 +1,193 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\PregException; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Matteo Beccati + */ +final class EregToPregFixer extends AbstractFixer +{ + /** + * @var list> the list of the ext/ereg function names, their preg equivalent and the preg modifier(s), if any + * all condensed in an array of arrays + */ + private static array $functions = [ + ['ereg', 'preg_match', ''], + ['eregi', 'preg_match', 'i'], + ['ereg_replace', 'preg_replace', ''], + ['eregi_replace', 'preg_replace', 'i'], + ['split', 'preg_split', ''], + ['spliti', 'preg_split', 'i'], + ]; + + /** + * @var list the list of preg delimiters, in order of preference + */ + private static array $delimiters = ['/', '#', '!']; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace deprecated `ereg` regular expression functions with `preg`.', + [new CodeSample("isTokenKindFound(T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $end = $tokens->count() - 1; + $functionsAnalyzer = new FunctionsAnalyzer(); + + foreach (self::$functions as $map) { + // the sequence is the function name, followed by "(" and a quoted string + $seq = [[T_STRING, $map[0]], '(', [T_CONSTANT_ENCAPSED_STRING]]; + $currIndex = 0; + + while (true) { + $match = $tokens->findSequence($seq, $currIndex, $end, false); + + // did we find a match? + if (null === $match) { + break; + } + + // findSequence also returns the tokens, but we're only interested in the indices, i.e.: + // 0 => function name, + // 1 => parenthesis "(" + // 2 => quoted string passed as 1st parameter + $match = array_keys($match); + + // advance tokenizer cursor + $currIndex = $match[2]; + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $match[0])) { + continue; + } + + // ensure the first parameter is just a string (e.g. has nothing appended) + $next = $tokens->getNextMeaningfulToken($match[2]); + + if (null === $next || !$tokens[$next]->equalsAny([',', ')'])) { + continue; + } + + // convert to PCRE + $regexTokenContent = $tokens[$match[2]]->getContent(); + + if ('b' === $regexTokenContent[0] || 'B' === $regexTokenContent[0]) { + $quote = $regexTokenContent[1]; + $prefix = $regexTokenContent[0]; + $string = substr($regexTokenContent, 2, -1); + } else { + $quote = $regexTokenContent[0]; + $prefix = ''; + $string = substr($regexTokenContent, 1, -1); + } + + $delim = $this->getBestDelimiter($string); + $preg = $delim.addcslashes($string, $delim).$delim.'D'.$map[2]; + + // check if the preg is valid + if (!$this->checkPreg($preg)) { + continue; + } + + // modify function and argument + $tokens[$match[0]] = new Token([T_STRING, $map[1]]); + $tokens[$match[2]] = new Token([T_CONSTANT_ENCAPSED_STRING, $prefix.$quote.$preg.$quote]); + } + } + } + + /** + * Check the validity of a PCRE. + * + * @param string $pattern the regular expression + */ + private function checkPreg(string $pattern): bool + { + try { + Preg::match($pattern, ''); + + return true; + } catch (PregException $e) { + return false; + } + } + + /** + * Get the delimiter that would require the least escaping in a regular expression. + * + * @param string $pattern the regular expression + * + * @return string the preg delimiter + */ + private function getBestDelimiter(string $pattern): string + { + // try to find something that's not used + $delimiters = []; + + foreach (self::$delimiters as $k => $d) { + if (!str_contains($pattern, $d)) { + return $d; + } + + $delimiters[$d] = [substr_count($pattern, $d), $k]; + } + + // return the least used delimiter, using the position in the list as a tiebreaker + uasort($delimiters, static function (array $a, array $b): int { + if ($a[0] === $b[0]) { + return $a[1] <=> $b[1]; + } + + return $a[0] <=> $b[0]; + }); + + return key($delimiters); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/MbStrFunctionsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/MbStrFunctionsFixer.php new file mode 100644 index 00000000..6dd62f49 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/MbStrFunctionsFixer.php @@ -0,0 +1,131 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + */ +final class MbStrFunctionsFixer extends AbstractFunctionReferenceFixer +{ + /** + * list of the string-related function names and their mb_ equivalent. + * + * @var array< + * string, + * array{ + * alternativeName: string, + * argumentCount: list, + * }, + * > + */ + private static array $functionsMap = [ + 'str_split' => ['alternativeName' => 'mb_str_split', 'argumentCount' => [1, 2, 3]], + 'stripos' => ['alternativeName' => 'mb_stripos', 'argumentCount' => [2, 3]], + 'stristr' => ['alternativeName' => 'mb_stristr', 'argumentCount' => [2, 3]], + 'strlen' => ['alternativeName' => 'mb_strlen', 'argumentCount' => [1]], + 'strpos' => ['alternativeName' => 'mb_strpos', 'argumentCount' => [2, 3]], + 'strrchr' => ['alternativeName' => 'mb_strrchr', 'argumentCount' => [2]], + 'strripos' => ['alternativeName' => 'mb_strripos', 'argumentCount' => [2, 3]], + 'strrpos' => ['alternativeName' => 'mb_strrpos', 'argumentCount' => [2, 3]], + 'strstr' => ['alternativeName' => 'mb_strstr', 'argumentCount' => [2, 3]], + 'strtolower' => ['alternativeName' => 'mb_strtolower', 'argumentCount' => [1]], + 'strtoupper' => ['alternativeName' => 'mb_strtoupper', 'argumentCount' => [1]], + 'substr' => ['alternativeName' => 'mb_substr', 'argumentCount' => [2, 3]], + 'substr_count' => ['alternativeName' => 'mb_substr_count', 'argumentCount' => [2, 3, 4]], + ]; + + /** + * @var array< + * string, + * array{ + * alternativeName: string, + * argumentCount: list, + * }, + * > + */ + private array $functions; + + public function __construct() + { + parent::__construct(); + + $this->functions = array_filter( + self::$functionsMap, + static fn (array $mapping): bool => (new \ReflectionFunction($mapping['alternativeName']))->isInternal() + ); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace non multibyte-safe functions with corresponding mb function.', + [ + new CodeSample( + 'functions as $functionIdentity => $functionReplacement) { + $currIndex = 0; + do { + // try getting function reference and translate boundaries for humans + $boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1); + if (null === $boundaries) { + // next function search, as current one not found + continue 2; + } + + [$functionName, $openParenthesis, $closeParenthesis] = $boundaries; + $count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis); + if (!\in_array($count, $functionReplacement['argumentCount'], true)) { + continue 2; + } + + // analysing cursor shift, so nested calls could be processed + $currIndex = $openParenthesis; + + $tokens[$functionName] = new Token([T_STRING, $functionReplacement['alternativeName']]); + } while (null !== $currIndex); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ModernizeStrposFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ModernizeStrposFixer.php new file mode 100644 index 00000000..b060b4e6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ModernizeStrposFixer.php @@ -0,0 +1,233 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Alexander M. Turek + */ +final class ModernizeStrposFixer extends AbstractFixer +{ + private const REPLACEMENTS = [ + [ + 'operator' => [T_IS_IDENTICAL, '==='], + 'operand' => [T_LNUMBER, '0'], + 'replacement' => [T_STRING, 'str_starts_with'], + 'negate' => false, + ], + [ + 'operator' => [T_IS_NOT_IDENTICAL, '!=='], + 'operand' => [T_LNUMBER, '0'], + 'replacement' => [T_STRING, 'str_starts_with'], + 'negate' => true, + ], + [ + 'operator' => [T_IS_NOT_IDENTICAL, '!=='], + 'operand' => [T_STRING, 'false'], + 'replacement' => [T_STRING, 'str_contains'], + 'negate' => false, + ], + [ + 'operator' => [T_IS_IDENTICAL, '==='], + 'operand' => [T_STRING, 'false'], + 'replacement' => [T_STRING, 'str_contains'], + 'negate' => true, + ], + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace `strpos()` calls with `str_starts_with()` or `str_contains()` if possible.', + [ + new CodeSample( + 'isTokenKindFound(T_STRING) && $tokens->isAnyTokenKindsFound([T_IS_IDENTICAL, T_IS_NOT_IDENTICAL]); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + for ($index = \count($tokens) - 1; $index > 0; --$index) { + // find candidate function call + if (!$tokens[$index]->equals([T_STRING, 'strpos'], false) || !$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + // assert called with 2 arguments + $openIndex = $tokens->getNextMeaningfulToken($index); + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); + $arguments = $argumentsAnalyzer->getArguments($tokens, $openIndex, $closeIndex); + + if (2 !== \count($arguments)) { + continue; + } + + // check if part condition and fix if needed + $compareTokens = $this->getCompareTokens($tokens, $index, -1); // look behind + + if (null === $compareTokens) { + $compareTokens = $this->getCompareTokens($tokens, $closeIndex, 1); // look ahead + } + + if (null !== $compareTokens) { + $this->fixCall($tokens, $index, $compareTokens); + } + } + } + + /** + * @param array{operator_index: int, operand_index: int} $operatorIndices + */ + private function fixCall(Tokens $tokens, int $functionIndex, array $operatorIndices): void + { + foreach (self::REPLACEMENTS as $replacement) { + if (!$tokens[$operatorIndices['operator_index']]->equals($replacement['operator'])) { + continue; + } + + if (!$tokens[$operatorIndices['operand_index']]->equals($replacement['operand'], false)) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($operatorIndices['operator_index']); + $tokens->clearTokenAndMergeSurroundingWhitespace($operatorIndices['operand_index']); + $tokens->clearTokenAndMergeSurroundingWhitespace($functionIndex); + + if ($replacement['negate']) { + $negateInsertIndex = $functionIndex; + + $prevFunctionIndex = $tokens->getPrevMeaningfulToken($functionIndex); + if ($tokens[$prevFunctionIndex]->isGivenKind(T_NS_SEPARATOR)) { + $negateInsertIndex = $prevFunctionIndex; + } + + $tokens->insertAt($negateInsertIndex, new Token('!')); + ++$functionIndex; + } + + $tokens->insertAt($functionIndex, new Token($replacement['replacement'])); + + break; + } + } + + /** + * @param -1|1 $direction + * + * @return null|array{operator_index: int, operand_index: int} + */ + private function getCompareTokens(Tokens $tokens, int $offsetIndex, int $direction): ?array + { + $operatorIndex = $tokens->getMeaningfulTokenSibling($offsetIndex, $direction); + + if (null !== $operatorIndex && $tokens[$operatorIndex]->isGivenKind(T_NS_SEPARATOR)) { + $operatorIndex = $tokens->getMeaningfulTokenSibling($operatorIndex, $direction); + } + + if (null === $operatorIndex || !$tokens[$operatorIndex]->isGivenKind([T_IS_IDENTICAL, T_IS_NOT_IDENTICAL])) { + return null; + } + + $operandIndex = $tokens->getMeaningfulTokenSibling($operatorIndex, $direction); + + if (null === $operandIndex) { + return null; + } + + $operand = $tokens[$operandIndex]; + + if (!$operand->equals([T_LNUMBER, '0']) && !$operand->equals([T_STRING, 'false'], false)) { + return null; + } + + $precedenceTokenIndex = $tokens->getMeaningfulTokenSibling($operandIndex, $direction); + + if (null !== $precedenceTokenIndex && $this->isOfHigherPrecedence($tokens[$precedenceTokenIndex])) { + return null; + } + + return ['operator_index' => $operatorIndex, 'operand_index' => $operandIndex]; + } + + private function isOfHigherPrecedence(Token $token): bool + { + static $operatorsKinds = [ + T_DEC, // -- + T_INC, // ++ + T_INSTANCEOF, // instanceof + T_IS_GREATER_OR_EQUAL, // >= + T_IS_SMALLER_OR_EQUAL, // <= + T_POW, // ** + T_SL, // << + T_SR, // >> + ]; + + static $operatorsPerContent = [ + '!', + '%', + '*', + '+', + '-', + '.', + '/', + '<', + '>', + '~', + ]; + + return $token->isGivenKind($operatorsKinds) || $token->equalsAny($operatorsPerContent); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasFunctionsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasFunctionsFixer.php new file mode 100644 index 00000000..b56d0c40 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasFunctionsFixer.php @@ -0,0 +1,322 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Vladimir Reznichenko + * @author Dariusz Rumiński + */ +final class NoAliasFunctionsFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const SETS = [ + '@internal' => [ + 'diskfreespace' => 'disk_free_space', + + 'dns_check_record' => 'checkdnsrr', + 'dns_get_mx' => 'getmxrr', + + 'session_commit' => 'session_write_close', + + 'stream_register_wrapper' => 'stream_wrapper_register', + 'set_file_buffer' => 'stream_set_write_buffer', + 'socket_set_blocking' => 'stream_set_blocking', + 'socket_get_status' => 'stream_get_meta_data', + 'socket_set_timeout' => 'stream_set_timeout', + 'socket_getopt' => 'socket_get_option', + 'socket_setopt' => 'socket_set_option', + + 'chop' => 'rtrim', + 'close' => 'closedir', + 'doubleval' => 'floatval', + 'fputs' => 'fwrite', + 'get_required_files' => 'get_included_files', + 'ini_alter' => 'ini_set', + 'is_double' => 'is_float', + 'is_integer' => 'is_int', + 'is_long' => 'is_int', + 'is_real' => 'is_float', + 'is_writeable' => 'is_writable', + 'join' => 'implode', + 'key_exists' => 'array_key_exists', + 'magic_quotes_runtime' => 'set_magic_quotes_runtime', + 'pos' => 'current', + 'show_source' => 'highlight_file', + 'sizeof' => 'count', + 'strchr' => 'strstr', + 'user_error' => 'trigger_error', + ], + + '@IMAP' => [ + 'imap_create' => 'imap_createmailbox', + 'imap_fetchtext' => 'imap_body', + 'imap_header' => 'imap_headerinfo', + 'imap_listmailbox' => 'imap_list', + 'imap_listsubscribed' => 'imap_lsub', + 'imap_rename' => 'imap_renamemailbox', + 'imap_scan' => 'imap_listscan', + 'imap_scanmailbox' => 'imap_listscan', + ], + + '@ldap' => [ + 'ldap_close' => 'ldap_unbind', + 'ldap_modify' => 'ldap_mod_replace', + ], + + '@mysqli' => [ + 'mysqli_execute' => 'mysqli_stmt_execute', + 'mysqli_set_opt' => 'mysqli_options', + 'mysqli_escape_string' => 'mysqli_real_escape_string', + ], + + '@pg' => [ + 'pg_exec' => 'pg_query', + ], + + '@oci' => [ + 'oci_free_cursor' => 'oci_free_statement', + ], + + '@odbc' => [ + 'odbc_do' => 'odbc_exec', + 'odbc_field_precision' => 'odbc_field_len', + ], + + '@mbreg' => [ + 'mbereg' => 'mb_ereg', + 'mbereg_match' => 'mb_ereg_match', + 'mbereg_replace' => 'mb_ereg_replace', + 'mbereg_search' => 'mb_ereg_search', + 'mbereg_search_getpos' => 'mb_ereg_search_getpos', + 'mbereg_search_getregs' => 'mb_ereg_search_getregs', + 'mbereg_search_init' => 'mb_ereg_search_init', + 'mbereg_search_pos' => 'mb_ereg_search_pos', + 'mbereg_search_regs' => 'mb_ereg_search_regs', + 'mbereg_search_setpos' => 'mb_ereg_search_setpos', + 'mberegi' => 'mb_eregi', + 'mberegi_replace' => 'mb_eregi_replace', + 'mbregex_encoding' => 'mb_regex_encoding', + 'mbsplit' => 'mb_split', + ], + + '@openssl' => [ + 'openssl_get_publickey' => 'openssl_pkey_get_public', + 'openssl_get_privatekey' => 'openssl_pkey_get_private', + ], + + '@sodium' => [ + 'sodium_crypto_scalarmult_base' => 'sodium_crypto_box_publickey_from_secretkey', + ], + + '@exif' => [ + 'read_exif_data' => 'exif_read_data', + ], + + '@ftp' => [ + 'ftp_quit' => 'ftp_close', + ], + + '@posix' => [ + 'posix_errno' => 'posix_get_last_error', + ], + + '@pcntl' => [ + 'pcntl_errno' => 'pcntl_get_last_error', + ], + + '@time' => [ + 'mktime' => ['time', 0], + 'gmmktime' => ['time', 0], + ], + ]; + + /** + * @var array|string> stores alias (key) - master (value) functions mapping + */ + private array $aliases = []; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->aliases = []; + + foreach ($this->configuration['sets'] as $set) { + if ('@all' === $set) { + $this->aliases = array_merge(...array_values(self::SETS)); + + break; + } + + $this->aliases = array_merge($this->aliases, self::SETS[$set]); + } + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Master functions shall be used instead of aliases.', + [ + new CodeSample( + ' ['@mbreg']] + ), + ], + null, + 'Risky when any of the alias functions are overridden.' + ); + } + + /** + * {@inheritdoc} + * + * Must run before ImplodeCallFixer, PhpUnitDedicateAssertFixer. + */ + public function getPriority(): int + { + return 40; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + /** @var Token $token */ + foreach ($tokens->findGivenKind(T_STRING) as $index => $token) { + // check mapping hit + $tokenContent = strtolower($token->getContent()); + + if (!isset($this->aliases[$tokenContent])) { + continue; + } + + // skip expressions without parameters list + $openParenthesis = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$openParenthesis]->equals('(')) { + continue; + } + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + if (\is_array($this->aliases[$tokenContent])) { + [$alias, $numberOfArguments] = $this->aliases[$tokenContent]; + + $count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis)); + + if ($numberOfArguments !== $count) { + continue; + } + } else { + $alias = $this->aliases[$tokenContent]; + } + + $tokens[$index] = new Token([T_STRING, $alias]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $sets = [ + '@all' => 'all listed sets', + '@internal' => 'native functions', + '@exif' => 'EXIF functions', + '@ftp' => 'FTP functions', + '@IMAP' => 'IMAP functions', + '@ldap' => 'LDAP functions', + '@mbreg' => 'from `ext-mbstring`', + '@mysqli' => 'mysqli functions', + '@oci' => 'oci functions', + '@odbc' => 'odbc functions', + '@openssl' => 'openssl functions', + '@pcntl' => 'PCNTL functions', + '@pg' => 'pg functions', + '@posix' => 'POSIX functions', + '@snmp' => 'SNMP functions', // @TODO Remove on next major 4.0 as this set is now empty + '@sodium' => 'libsodium functions', + '@time' => 'time functions', + ]; + + $list = "List of sets to fix. Defined sets are:\n\n"; + + foreach ($sets as $set => $description) { + $list .= sprintf("* `%s` (%s);\n", $set, $description); + } + + $list = rtrim($list, ";\n").'.'; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('sets', $list)) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset(array_keys($sets))]) + ->setDefault(['@internal', '@IMAP', '@pg']) + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasLanguageConstructCallFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasLanguageConstructCallFixer.php new file mode 100644 index 00000000..4df764ab --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasLanguageConstructCallFixer.php @@ -0,0 +1,59 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class NoAliasLanguageConstructCallFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Master language constructs shall be used instead of aliases.', + [ + new CodeSample( + 'isTokenKindFound(T_EXIT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_EXIT)) { + continue; + } + + if ('exit' === strtolower($token->getContent())) { + continue; + } + + $tokens[$index] = new Token([T_EXIT, 'exit']); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoMixedEchoPrintFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoMixedEchoPrintFixer.php new file mode 100644 index 00000000..ff5e666c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoMixedEchoPrintFixer.php @@ -0,0 +1,139 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Sullivan Senechal + */ +final class NoMixedEchoPrintFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var string + */ + private $callBack; + + /** + * @var int T_ECHO or T_PRINT + */ + private $candidateTokenType; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + if ('echo' === $this->configuration['use']) { + $this->candidateTokenType = T_PRINT; + $this->callBack = 'fixPrintToEcho'; + } else { + $this->candidateTokenType = T_ECHO; + $this->callBack = 'fixEchoToPrint'; + } + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Either language construct `print` or `echo` should be used.', + [ + new CodeSample(" 'print']), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run after EchoTagSyntaxFixer. + */ + public function getPriority(): int + { + return -10; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound($this->candidateTokenType); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $callBack = $this->callBack; + foreach ($tokens as $index => $token) { + if ($token->isGivenKind($this->candidateTokenType)) { + $this->{$callBack}($tokens, $index); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('use', 'The desired language construct.')) + ->setAllowedValues(['print', 'echo']) + ->setDefault('echo') + ->getOption(), + ]); + } + + private function fixEchoToPrint(Tokens $tokens, int $index): void + { + $nextTokenIndex = $tokens->getNextMeaningfulToken($index); + $endTokenIndex = $tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]); + $canBeConverted = true; + + for ($i = $nextTokenIndex; $i < $endTokenIndex; ++$i) { + if ($tokens[$i]->equalsAny(['(', [CT::T_ARRAY_SQUARE_BRACE_OPEN]])) { + $blockType = Tokens::detectBlockType($tokens[$i]); + $i = $tokens->findBlockEnd($blockType['type'], $i); + } + + if ($tokens[$i]->equals(',')) { + $canBeConverted = false; + + break; + } + } + + if (false === $canBeConverted) { + return; + } + + $tokens[$index] = new Token([T_PRINT, 'print']); + } + + private function fixPrintToEcho(Tokens $tokens, int $index): void + { + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + + if (!$prevToken->equalsAny([';', '{', '}', ')', [T_OPEN_TAG], [T_ELSE]])) { + return; + } + + $tokens[$index] = new Token([T_ECHO, 'echo']); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/PowToExponentiationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/PowToExponentiationFixer.php new file mode 100644 index 00000000..a56385e6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/PowToExponentiationFixer.php @@ -0,0 +1,219 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class PowToExponentiationFixer extends AbstractFunctionReferenceFixer +{ + public function isCandidate(Tokens $tokens): bool + { + // minimal candidate to fix is seven tokens: pow(x,y); + return $tokens->count() > 7 && $tokens->isTokenKindFound(T_STRING); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts `pow` to the `**` operator.', + [ + new CodeSample( + "findPowCalls($tokens); + $argumentsAnalyzer = new ArgumentsAnalyzer(); + $numberOfTokensAdded = 0; + $previousCloseParenthesisIndex = \count($tokens); + + foreach (array_reverse($candidates) as $candidate) { + // if in the previous iteration(s) tokens were added to the collection and this is done within the tokens + // indices of the current candidate than the index of the close ')' of the candidate has moved and so + // the index needs to be updated + if ($previousCloseParenthesisIndex < $candidate[2]) { + $previousCloseParenthesisIndex = $candidate[2]; + $candidate[2] += $numberOfTokensAdded; + } else { + $previousCloseParenthesisIndex = $candidate[2]; + $numberOfTokensAdded = 0; + } + + $arguments = $argumentsAnalyzer->getArguments($tokens, $candidate[1], $candidate[2]); + + if (2 !== \count($arguments)) { + continue; + } + + for ($i = $candidate[1]; $i < $candidate[2]; ++$i) { + if ($tokens[$i]->isGivenKind(T_ELLIPSIS)) { + continue 2; + } + } + + $numberOfTokensAdded += $this->fixPowToExponentiation( + $tokens, + $candidate[0], // functionNameIndex, + $candidate[1], // openParenthesisIndex, + $candidate[2], // closeParenthesisIndex, + $arguments + ); + } + } + + /** + * @return array + */ + private function findPowCalls(Tokens $tokens): array + { + $candidates = []; + + // Minimal candidate to fix is seven tokens: pow(x,y); + $end = \count($tokens) - 6; + + // First possible location is after the open token: 1 + for ($i = 1; $i < $end; ++$i) { + $candidate = $this->find('pow', $tokens, $i, $end); + + if (null === $candidate) { + break; + } + + $i = $candidate[1]; // proceed to openParenthesisIndex + $candidates[] = $candidate; + } + + return $candidates; + } + + /** + * @param array $arguments + * + * @return int number of tokens added to the collection + */ + private function fixPowToExponentiation(Tokens $tokens, int $functionNameIndex, int $openParenthesisIndex, int $closeParenthesisIndex, array $arguments): int + { + // find the argument separator ',' directly after the last token of the first argument; + // replace it with T_POW '**' + $tokens[$tokens->getNextTokenOfKind(reset($arguments), [','])] = new Token([T_POW, '**']); + + // clean up the function call tokens prt. I + $tokens->clearAt($closeParenthesisIndex); + $previousIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex); + + if ($tokens[$previousIndex]->equals(',')) { + $tokens->clearAt($previousIndex); // trailing ',' in function call (PHP 7.3) + } + + $added = 0; + + // check if the arguments need to be wrapped in parentheses + foreach (array_reverse($arguments, true) as $argumentStartIndex => $argumentEndIndex) { + if ($this->isParenthesisNeeded($tokens, $argumentStartIndex, $argumentEndIndex)) { + $tokens->insertAt($argumentEndIndex + 1, new Token(')')); + $tokens->insertAt($argumentStartIndex, new Token('(')); + $added += 2; + } + } + + // clean up the function call tokens prt. II + $tokens->clearAt($openParenthesisIndex); + $tokens->clearAt($functionNameIndex); + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($functionNameIndex); + + if ($tokens[$prevMeaningfulTokenIndex]->isGivenKind(T_NS_SEPARATOR)) { + $tokens->clearAt($prevMeaningfulTokenIndex); + } + + return $added; + } + + private function isParenthesisNeeded(Tokens $tokens, int $argumentStartIndex, int $argumentEndIndex): bool + { + static $allowedKinds = null; + + if (null === $allowedKinds) { + $allowedKinds = $this->getAllowedKinds(); + } + + for ($i = $argumentStartIndex; $i <= $argumentEndIndex; ++$i) { + if ($tokens[$i]->isGivenKind($allowedKinds) || $tokens->isEmptyAt($i)) { + continue; + } + + $blockType = Tokens::detectBlockType($tokens[$i]); + + if (null !== $blockType) { + $i = $tokens->findBlockEnd($blockType['type'], $i); + + continue; + } + + if ($tokens[$i]->equals('$')) { + $i = $tokens->getNextMeaningfulToken($i); + if ($tokens[$i]->isGivenKind(CT::T_DYNAMIC_VAR_BRACE_OPEN)) { + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE, $i); + + continue; + } + } + + if ($tokens[$i]->equals('+') && $tokens->getPrevMeaningfulToken($i) < $argumentStartIndex) { + continue; + } + + return true; + } + + return false; + } + + /** + * @return int[] + */ + private function getAllowedKinds(): array + { + return [ + T_DNUMBER, T_LNUMBER, T_VARIABLE, T_STRING, T_CONSTANT_ENCAPSED_STRING, T_DOUBLE_CAST, + T_INT_CAST, T_INC, T_DEC, T_NS_SEPARATOR, T_WHITESPACE, T_DOUBLE_COLON, T_LINE, T_COMMENT, T_DOC_COMMENT, + CT::T_NAMESPACE_OPERATOR, + ...Token::getObjectOperatorKinds(), + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/RandomApiMigrationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/RandomApiMigrationFixer.php new file mode 100644 index 00000000..c65f6932 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/RandomApiMigrationFixer.php @@ -0,0 +1,158 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @author Vladimir Reznichenko + */ +final class RandomApiMigrationFixer extends AbstractFunctionReferenceFixer implements ConfigurableFixerInterface +{ + /** + * @var array> + */ + private static array $argumentCounts = [ + 'getrandmax' => [0], + 'mt_rand' => [1, 2], + 'rand' => [0, 2], + 'srand' => [0, 1], + 'random_int' => [0, 2], + ]; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + foreach ($this->configuration['replacements'] as $functionName => $replacement) { + $this->configuration['replacements'][$functionName] = [ + 'alternativeName' => $replacement, + 'argumentCount' => self::$argumentCounts[$functionName], + ]; + } + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replaces `rand`, `srand`, `getrandmax` functions calls with their `mt_*` analogs or `random_int`.', + [ + new CodeSample(" ['getrandmax' => 'mt_getrandmax']] + ), + new CodeSample( + " ['rand' => 'random_int']] + ), + ], + null, + 'Risky when the configured functions are overridden. Or when relying on the seed based generating of the numbers.' + ); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + foreach ($this->configuration['replacements'] as $functionIdentity => $functionReplacement) { + if ($functionIdentity === $functionReplacement['alternativeName']) { + continue; + } + + $currIndex = 0; + + do { + // try getting function reference and translate boundaries for humans + $boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1); + + if (null === $boundaries) { + // next function search, as current one not found + continue 2; + } + + [$functionName, $openParenthesis, $closeParenthesis] = $boundaries; + $count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis); + + if (!\in_array($count, $functionReplacement['argumentCount'], true)) { + continue 2; + } + + // analysing cursor shift, so nested calls could be processed + $currIndex = $openParenthesis; + $tokens[$functionName] = new Token([T_STRING, $functionReplacement['alternativeName']]); + + if (0 === $count && 'random_int' === $functionReplacement['alternativeName']) { + $tokens->insertAt($currIndex + 1, [ + new Token([T_LNUMBER, '0']), + new Token(','), + new Token([T_WHITESPACE, ' ']), + new Token([T_STRING, 'getrandmax']), + new Token('('), + new Token(')'), + ]); + + $currIndex += 6; + } + } while (null !== $currIndex); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('replacements', 'Mapping between replaced functions with the new ones.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([static function (array $value): bool { + foreach ($value as $functionName => $replacement) { + if (!\array_key_exists($functionName, self::$argumentCounts)) { + throw new InvalidOptionsException(sprintf( + 'Function "%s" is not handled by the fixer.', + $functionName + )); + } + + if (!\is_string($replacement)) { + throw new InvalidOptionsException(sprintf( + 'Replacement for function "%s" must be a string, "%s" given.', + $functionName, + get_debug_type($replacement) + )); + } + } + + return true; + }]) + ->setDefault([ + 'getrandmax' => 'mt_getrandmax', + 'rand' => 'mt_rand', // @TODO change to `random_int` as default on 4.0 + 'srand' => 'mt_srand', + ]) + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/SetTypeToCastFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/SetTypeToCastFixer.php new file mode 100644 index 00000000..2c807eb5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/SetTypeToCastFixer.php @@ -0,0 +1,240 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class SetTypeToCastFixer extends AbstractFunctionReferenceFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Cast shall be used, not `settype`.', + [ + new CodeSample( + 'isAllTokenKindsFound([T_CONSTANT_ENCAPSED_STRING, T_STRING, T_VARIABLE]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $map = [ + 'array' => [T_ARRAY_CAST, '(array)'], + 'bool' => [T_BOOL_CAST, '(bool)'], + 'boolean' => [T_BOOL_CAST, '(bool)'], + 'double' => [T_DOUBLE_CAST, '(float)'], + 'float' => [T_DOUBLE_CAST, '(float)'], + 'int' => [T_INT_CAST, '(int)'], + 'integer' => [T_INT_CAST, '(int)'], + 'object' => [T_OBJECT_CAST, '(object)'], + 'string' => [T_STRING_CAST, '(string)'], + // note: `'null' is dealt with later on + ]; + + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + foreach (array_reverse($this->findSettypeCalls($tokens)) as $candidate) { + $functionNameIndex = $candidate[0]; + + $arguments = $argumentsAnalyzer->getArguments($tokens, $candidate[1], $candidate[2]); + if (2 !== \count($arguments)) { + continue; // function must be overridden or used incorrectly + } + + $prev = $tokens->getPrevMeaningfulToken($functionNameIndex); + + if (!$tokens[$prev]->equalsAny([';', '{', '}', [T_OPEN_TAG]])) { + continue; // return value of the function is used + } + + reset($arguments); + + // --- Test first argument -------------------- + + $firstArgumentStart = key($arguments); + if ($tokens[$firstArgumentStart]->isComment() || $tokens[$firstArgumentStart]->isWhitespace()) { + $firstArgumentStart = $tokens->getNextMeaningfulToken($firstArgumentStart); + } + + if (!$tokens[$firstArgumentStart]->isGivenKind(T_VARIABLE)) { + continue; // settype only works with variables pass by reference, function must be overridden + } + + $commaIndex = $tokens->getNextMeaningfulToken($firstArgumentStart); + + if (null === $commaIndex || !$tokens[$commaIndex]->equals(',')) { + continue; // first argument is complex statement; function must be overridden + } + + // --- Test second argument ------------------- + + next($arguments); + $secondArgumentStart = key($arguments); + $secondArgumentEnd = $arguments[$secondArgumentStart]; + + if ($tokens[$secondArgumentStart]->isComment() || $tokens[$secondArgumentStart]->isWhitespace()) { + $secondArgumentStart = $tokens->getNextMeaningfulToken($secondArgumentStart); + } + + if ( + !$tokens[$secondArgumentStart]->isGivenKind(T_CONSTANT_ENCAPSED_STRING) + || $tokens->getNextMeaningfulToken($secondArgumentStart) < $secondArgumentEnd + ) { + continue; // second argument is of the wrong type or is a (complex) statement of some sort (function is overridden) + } + + // --- Test type ------------------------------ + + $type = strtolower(trim($tokens[$secondArgumentStart]->getContent(), '"\'"')); + + if ('null' !== $type && !isset($map[$type])) { + continue; // we don't know how to map + } + + // --- Fixing --------------------------------- + + $argumentToken = $tokens[$firstArgumentStart]; + + $this->removeSettypeCall( + $tokens, + $functionNameIndex, + $candidate[1], + $firstArgumentStart, + $commaIndex, + $secondArgumentStart, + $candidate[2] + ); + + if ('null' === $type) { + $this->fixSettypeNullCall($tokens, $functionNameIndex, $argumentToken); + } else { + $this->fixSettypeCall($tokens, $functionNameIndex, $argumentToken, new Token($map[$type])); + } + } + } + + /** + * @return list> + */ + private function findSettypeCalls(Tokens $tokens): array + { + $candidates = []; + + $end = \count($tokens); + for ($i = 1; $i < $end; ++$i) { + $candidate = $this->find('settype', $tokens, $i, $end); + if (null === $candidate) { + break; + } + + $i = $candidate[1]; // proceed to openParenthesisIndex + $candidates[] = $candidate; + } + + return $candidates; + } + + private function removeSettypeCall( + Tokens $tokens, + int $functionNameIndex, + int $openParenthesisIndex, + int $firstArgumentStart, + int $commaIndex, + int $secondArgumentStart, + int $closeParenthesisIndex + ): void { + $tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesisIndex); + $prevIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex); + if ($tokens[$prevIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + } + $tokens->clearTokenAndMergeSurroundingWhitespace($secondArgumentStart); + $tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($firstArgumentStart); + $tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesisIndex); + $tokens->clearAt($functionNameIndex); // we'll be inserting here so no need to merge the space tokens + $tokens->clearEmptyTokens(); + } + + private function fixSettypeCall( + Tokens $tokens, + int $functionNameIndex, + Token $argumentToken, + Token $castToken + ): void { + $tokens->insertAt( + $functionNameIndex, + [ + clone $argumentToken, + new Token([T_WHITESPACE, ' ']), + new Token('='), + new Token([T_WHITESPACE, ' ']), + $castToken, + new Token([T_WHITESPACE, ' ']), + clone $argumentToken, + ] + ); + + $tokens->removeTrailingWhitespace($functionNameIndex + 6); // 6 = number of inserted tokens -1 for offset correction + } + + private function fixSettypeNullCall( + Tokens $tokens, + int $functionNameIndex, + Token $argumentToken + ): void { + $tokens->insertAt( + $functionNameIndex, + [ + clone $argumentToken, + new Token([T_WHITESPACE, ' ']), + new Token('='), + new Token([T_WHITESPACE, ' ']), + new Token([T_STRING, 'null']), + ] + ); + + $tokens->removeTrailingWhitespace($functionNameIndex + 4); // 4 = number of inserted tokens -1 for offset correction + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ArraySyntaxFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ArraySyntaxFixer.php new file mode 100644 index 00000000..a7b0b20f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ArraySyntaxFixer.php @@ -0,0 +1,136 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Gregor Harlan + * @author Sebastiaan Stok + * @author Dariusz Rumiński + */ +final class ArraySyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var null|int + */ + private $candidateTokenKind; + + /** + * @var null|string + */ + private $fixCallback; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->resolveCandidateTokenKind(); + $this->resolveFixCallback(); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHP arrays should be declared using the configured syntax.', + [ + new CodeSample( + " 'long'] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer, SingleSpaceAfterConstructFixer, SingleSpaceAroundConstructFixer, TernaryOperatorSpacesFixer. + */ + public function getPriority(): int + { + return 37; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound($this->candidateTokenKind); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $callback = $this->fixCallback; + + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + if ($tokens[$index]->isGivenKind($this->candidateTokenKind)) { + $this->{$callback}($tokens, $index); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('syntax', 'Whether to use the `long` or `short` array syntax.')) + ->setAllowedValues(['long', 'short']) + ->setDefault('short') + ->getOption(), + ]); + } + + private function fixToLongArraySyntax(Tokens $tokens, int $index): void + { + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); + + $tokens[$index] = new Token('('); + $tokens[$closeIndex] = new Token(')'); + + $tokens->insertAt($index, new Token([T_ARRAY, 'array'])); + } + + private function fixToShortArraySyntax(Tokens $tokens, int $index): void + { + $openIndex = $tokens->getNextTokenOfKind($index, ['(']); + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); + + $tokens[$openIndex] = new Token([CT::T_ARRAY_SQUARE_BRACE_OPEN, '[']); + $tokens[$closeIndex] = new Token([CT::T_ARRAY_SQUARE_BRACE_CLOSE, ']']); + + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + + private function resolveFixCallback(): void + { + $this->fixCallback = sprintf('fixTo%sArraySyntax', ucfirst($this->configuration['syntax'])); + } + + private function resolveCandidateTokenKind(): void + { + $this->candidateTokenKind = 'long' === $this->configuration['syntax'] ? CT::T_ARRAY_SQUARE_BRACE_OPEN : T_ARRAY; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php new file mode 100644 index 00000000..b7a888f0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php @@ -0,0 +1,80 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Carlos Cirello + * @author Dariusz Rumiński + * @author Graham Campbell + */ +final class NoMultilineWhitespaceAroundDoubleArrowFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Operator `=>` should not be surrounded by multi-line whitespaces.', + [new CodeSample(" 2);\n")] + ); + } + + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer, MethodArgumentSpaceFixer. + */ + public function getPriority(): int + { + return 31; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOUBLE_ARROW); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOUBLE_ARROW)) { + continue; + } + + if (!$tokens[$index - 2]->isComment() || str_starts_with($tokens[$index - 2]->getContent(), '/*')) { + $this->fixWhitespace($tokens, $index - 1); + } + + // do not move anything about if there is a comment following the whitespace + if (!$tokens[$index + 2]->isComment()) { + $this->fixWhitespace($tokens, $index + 1); + } + } + } + + private function fixWhitespace(Tokens $tokens, int $index): void + { + $token = $tokens[$index]; + + if ($token->isWhitespace() && !$token->isWhitespace(" \t")) { + $tokens[$index] = new Token([T_WHITESPACE, rtrim($token->getContent()).' ']); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php new file mode 100644 index 00000000..6d133841 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php @@ -0,0 +1,52 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\Basic\NoTrailingCommaInSinglelineFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @deprecated + * + * @author Dariusz Rumiński + * @author Sebastiaan Stok + */ +final class NoTrailingCommaInSinglelineArrayFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHP single-line arrays should not have trailing comma.', + [new CodeSample("proxyFixers); + } + + protected function createProxyFixers(): array + { + $fixer = new NoTrailingCommaInSinglelineFixer(); + $fixer->configure(['elements' => ['array']]); + + return [$fixer]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php new file mode 100644 index 00000000..f2ff389d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php @@ -0,0 +1,140 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Adam Marczuk + */ +final class NoWhitespaceBeforeCommaInArrayFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'In array declaration, there MUST NOT be a whitespace before each comma.', + [ + new CodeSample(" true] + ), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { + $this->fixSpacing($index, $tokens); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('after_heredoc', 'Whether the whitespace between heredoc end and comma should be removed.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * Method to fix spacing in array declaration. + */ + private function fixSpacing(int $index, Tokens $tokens): void + { + if ($tokens[$index]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { + $startIndex = $index; + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex); + } else { + $startIndex = $tokens->getNextTokenOfKind($index, ['(']); + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); + } + + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + $i = $this->skipNonArrayElements($i, $tokens); + $currentToken = $tokens[$i]; + $prevIndex = $tokens->getPrevNonWhitespace($i - 1); + + if ( + $currentToken->equals(',') && !$tokens[$prevIndex]->isComment() + && (true === $this->configuration['after_heredoc'] || !$tokens[$prevIndex]->isGivenKind(T_END_HEREDOC)) + ) { + $tokens->removeLeadingWhitespace($i); + } + } + } + + /** + * Method to move index over the non-array elements like function calls or function declarations. + */ + private function skipNonArrayElements(int $index, Tokens $tokens): int + { + if ($tokens[$index]->equals('}')) { + return $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + } + + if ($tokens[$index]->equals(')')) { + $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $startIndex = $tokens->getPrevMeaningfulToken($startIndex); + if (!$tokens[$startIndex]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { + return $startIndex; + } + } + + if ($tokens[$index]->equals(',') && $this->commaIsPartOfImplementsList($index, $tokens)) { + --$index; + } + + return $index; + } + + private function commaIsPartOfImplementsList(int $index, Tokens $tokens): bool + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + + $current = $tokens[$index]; + } while ($current->isGivenKind(T_STRING) || $current->equals(',')); + + return $current->isGivenKind(T_IMPLEMENTS); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php new file mode 100644 index 00000000..f7e2b060 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php @@ -0,0 +1,53 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class NormalizeIndexBraceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Array index should always be written by using square braces.', + [new CodeSample("isTokenKindFound(CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN)) { + $tokens[$index] = new Token('['); + } elseif ($token->isGivenKind(CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE)) { + $tokens[$index] = new Token(']'); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ReturnToYieldFromFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ReturnToYieldFromFixer.php new file mode 100644 index 00000000..4b130a27 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ReturnToYieldFromFixer.php @@ -0,0 +1,105 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + */ +final class ReturnToYieldFromFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'If the function explicitly returns an array, and has the return type `iterable`, then `yield from` must be used instead of `return`.', + [new CodeSample('isAllTokenKindsFound([T_FUNCTION, T_RETURN]) && $tokens->isAnyTokenKindsFound([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]); + } + + /** + * {@inheritdoc} + * + * Must run before YieldFromArrayToYieldsFixer. + * Must run after PhpUnitDataProviderReturnTypeFixer, PhpdocToReturnTypeFixer. + */ + public function getPriority(): int + { + return 1; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens->findGivenKind(T_RETURN) as $index => $token) { + if (!$this->shouldBeFixed($tokens, $index)) { + continue; + } + + $tokens[$index] = new Token([T_YIELD_FROM, 'yield from']); + } + } + + private function shouldBeFixed(Tokens $tokens, int $returnIndex): bool + { + $arrayStartIndex = $tokens->getNextMeaningfulToken($returnIndex); + if (!$tokens[$arrayStartIndex]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { + return false; + } + + if ($tokens[$arrayStartIndex]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { + $arrayEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $arrayStartIndex); + } else { + $arrayOpenParenthesisIndex = $tokens->getNextTokenOfKind($arrayStartIndex, ['(']); + $arrayEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $arrayOpenParenthesisIndex); + } + + $functionEndIndex = $arrayEndIndex; + do { + $functionEndIndex = $tokens->getNextMeaningfulToken($functionEndIndex); + } while (null !== $functionEndIndex && $tokens[$functionEndIndex]->equals(';')); + if (null === $functionEndIndex || !$tokens[$functionEndIndex]->equals('}')) { + return false; + } + + $functionStartIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $functionEndIndex); + + $returnTypeIndex = $tokens->getPrevMeaningfulToken($functionStartIndex); + if (!$tokens[$returnTypeIndex]->isGivenKind(T_STRING)) { + return false; + } + + if ('iterable' !== strtolower($tokens[$returnTypeIndex]->getContent())) { + return false; + } + + $beforeReturnTypeIndex = $tokens->getPrevMeaningfulToken($returnTypeIndex); + + return $tokens[$beforeReturnTypeIndex]->isGivenKind(CT::T_TYPE_COLON); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/TrimArraySpacesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/TrimArraySpacesFixer.php new file mode 100644 index 00000000..775e9125 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/TrimArraySpacesFixer.php @@ -0,0 +1,97 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Jared Henderson + */ +final class TrimArraySpacesFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Arrays should be formatted like function/method arguments, without leading or trailing single line space.', + [new CodeSample("isAnyTokenKindsFound([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = 0, $c = $tokens->count(); $index < $c; ++$index) { + if ($tokens[$index]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN])) { + self::fixArray($tokens, $index); + } + } + } + + /** + * Method to trim leading/trailing whitespace within single line arrays. + */ + private static function fixArray(Tokens $tokens, int $index): void + { + $startIndex = $index; + + if ($tokens[$startIndex]->isGivenKind(T_ARRAY)) { + $startIndex = $tokens->getNextMeaningfulToken($startIndex); + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); + } elseif ($tokens[$startIndex]->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN)) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE, $startIndex); + } else { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex); + } + + $nextIndex = $startIndex + 1; + $nextToken = $tokens[$nextIndex]; + $nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($startIndex); + $nextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex]; + $tokenAfterNextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex + 1]; + + $prevIndex = $endIndex - 1; + $prevToken = $tokens[$prevIndex]; + $prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($endIndex); + $prevNonWhitespaceToken = $tokens[$prevNonWhitespaceIndex]; + + if ( + $nextToken->isWhitespace(" \t") + && ( + !$nextNonWhitespaceToken->isComment() + || $nextNonWhitespaceIndex === $prevNonWhitespaceIndex + || $tokenAfterNextNonWhitespaceToken->isWhitespace(" \t") + || str_starts_with($nextNonWhitespaceToken->getContent(), '/*') + ) + ) { + $tokens->clearAt($nextIndex); + } + + if ( + $prevToken->isWhitespace(" \t") + && !$prevNonWhitespaceToken->equals(',') + ) { + $tokens->clearAt($prevIndex); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php new file mode 100644 index 00000000..a9c7d051 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php @@ -0,0 +1,137 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Adam Marczuk + */ +final class WhitespaceAfterCommaInArrayFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'In array declaration, there MUST be a whitespace after each comma.', + [ + new CodeSample(" true]), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('ensure_single_space', 'If there are only horizontal whitespaces after the comma then ensure it is a single space.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensToInsert = []; + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (!$tokens[$index]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { + continue; + } + + if ($tokens[$index]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { + $startIndex = $index; + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex); + } else { + $startIndex = $tokens->getNextTokenOfKind($index, ['(']); + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); + } + + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + $i = $this->skipNonArrayElements($i, $tokens); + if (!$tokens[$i]->equals(',')) { + continue; + } + if (!$tokens[$i + 1]->isWhitespace()) { + $tokensToInsert[$i + 1] = new Token([T_WHITESPACE, ' ']); + } elseif ( + $this->configuration['ensure_single_space'] + && ' ' !== $tokens[$i + 1]->getContent() + && Preg::match('/^\h+$/', $tokens[$i + 1]->getContent()) + && (!$tokens[$i + 2]->isComment() || Preg::match('/^\h+$/', $tokens[$i + 3]->getContent())) + ) { + $tokens[$i + 1] = new Token([T_WHITESPACE, ' ']); + } + } + } + + if ([] !== $tokensToInsert) { + $tokens->insertSlices($tokensToInsert); + } + } + + /** + * Method to move index over the non-array elements like function calls or function declarations. + * + * @return int New index + */ + private function skipNonArrayElements(int $index, Tokens $tokens): int + { + if ($tokens[$index]->equals('}')) { + return $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + } + + if ($tokens[$index]->equals(')')) { + $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $startIndex = $tokens->getPrevMeaningfulToken($startIndex); + if (!$tokens[$startIndex]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { + return $startIndex; + } + } + + if ($tokens[$index]->equals(',') && $this->commaIsPartOfImplementsList($index, $tokens)) { + --$index; + } + + return $index; + } + + private function commaIsPartOfImplementsList(int $index, Tokens $tokens): bool + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + + $current = $tokens[$index]; + } while ($current->isGivenKind(T_STRING) || $current->equals(',')); + + return $current->isGivenKind(T_IMPLEMENTS); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/YieldFromArrayToYieldsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/YieldFromArrayToYieldsFixer.php new file mode 100644 index 00000000..7df614fc --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/YieldFromArrayToYieldsFixer.php @@ -0,0 +1,189 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + */ +final class YieldFromArrayToYieldsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Yield from array must be unpacked to series of yields.', + [ + new CodeSample('isTokenKindFound(T_YIELD_FROM); + } + + /** + * {@inheritdoc} + * + * Must run before BlankLineBeforeStatementFixer, NoExtraBlankLinesFixer, NoMultipleStatementsPerLineFixer, NoWhitespaceInBlankLineFixer, StatementIndentationFixer. + * Must run after ReturnToYieldFromFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + /** + * @var array $inserts + */ + $inserts = []; + + foreach ($this->getYieldsFromToUnpack($tokens) as $index => [$startIndex, $endIndex]) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + if ($tokens[$startIndex]->equals('(')) { + $prevStartIndex = $tokens->getPrevMeaningfulToken($startIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($prevStartIndex); // clear `array` from `array(` + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($startIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($endIndex); + + $arrayHasTrailingComma = false; + + $startIndex = $tokens->getNextMeaningfulToken($startIndex); + + $inserts[$startIndex] = [new Token([T_YIELD, 'yield']), new Token([T_WHITESPACE, ' '])]; + + foreach ($this->findArrayItemCommaIndex( + $tokens, + $startIndex, + $tokens->getPrevMeaningfulToken($endIndex), + ) as $commaIndex) { + $nextItemIndex = $tokens->getNextMeaningfulToken($commaIndex); + + if ($nextItemIndex < $endIndex) { + $inserts[$nextItemIndex] = [new Token([T_YIELD, 'yield']), new Token([T_WHITESPACE, ' '])]; + $tokens[$commaIndex] = new Token(';'); + } else { + $arrayHasTrailingComma = true; + // array has trailing comma - we replace it with `;` (as it's best fit to put it) + $tokens[$commaIndex] = new Token(';'); + } + } + + // there was a trailing comma, so we do not need original `;` after initial array structure + if (true === $arrayHasTrailingComma) { + $tokens->clearTokenAndMergeSurroundingWhitespace($tokens->getNextMeaningfulToken($endIndex)); + } + } + + $tokens->insertSlices($inserts); + } + + /** + * @return iterable> + */ + private function getYieldsFromToUnpack(Tokens $tokens): iterable + { + $tokensCount = $tokens->count(); + $index = 0; + while (++$index < $tokensCount) { + if (!$tokens[$index]->isGivenKind(T_YIELD_FROM)) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->equalsAny([';', '{', '}', [T_OPEN_TAG]])) { + continue; + } + + $arrayStartIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$arrayStartIndex]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { + continue; + } + + if ($tokens[$arrayStartIndex]->isGivenKind(T_ARRAY)) { + $startIndex = $tokens->getNextTokenOfKind($arrayStartIndex, ['(']); + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); + } else { + $startIndex = $arrayStartIndex; + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex); + } + + // is there empty "yield from []" ? + if ($endIndex === $tokens->getNextMeaningfulToken($startIndex)) { + continue; + } + + // is there any nested "yield from"? + if ([] !== $tokens->findGivenKind(T_YIELD_FROM, $startIndex, $endIndex)) { + continue; + } + + yield $index => [$startIndex, $endIndex]; + } + } + + /** + * @return iterable + */ + private function findArrayItemCommaIndex(Tokens $tokens, int $startIndex, int $endIndex): iterable + { + for ($index = $startIndex; $index <= $endIndex; ++$index) { + $token = $tokens[$index]; + + // skip nested (), [], {} constructs + $blockDefinitionProbe = Tokens::detectBlockType($token); + + if (null !== $blockDefinitionProbe && true === $blockDefinitionProbe['isStart']) { + $index = $tokens->findBlockEnd($blockDefinitionProbe['type'], $index); + + continue; + } + + if (!$tokens[$index]->equals(',')) { + continue; + } + + yield $index; + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/AttributeNotation/AttributeEmptyParenthesesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/AttributeNotation/AttributeEmptyParenthesesFixer.php new file mode 100644 index 00000000..cba06046 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/AttributeNotation/AttributeEmptyParenthesesFixer.php @@ -0,0 +1,123 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\AttributeNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author HypeMC + */ +final class AttributeEmptyParenthesesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHP attributes declared without arguments must (not) be followed by empty parentheses.', + [ + new CodeSample(" true] + ), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return \defined('T_ATTRIBUTE') && $tokens->isTokenKindFound(T_ATTRIBUTE); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('use_parentheses', 'Whether attributes should be followed by parentheses or not.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $index = 0; + + while (null !== $index = $tokens->getNextTokenOfKind($index, [[T_ATTRIBUTE]])) { + $nextIndex = $index; + + do { + $parenthesesIndex = $tokens->getNextTokenOfKind($nextIndex, ['(', ',', [CT::T_ATTRIBUTE_CLOSE]]); + + if (true === $this->configuration['use_parentheses']) { + $this->ensureParenthesesAt($tokens, $parenthesesIndex); + } else { + $this->ensureNoParenthesesAt($tokens, $parenthesesIndex); + } + + $nextIndex = $tokens->getNextTokenOfKind($nextIndex, ['(', ',', [CT::T_ATTRIBUTE_CLOSE]]); + + // Find closing parentheses, we need to do this in case there's a comma inside the parentheses + if ($tokens[$nextIndex]->equals('(')) { + $nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex); + $nextIndex = $tokens->getNextTokenOfKind($nextIndex, [',', [CT::T_ATTRIBUTE_CLOSE]]); + } + + // In case there's a comma right before T_ATTRIBUTE_CLOSE + if (!$tokens[$nextIndex]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + } + } while (!$tokens[$nextIndex]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)); + } + } + + private function ensureParenthesesAt(Tokens $tokens, int $index): void + { + if ($tokens[$index]->equals('(')) { + return; + } + + $tokens->insertAt( + $tokens->getPrevMeaningfulToken($index) + 1, + [new Token('('), new Token(')')] + ); + } + + private function ensureNoParenthesesAt(Tokens $tokens, int $index): void + { + if (!$tokens[$index]->equals('(')) { + return; + } + + $closingIndex = $tokens->getNextMeaningfulToken($index); + + // attribute has arguments - parentheses can not be removed + if (!$tokens[$closingIndex]->equals(')')) { + return; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($closingIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesFixer.php new file mode 100644 index 00000000..a5b3916b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesFixer.php @@ -0,0 +1,252 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ControlStructure\ControlStructureBracesFixer; +use PhpCsFixer\Fixer\ControlStructure\ControlStructureContinuationPositionFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\LanguageConstruct\DeclareParenthesesFixer; +use PhpCsFixer\Fixer\LanguageConstruct\SingleSpaceAroundConstructFixer; +use PhpCsFixer\Fixer\Whitespace\NoExtraBlankLinesFixer; +use PhpCsFixer\Fixer\Whitespace\StatementIndentationFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * Fixer for rules defined in PSR2 ¶4.1, ¶4.4, ¶5. + * + * @author Dariusz Rumiński + * + * @deprecated + */ +final class BracesFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface, DeprecatedFixerInterface +{ + /** + * @internal + */ + public const LINE_NEXT = 'next'; + + /** + * @internal + */ + public const LINE_SAME = 'same'; + + /** + * @var null|CurlyBracesPositionFixer + */ + private $curlyBracesPositionFixer; + + /** + * @var null|ControlStructureContinuationPositionFixer + */ + private $controlStructureContinuationPositionFixer; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The body of each structure MUST be enclosed by braces. Braces should be properly placed. Body of braces should be properly indented.', + [ + new CodeSample( + '= 0; }; +$negative = function ($item) { + return $item < 0; }; +', + ['allow_single_line_closure' => true] + ), + new CodeSample( + ' self::LINE_SAME] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before HeredocIndentationFixer. + * Must run after ClassAttributesSeparationFixer, ClassDefinitionFixer, EmptyLoopBodyFixer, NoAlternativeSyntaxFixer, NoEmptyStatementFixer, NoUselessElseFixer, SingleLineThrowFixer, SingleSpaceAfterConstructFixer, SingleSpaceAroundConstructFixer, SingleTraitInsertPerStatementFixer. + */ + public function getPriority(): int + { + return 35; + } + + public function getSuccessorsNames(): array + { + return array_keys($this->proxyFixers); + } + + public function configure(array $configuration = null): void + { + parent::configure($configuration); + + $this->getCurlyBracesPositionFixer()->configure([ + 'control_structures_opening_brace' => $this->translatePositionOption($this->configuration['position_after_control_structures']), + 'functions_opening_brace' => $this->translatePositionOption($this->configuration['position_after_functions_and_oop_constructs']), + 'anonymous_functions_opening_brace' => $this->translatePositionOption($this->configuration['position_after_anonymous_constructs']), + 'classes_opening_brace' => $this->translatePositionOption($this->configuration['position_after_functions_and_oop_constructs']), + 'anonymous_classes_opening_brace' => $this->translatePositionOption($this->configuration['position_after_anonymous_constructs']), + 'allow_single_line_empty_anonymous_classes' => $this->configuration['allow_single_line_anonymous_class_with_empty_body'], + 'allow_single_line_anonymous_functions' => $this->configuration['allow_single_line_closure'], + ]); + + $this->getControlStructureContinuationPositionFixer()->configure([ + 'position' => self::LINE_NEXT === $this->configuration['position_after_control_structures'] + ? ControlStructureContinuationPositionFixer::NEXT_LINE + : ControlStructureContinuationPositionFixer::SAME_LINE, + ]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('allow_single_line_anonymous_class_with_empty_body', 'Whether single line anonymous class with empty body notation should be allowed.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('allow_single_line_closure', 'Whether single line lambda notation should be allowed.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('position_after_functions_and_oop_constructs', 'Whether the opening brace should be placed on "next" or "same" line after classy constructs (non-anonymous classes, interfaces, traits, methods and non-lambda functions).')) + ->setAllowedValues([self::LINE_NEXT, self::LINE_SAME]) + ->setDefault(self::LINE_NEXT) + ->getOption(), + (new FixerOptionBuilder('position_after_control_structures', 'Whether the opening brace should be placed on "next" or "same" line after control structures.')) + ->setAllowedValues([self::LINE_NEXT, self::LINE_SAME]) + ->setDefault(self::LINE_SAME) + ->getOption(), + (new FixerOptionBuilder('position_after_anonymous_constructs', 'Whether the opening brace should be placed on "next" or "same" line after anonymous constructs (anonymous classes and lambda functions).')) + ->setAllowedValues([self::LINE_NEXT, self::LINE_SAME]) + ->setDefault(self::LINE_SAME) + ->getOption(), + ]); + } + + protected function createProxyFixers(): array + { + $singleSpaceAroundConstructFixer = new SingleSpaceAroundConstructFixer(); + $singleSpaceAroundConstructFixer->configure([ + 'constructs_contain_a_single_space' => [], + 'constructs_followed_by_a_single_space' => ['elseif', 'for', 'foreach', 'if', 'match', 'while', 'use_lambda'], + 'constructs_preceded_by_a_single_space' => ['use_lambda'], + ]); + + $noExtraBlankLinesFixer = new NoExtraBlankLinesFixer(); + $noExtraBlankLinesFixer->configure([ + 'tokens' => ['curly_brace_block'], + ]); + + return [ + $singleSpaceAroundConstructFixer, + new ControlStructureBracesFixer(), + $noExtraBlankLinesFixer, + $this->getCurlyBracesPositionFixer(), + $this->getControlStructureContinuationPositionFixer(), + new DeclareParenthesesFixer(), + new NoMultipleStatementsPerLineFixer(), + new StatementIndentationFixer(true), + ]; + } + + private function getCurlyBracesPositionFixer(): CurlyBracesPositionFixer + { + if (null === $this->curlyBracesPositionFixer) { + $this->curlyBracesPositionFixer = new CurlyBracesPositionFixer(); + } + + return $this->curlyBracesPositionFixer; + } + + private function getControlStructureContinuationPositionFixer(): ControlStructureContinuationPositionFixer + { + if (null === $this->controlStructureContinuationPositionFixer) { + $this->controlStructureContinuationPositionFixer = new ControlStructureContinuationPositionFixer(); + } + + return $this->controlStructureContinuationPositionFixer; + } + + private function translatePositionOption(string $option): string + { + return self::LINE_NEXT === $option + ? CurlyBracesPositionFixer::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END + : CurlyBracesPositionFixer::SAME_LINE; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesPositionFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesPositionFixer.php new file mode 100644 index 00000000..4812308a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesPositionFixer.php @@ -0,0 +1,410 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\Indentation; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +final class BracesPositionFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + use Indentation; + + /** + * @internal + */ + public const NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END = 'next_line_unless_newline_at_signature_end'; + + /** + * @internal + */ + public const SAME_LINE = 'same_line'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Braces must be placed as configured.', + [ + new CodeSample( + ' self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END] + ), + new CodeSample( + ' self::SAME_LINE] + ), + new CodeSample( + ' self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END] + ), + new CodeSample( + ' self::SAME_LINE] + ), + new CodeSample( + ' self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END] + ), + new CodeSample( + ' true] + ), + new CodeSample( + ' true] + ), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound('{'); + } + + /** + * {@inheritdoc} + * + * Must run before SingleLineEmptyBodyFixer, StatementIndentationFixer. + * Must run after ControlStructureBracesFixer, NoMultipleStatementsPerLineFixer. + */ + public function getPriority(): int + { + return -2; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $classyTokens = Token::getClassyTokenKinds(); + $controlStructureTokens = [T_DECLARE, T_DO, T_ELSE, T_ELSEIF, T_FINALLY, T_FOR, T_FOREACH, T_IF, T_WHILE, T_TRY, T_CATCH, T_SWITCH]; + // @TODO: drop condition when PHP 8.0+ is required + if (\defined('T_MATCH')) { + $controlStructureTokens[] = T_MATCH; + } + + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $allowSingleLineUntil = null; + + foreach ($tokens as $index => $token) { + $allowSingleLine = false; + $allowSingleLineIfEmpty = false; + + if ($token->isGivenKind($classyTokens)) { + $openBraceIndex = $tokens->getNextTokenOfKind($index, ['{']); + + if ($tokensAnalyzer->isAnonymousClass($index)) { + $allowSingleLineIfEmpty = $this->configuration['allow_single_line_empty_anonymous_classes']; + $positionOption = 'anonymous_classes_opening_brace'; + } else { + $positionOption = 'classes_opening_brace'; + } + } elseif ($token->isGivenKind(T_FUNCTION)) { + $openBraceIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + + if ($tokens[$openBraceIndex]->equals(';')) { + continue; + } + + if ($tokensAnalyzer->isLambda($index)) { + $allowSingleLine = $this->configuration['allow_single_line_anonymous_functions']; + $positionOption = 'anonymous_functions_opening_brace'; + } else { + $positionOption = 'functions_opening_brace'; + } + } elseif ($token->isGivenKind($controlStructureTokens)) { + $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); + $openBraceIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); + + if (!$tokens[$openBraceIndex]->equals('{')) { + continue; + } + + $positionOption = 'control_structures_opening_brace'; + } else { + continue; + } + + $closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openBraceIndex); + + $addNewlinesInsideBraces = true; + if ($allowSingleLine || $allowSingleLineIfEmpty || $index < $allowSingleLineUntil) { + $addNewlinesInsideBraces = false; + + for ($indexInsideBraces = $openBraceIndex + 1; $indexInsideBraces < $closeBraceIndex; ++$indexInsideBraces) { + $tokenInsideBraces = $tokens[$indexInsideBraces]; + + if ( + ($allowSingleLineIfEmpty && !$tokenInsideBraces->isWhitespace() && !$tokenInsideBraces->isComment()) + || ($tokenInsideBraces->isWhitespace() && Preg::match('/\R/', $tokenInsideBraces->getContent())) + ) { + $addNewlinesInsideBraces = true; + + break; + } + } + + if (!$addNewlinesInsideBraces && null === $allowSingleLineUntil) { + $allowSingleLineUntil = $closeBraceIndex; + } + } + + if ( + $addNewlinesInsideBraces + && !$this->isFollowedByNewLine($tokens, $openBraceIndex) + && !$this->hasCommentOnSameLine($tokens, $openBraceIndex) + && !$tokens[$tokens->getNextMeaningfulToken($openBraceIndex)]->isGivenKind(T_CLOSE_TAG) + ) { + $whitespace = $this->whitespacesConfig->getLineEnding().$this->getLineIndentation($tokens, $openBraceIndex); + if ($tokens->ensureWhitespaceAtIndex($openBraceIndex + 1, 0, $whitespace)) { + ++$closeBraceIndex; + } + } + + $whitespace = ' '; + if (self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END === $this->configuration[$positionOption]) { + $whitespace = $this->whitespacesConfig->getLineEnding().$this->getLineIndentation($tokens, $index); + + $previousTokenIndex = $openBraceIndex; + do { + $previousTokenIndex = $tokens->getPrevMeaningfulToken($previousTokenIndex); + } while ($tokens[$previousTokenIndex]->isGivenKind([CT::T_TYPE_COLON, CT::T_NULLABLE_TYPE, T_STRING, T_NS_SEPARATOR, CT::T_ARRAY_TYPEHINT, T_STATIC, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, T_CALLABLE, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE])); + + if ($tokens[$previousTokenIndex]->equals(')')) { + if ($tokens[--$previousTokenIndex]->isComment()) { + --$previousTokenIndex; + } + if ( + $tokens[$previousTokenIndex]->isWhitespace() + && Preg::match('/\R/', $tokens[$previousTokenIndex]->getContent()) + ) { + $whitespace = ' '; + } + } + } + + $moveBraceToIndex = null; + + if (' ' === $whitespace) { + $previousMeaningfulIndex = $tokens->getPrevMeaningfulToken($openBraceIndex); + for ($indexBeforeOpenBrace = $openBraceIndex - 1; $indexBeforeOpenBrace > $previousMeaningfulIndex; --$indexBeforeOpenBrace) { + if (!$tokens[$indexBeforeOpenBrace]->isComment()) { + continue; + } + + $tokenBeforeOpenBrace = $tokens[--$indexBeforeOpenBrace]; + if ($tokenBeforeOpenBrace->isWhitespace()) { + $moveBraceToIndex = $indexBeforeOpenBrace; + } elseif ($indexBeforeOpenBrace === $previousMeaningfulIndex) { + $moveBraceToIndex = $previousMeaningfulIndex + 1; + } + } + } elseif (!$tokens[$openBraceIndex - 1]->isWhitespace() || !Preg::match('/\R/', $tokens[$openBraceIndex - 1]->getContent())) { + for ($indexAfterOpenBrace = $openBraceIndex + 1; $indexAfterOpenBrace < $closeBraceIndex; ++$indexAfterOpenBrace) { + if ($tokens[$indexAfterOpenBrace]->isWhitespace() && Preg::match('/\R/', $tokens[$indexAfterOpenBrace]->getContent())) { + break; + } + + if ($tokens[$indexAfterOpenBrace]->isComment() && !str_starts_with($tokens[$indexAfterOpenBrace]->getContent(), '/*')) { + $moveBraceToIndex = $indexAfterOpenBrace + 1; + } + } + } + + if (null !== $moveBraceToIndex) { + /** @var Token $movedToken */ + $movedToken = clone $tokens[$openBraceIndex]; + + $delta = $openBraceIndex < $moveBraceToIndex ? 1 : -1; + + if ($tokens[$openBraceIndex + $delta]->isWhitespace()) { + if (-1 === $delta && Preg::match('/\R/', $tokens[$openBraceIndex - 1]->getContent())) { + $content = Preg::replace('/^(\h*?\R)?\h*/', '', $tokens[$openBraceIndex + 1]->getContent()); + if ('' !== $content) { + $tokens[$openBraceIndex + 1] = new Token([T_WHITESPACE, $content]); + } else { + $tokens->clearAt($openBraceIndex + 1); + } + } elseif ($tokens[$openBraceIndex - 1]->isWhitespace()) { + $tokens->clearAt($openBraceIndex - 1); + } + } + + for (; $openBraceIndex !== $moveBraceToIndex; $openBraceIndex += $delta) { + /** @var Token $siblingToken */ + $siblingToken = $tokens[$openBraceIndex + $delta]; + $tokens[$openBraceIndex] = $siblingToken; + } + + $tokens[$openBraceIndex] = $movedToken; + + $openBraceIndex = $moveBraceToIndex; + } + + if ($tokens->ensureWhitespaceAtIndex($openBraceIndex - 1, 1, $whitespace)) { + ++$closeBraceIndex; + if (null !== $allowSingleLineUntil) { + ++$allowSingleLineUntil; + } + } + + if ( + !$addNewlinesInsideBraces + || $tokens[$tokens->getPrevMeaningfulToken($closeBraceIndex)]->isGivenKind(T_OPEN_TAG) + ) { + continue; + } + + for ($prevIndex = $closeBraceIndex - 1; $tokens->isEmptyAt($prevIndex); --$prevIndex); + + $prevToken = $tokens[$prevIndex]; + if ($prevToken->isWhitespace() && Preg::match('/\R/', $prevToken->getContent())) { + continue; + } + + $whitespace = $this->whitespacesConfig->getLineEnding().$this->getLineIndentation($tokens, $openBraceIndex); + $tokens->ensureWhitespaceAtIndex($prevIndex, 1, $whitespace); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('control_structures_opening_brace', 'The position of the opening brace of control structures‘ body.')) + ->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE]) + ->setDefault(self::SAME_LINE) + ->getOption(), + (new FixerOptionBuilder('functions_opening_brace', 'The position of the opening brace of functions‘ body.')) + ->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE]) + ->setDefault(self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END) + ->getOption(), + (new FixerOptionBuilder('anonymous_functions_opening_brace', 'The position of the opening brace of anonymous functions‘ body.')) + ->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE]) + ->setDefault(self::SAME_LINE) + ->getOption(), + (new FixerOptionBuilder('classes_opening_brace', 'The position of the opening brace of classes‘ body.')) + ->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE]) + ->setDefault(self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END) + ->getOption(), + (new FixerOptionBuilder('anonymous_classes_opening_brace', 'The position of the opening brace of anonymous classes‘ body.')) + ->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE]) + ->setDefault(self::SAME_LINE) + ->getOption(), + (new FixerOptionBuilder('allow_single_line_empty_anonymous_classes', 'Allow anonymous classes to have opening and closing braces on the same line.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('allow_single_line_anonymous_functions', 'Allow anonymous functions to have opening and closing braces on the same line.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + private function findParenthesisEnd(Tokens $tokens, int $structureTokenIndex): int + { + $nextIndex = $tokens->getNextMeaningfulToken($structureTokenIndex); + $nextToken = $tokens[$nextIndex]; + + // return if next token is not opening parenthesis + if (!$nextToken->equals('(')) { + return $structureTokenIndex; + } + + return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex); + } + + private function isFollowedByNewLine(Tokens $tokens, int $index): bool + { + for (++$index, $max = \count($tokens) - 1; $index < $max; ++$index) { + $token = $tokens[$index]; + if (!$token->isComment()) { + return $token->isWhitespace() && Preg::match('/\R/', $token->getContent()); + } + } + + return false; + } + + private function hasCommentOnSameLine(Tokens $tokens, int $index): bool + { + $token = $tokens[$index + 1]; + + if ($token->isWhitespace() && !Preg::match('/\R/', $token->getContent())) { + $token = $tokens[$index + 2]; + } + + return $token->isComment(); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/CurlyBracesPositionFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/CurlyBracesPositionFixer.php new file mode 100644 index 00000000..324d0753 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/CurlyBracesPositionFixer.php @@ -0,0 +1,100 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\Indentation; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @deprecated + */ +final class CurlyBracesPositionFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface, WhitespacesAwareFixerInterface +{ + use Indentation; + + /** + * @internal + */ + public const NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END = 'next_line_unless_newline_at_signature_end'; + + /** + * @internal + */ + public const SAME_LINE = 'same_line'; + + private BracesPositionFixer $bracesPositionFixer; + + public function __construct() + { + $this->bracesPositionFixer = new BracesPositionFixer(); + + parent::__construct(); + } + + public function getDefinition(): FixerDefinitionInterface + { + $fixerDefinition = $this->bracesPositionFixer->getDefinition(); + + return new FixerDefinition( + 'Curly braces must be placed as configured.', + $fixerDefinition->getCodeSamples(), + $fixerDefinition->getDescription(), + $fixerDefinition->getRiskyDescription() + ); + } + + public function configure(array $configuration): void + { + $this->bracesPositionFixer->configure($configuration); + + parent::configure($configuration); + } + + /** + * {@inheritdoc} + * + * Must run before SingleLineEmptyBodyFixer, StatementIndentationFixer. + * Must run after ControlStructureBracesFixer, NoMultipleStatementsPerLineFixer. + */ + public function getPriority(): int + { + return $this->bracesPositionFixer->getPriority(); + } + + public function getSuccessorsNames(): array + { + return [ + $this->bracesPositionFixer->getName(), + ]; + } + + protected function createProxyFixers(): array + { + return [ + $this->bracesPositionFixer, + ]; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return $this->bracesPositionFixer->createConfigurationDefinition(); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/EncodingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/EncodingFixer.php new file mode 100644 index 00000000..2dc98e47 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/EncodingFixer.php @@ -0,0 +1,80 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR1 ¶2.2. + * + * @author Dariusz Rumiński + */ +final class EncodingFixer extends AbstractFixer +{ + private string $bom; + + public function __construct() + { + parent::__construct(); + + $this->bom = pack('CCC', 0xEF, 0xBB, 0xBF); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHP code MUST use only UTF-8 without BOM (remove BOM).', + [ + new CodeSample( + $this->bom.'getContent(); + + if (str_starts_with($content, $this->bom)) { + $newContent = substr($content, 3); + + if ('' === $newContent) { + $tokens->clearAt(0); + } else { + $tokens[0] = new Token([$tokens[0]->getId(), $newContent]); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoMultipleStatementsPerLineFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoMultipleStatementsPerLineFixer.php new file mode 100644 index 00000000..fcd9d292 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoMultipleStatementsPerLineFixer.php @@ -0,0 +1,101 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\Indentation; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶2.3 Lines: There must not be more than one statement per line. + */ +final class NoMultipleStatementsPerLineFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + use Indentation; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There must not be more than one statement per line.', + [new CodeSample("isTokenKindFound(';'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = 1, $max = \count($tokens) - 1; $index < $max; ++$index) { + if ($tokens[$index]->isGivenKind(T_FOR)) { + $index = $tokens->findBlockEnd( + Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, + $tokens->getNextTokenOfKind($index, ['(']) + ); + + continue; + } + + if (!$tokens[$index]->equals(';')) { + continue; + } + + for ($nextIndex = $index + 1; $nextIndex < $max; ++$nextIndex) { + $token = $tokens[$nextIndex]; + + if ($token->isWhitespace() || $token->isComment()) { + if (Preg::match('/\R/', $token->getContent())) { + break; + } + + continue; + } + + if (!$token->equalsAny(['}', [T_CLOSE_TAG], [T_ENDIF], [T_ENDFOR], [T_ENDSWITCH], [T_ENDWHILE], [T_ENDFOREACH]])) { + $whitespaceIndex = $index; + do { + $token = $tokens[++$whitespaceIndex]; + } while ($token->isComment()); + + $newline = $this->whitespacesConfig->getLineEnding().$this->getLineIndentation($tokens, $index); + + if ($tokens->ensureWhitespaceAtIndex($whitespaceIndex, 0, $newline)) { + ++$max; + } + } + + break; + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoTrailingCommaInSinglelineFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoTrailingCommaInSinglelineFixer.php new file mode 100644 index 00000000..610299b3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoTrailingCommaInSinglelineFixer.php @@ -0,0 +1,149 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +final class NoTrailingCommaInSinglelineFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'If a list of values separated by a comma is contained on a single line, then the last item MUST NOT have a trailing comma.', + [ + new CodeSample(" ['array_destructuring']]), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return + $tokens->isTokenKindFound(',') + && $tokens->isAnyTokenKindsFound([')', CT::T_ARRAY_SQUARE_BRACE_CLOSE, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, CT::T_GROUP_IMPORT_BRACE_CLOSE]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $elements = ['arguments', 'array_destructuring', 'array', 'group_import']; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('elements', 'Which elements to fix.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset($elements)]) + ->setDefault($elements) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (!$tokens[$index]->equals(')') && !$tokens[$index]->isGivenKind([CT::T_ARRAY_SQUARE_BRACE_CLOSE, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, CT::T_GROUP_IMPORT_BRACE_CLOSE])) { + continue; + } + + $commaIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$commaIndex]->equals(',')) { + continue; + } + + $block = Tokens::detectBlockType($tokens[$index]); + $blockOpenIndex = $tokens->findBlockStart($block['type'], $index); + + if ($tokens->isPartialCodeMultiline($blockOpenIndex, $index)) { + continue; + } + + if (!$this->shouldBeCleared($tokens, $blockOpenIndex)) { + continue; + } + + do { + $tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex); + $commaIndex = $tokens->getPrevMeaningfulToken($commaIndex); + } while ($tokens[$commaIndex]->equals(',')); + + $tokens->removeTrailingWhitespace($commaIndex); + } + } + + private function shouldBeCleared(Tokens $tokens, int $openIndex): bool + { + /** @var string[] $elements */ + $elements = $this->configuration['elements']; + + if ($tokens[$openIndex]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { + return \in_array('array', $elements, true); + } + + if ($tokens[$openIndex]->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN)) { + return \in_array('array_destructuring', $elements, true); + } + + if ($tokens[$openIndex]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + return \in_array('group_import', $elements, true); + } + + if (!$tokens[$openIndex]->equals('(')) { + return false; + } + + $beforeOpen = $tokens->getPrevMeaningfulToken($openIndex); + + if ($tokens[$beforeOpen]->isGivenKind(T_ARRAY)) { + return \in_array('array', $elements, true); + } + + if ($tokens[$beforeOpen]->isGivenKind(T_LIST)) { + return \in_array('array_destructuring', $elements, true); + } + + if ($tokens[$beforeOpen]->isGivenKind([T_UNSET, T_ISSET, T_VARIABLE, T_CLASS])) { + return \in_array('arguments', $elements, true); + } + + if ($tokens[$beforeOpen]->isGivenKind(T_STRING)) { + return !AttributeAnalyzer::isAttribute($tokens, $beforeOpen) && \in_array('arguments', $elements, true); + } + + if ($tokens[$beforeOpen]->equalsAny([')', ']', [CT::T_DYNAMIC_VAR_BRACE_CLOSE], [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE]])) { + $block = Tokens::detectBlockType($tokens[$beforeOpen]); + + return + ( + Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE === $block['type'] + || Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE === $block['type'] + || Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE === $block['type'] + || Tokens::BLOCK_TYPE_PARENTHESIS_BRACE === $block['type'] + ) && \in_array('arguments', $elements, true); + } + + return false; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NonPrintableCharacterFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NonPrintableCharacterFixer.php new file mode 100644 index 00000000..318c9fa6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NonPrintableCharacterFixer.php @@ -0,0 +1,178 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Removes Zero-width space (ZWSP), Non-breaking space (NBSP) and other invisible unicode symbols. + * + * @author Ivan Boprzenkov + */ +final class NonPrintableCharacterFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private array $symbolsReplace; + + /** + * @var int[] + */ + private static array $tokens = [ + T_STRING_VARNAME, + T_INLINE_HTML, + T_VARIABLE, + T_COMMENT, + T_ENCAPSED_AND_WHITESPACE, + T_CONSTANT_ENCAPSED_STRING, + T_DOC_COMMENT, + ]; + + public function __construct() + { + parent::__construct(); + + $this->symbolsReplace = [ + pack('H*', 'e2808b') => ['', '200b'], // ZWSP U+200B + pack('H*', 'e28087') => [' ', '2007'], // FIGURE SPACE U+2007 + pack('H*', 'e280af') => [' ', '202f'], // NBSP U+202F + pack('H*', 'e281a0') => ['', '2060'], // WORD JOINER U+2060 + pack('H*', 'c2a0') => [' ', 'a0'], // NO-BREAK SPACE U+A0 + ]; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Remove Zero-width space (ZWSP), Non-breaking space (NBSP) and other invisible unicode symbols.', + [ + new CodeSample( + ' false] + ), + ], + null, + 'Risky when strings contain intended invisible characters.' + ); + } + + public function isRisky(): bool + { + return true; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(self::$tokens); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('use_escape_sequences_in_strings', 'Whether characters should be replaced with escape sequences in strings.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $replacements = []; + $escapeSequences = []; + + foreach ($this->symbolsReplace as $character => [$replacement, $codepoint]) { + $replacements[$character] = $replacement; + $escapeSequences[$character] = '\u{'.$codepoint.'}'; + } + + foreach ($tokens as $index => $token) { + $content = $token->getContent(); + + if ( + $this->configuration['use_escape_sequences_in_strings'] + && $token->isGivenKind([T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE]) + ) { + if (!Preg::match('/'.implode('|', array_keys($escapeSequences)).'/', $content)) { + continue; + } + + $previousToken = $tokens[$index - 1]; + $stringTypeChanged = false; + $swapQuotes = false; + + if ($previousToken->isGivenKind(T_START_HEREDOC)) { + $previousTokenContent = $previousToken->getContent(); + + if (str_contains($previousTokenContent, '\'')) { + $tokens[$index - 1] = new Token([T_START_HEREDOC, str_replace('\'', '', $previousTokenContent)]); + $stringTypeChanged = true; + } + } elseif (str_starts_with($content, "'")) { + $stringTypeChanged = true; + $swapQuotes = true; + } + + if ($swapQuotes) { + $content = str_replace("\\'", "'", $content); + } + + if ($stringTypeChanged) { + $content = Preg::replace('/(\\\\{1,2})/', '\\\\\\\\', $content); + $content = str_replace('$', '\$', $content); + } + + if ($swapQuotes) { + $content = str_replace('"', '\"', $content); + $content = Preg::replace('/^\'(.*)\'$/s', '"$1"', $content); + } + + $tokens[$index] = new Token([$token->getId(), strtr($content, $escapeSequences)]); + + continue; + } + + if ($token->isGivenKind(self::$tokens)) { + $newContent = strtr($content, $replacements); + + // variable name cannot contain space + if ($token->isGivenKind([T_STRING_VARNAME, T_VARIABLE]) && str_contains($newContent, ' ')) { + continue; + } + + // multiline comment must have "*/" only at the end + if ($token->isGivenKind([T_COMMENT, T_DOC_COMMENT]) && str_starts_with($newContent, '/*') && strpos($newContent, '*/') !== \strlen($newContent) - 2) { + continue; + } + + $tokens[$index] = new Token([$token->getId(), $newContent]); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/OctalNotationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/OctalNotationFixer.php new file mode 100644 index 00000000..36f19e88 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/OctalNotationFixer.php @@ -0,0 +1,64 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class OctalNotationFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Literal octal must be in `0o` notation.', + [ + new VersionSpecificCodeSample( + "= 8_01_00 && $tokens->isTokenKindFound(T_LNUMBER); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_LNUMBER)) { + continue; + } + + $content = $token->getContent(); + + $newContent = Preg::replace('#^0_*+([0-7_]+)$#', '0o$1', $content); + + if ($content === $newContent) { + continue; + } + + $tokens[$index] = new Token([T_LNUMBER, $newContent]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/PsrAutoloadingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/PsrAutoloadingFixer.php new file mode 100644 index 00000000..2f31f540 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/PsrAutoloadingFixer.php @@ -0,0 +1,280 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\FileSpecificCodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\StdinFileInfo; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Jordi Boggiano + * @author Dariusz Rumiński + * @author Bram Gotink + * @author Graham Campbell + * @author Kuba Werłos + */ +final class PsrAutoloadingFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Classes must be in a path that matches their namespace, be at least one namespace deep and the class name should match the file name.', + [ + new FileSpecificCodeSample( + ' './src'] + ), + ], + null, + 'This fixer may change your class name, which will break the code that depends on the old name.' + ); + } + + public function configure(array $configuration): void + { + parent::configure($configuration); + + if (null !== $this->configuration['dir']) { + $realpath = realpath($this->configuration['dir']); + + if (false === $realpath) { + throw new \InvalidArgumentException(sprintf('Failed to resolve configured directory "%s".', $this->configuration['dir'])); + } + + $this->configuration['dir'] = $realpath; + } + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run before SelfAccessorFixer. + */ + public function getPriority(): int + { + return -10; + } + + public function supports(\SplFileInfo $file): bool + { + if ($file instanceof StdinFileInfo) { + return false; + } + + if ( + // ignore file with extension other than php + ('php' !== $file->getExtension()) + // ignore file with name that cannot be a class name + || !Preg::match('/^'.TypeExpression::REGEX_IDENTIFIER.'$/', $file->getBasename('.php')) + ) { + return false; + } + + try { + $tokens = Tokens::fromCode(sprintf('getBasename('.php'))); + + if ($tokens[3]->isKeyword() || $tokens[3]->isMagicConstant()) { + // name cannot be a class name - detected by PHP 5.x + return false; + } + } catch (\ParseError $e) { + // name cannot be a class name - detected by PHP 7.x + return false; + } + + // ignore stubs/fixtures, since they typically contain invalid files for various reasons + return !Preg::match('{[/\\\\](stub|fixture)s?[/\\\\]}i', $file->getRealPath()); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('dir', 'If provided, the directory where the project code is placed.')) + ->setAllowedTypes(['null', 'string']) + ->setDefault(null) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokenAnalyzer = new TokensAnalyzer($tokens); + + if (null !== $this->configuration['dir'] && !str_starts_with($file->getRealPath(), $this->configuration['dir'])) { + return; + } + + $namespace = null; + $namespaceStartIndex = null; + $namespaceEndIndex = null; + + $classyName = null; + $classyIndex = null; + + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(T_NAMESPACE)) { + if (null !== $namespace) { + return; + } + + $namespaceStartIndex = $tokens->getNextMeaningfulToken($index); + $namespaceEndIndex = $tokens->getNextTokenOfKind($namespaceStartIndex, [';']); + $namespace = trim($tokens->generatePartialCode($namespaceStartIndex, $namespaceEndIndex - 1)); + } elseif ($token->isClassy()) { + if ($tokenAnalyzer->isAnonymousClass($index)) { + continue; + } + + if (null !== $classyName) { + return; + } + + $classyIndex = $tokens->getNextMeaningfulToken($index); + $classyName = $tokens[$classyIndex]->getContent(); + } + } + + if (null === $classyName) { + return; + } + + $expectedClassyName = $this->calculateClassyName($file, $namespace, $classyName); + + if ($classyName !== $expectedClassyName) { + $tokens[$classyIndex] = new Token([T_STRING, $expectedClassyName]); + } + + if (null === $this->configuration['dir'] || null === $namespace) { + return; + } + + if (!is_dir($this->configuration['dir'])) { + return; + } + + $configuredDir = realpath($this->configuration['dir']); + $fileDir = \dirname($file->getRealPath()); + + if (\strlen($configuredDir) >= \strlen($fileDir)) { + return; + } + + $newNamespace = substr(str_replace('/', '\\', $fileDir), \strlen($configuredDir) + 1); + $originalNamespace = substr($namespace, -\strlen($newNamespace)); + + if ($originalNamespace !== $newNamespace && strtolower($originalNamespace) === strtolower($newNamespace)) { + $tokens->clearRange($namespaceStartIndex, $namespaceEndIndex); + $namespace = substr($namespace, 0, -\strlen($newNamespace)).$newNamespace; + + $newNamespace = Tokens::fromCode('clearRange(0, 2); + $newNamespace->clearEmptyTokens(); + + $tokens->insertAt($namespaceStartIndex, $newNamespace); + } + } + + private function calculateClassyName(\SplFileInfo $file, ?string $namespace, string $currentName): string + { + $name = $file->getBasename('.php'); + $maxNamespace = $this->calculateMaxNamespace($file, $namespace); + + if (null !== $this->configuration['dir']) { + return ('' !== $maxNamespace ? (str_replace('\\', '_', $maxNamespace).'_') : '').$name; + } + + $namespaceParts = array_reverse(explode('\\', $maxNamespace)); + + foreach ($namespaceParts as $namespacePart) { + $nameCandidate = sprintf('%s_%s', $namespacePart, $name); + + if (strtolower($nameCandidate) !== strtolower(substr($currentName, -\strlen($nameCandidate)))) { + break; + } + + $name = $nameCandidate; + } + + return $name; + } + + private function calculateMaxNamespace(\SplFileInfo $file, ?string $namespace): string + { + if (null === $this->configuration['dir']) { + $root = \dirname($file->getRealPath()); + + while ($root !== \dirname($root)) { + $root = \dirname($root); + } + } else { + $root = realpath($this->configuration['dir']); + } + + $namespaceAccordingToFileLocation = trim(str_replace(\DIRECTORY_SEPARATOR, '\\', substr(\dirname($file->getRealPath()), \strlen($root))), '\\'); + + if (null === $namespace) { + return $namespaceAccordingToFileLocation; + } + + $namespaceAccordingToFileLocationPartsReversed = array_reverse(explode('\\', $namespaceAccordingToFileLocation)); + $namespacePartsReversed = array_reverse(explode('\\', $namespace)); + + foreach ($namespacePartsReversed as $key => $namespaceParte) { + if (!isset($namespaceAccordingToFileLocationPartsReversed[$key])) { + break; + } + + if (strtolower($namespaceParte) !== strtolower($namespaceAccordingToFileLocationPartsReversed[$key])) { + break; + } + + unset($namespaceAccordingToFileLocationPartsReversed[$key]); + } + + return implode('\\', array_reverse($namespaceAccordingToFileLocationPartsReversed)); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/SingleLineEmptyBodyFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/SingleLineEmptyBodyFixer.php new file mode 100644 index 00000000..c3a81769 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/SingleLineEmptyBodyFixer.php @@ -0,0 +1,83 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class SingleLineEmptyBodyFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Empty body of class, interface, trait, enum or function must be abbreviated as `{}` and placed on the same line as the previous symbol, separated by a single space.', + [new CodeSample('isTokenKindFound(T_ENUM)) { // @TODO: drop condition when PHP 8.1+ is required + return true; + } + + return $tokens->isAnyTokenKindsFound([T_INTERFACE, T_CLASS, T_FUNCTION, T_TRAIT]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind([...Token::getClassyTokenKinds(), T_FUNCTION])) { + continue; + } + + $openBraceIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + if (!$tokens[$openBraceIndex]->equals('{')) { + continue; + } + + $closeBraceIndex = $tokens->getNextNonWhitespace($openBraceIndex); + if (!$tokens[$closeBraceIndex]->equals('}')) { + continue; + } + + $tokens->ensureWhitespaceAtIndex($openBraceIndex + 1, 0, ''); + + $beforeOpenBraceIndex = $tokens->getPrevNonWhitespace($openBraceIndex); + if (!$tokens[$beforeOpenBraceIndex]->isGivenKind([T_COMMENT, T_DOC_COMMENT])) { + $tokens->ensureWhitespaceAtIndex($openBraceIndex - 1, 1, ' '); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ClassReferenceNameCasingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ClassReferenceNameCasingFixer.php new file mode 100644 index 00000000..83b0f979 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ClassReferenceNameCasingFixer.php @@ -0,0 +1,164 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class ClassReferenceNameCasingFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'When referencing an internal class it must be written using the correct casing.', + [ + new CodeSample("isTokenKindFound(T_STRING); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); + $classNames = $this->getClassNames(); + + foreach ($tokens->getNamespaceDeclarations() as $namespace) { + $uses = []; + + foreach ($namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace) as $use) { + $uses[strtolower($use->getShortName())] = true; + } + + foreach ($this->getClassReference($tokens, $namespace) as $reference) { + $currentContent = $tokens[$reference]->getContent(); + $lowerCurrentContent = strtolower($currentContent); + + if (isset($classNames[$lowerCurrentContent]) && $currentContent !== $classNames[$lowerCurrentContent] && !isset($uses[$lowerCurrentContent])) { + $tokens[$reference] = new Token([T_STRING, $classNames[$lowerCurrentContent]]); + } + } + } + } + + private function getClassReference(Tokens $tokens, NamespaceAnalysis $namespace): \Generator + { + static $notBeforeKinds; + static $blockKinds; + + if (null === $notBeforeKinds) { + $notBeforeKinds = [ + CT::T_USE_TRAIT, + T_AS, + T_CASE, // PHP 8.1 trait enum-case + T_CLASS, + T_CONST, + T_DOUBLE_ARROW, + T_DOUBLE_COLON, + T_FUNCTION, + T_INTERFACE, + T_OBJECT_OPERATOR, + T_TRAIT, + ]; + + if (\defined('T_ENUM')) { // @TODO: drop condition when PHP 8.1+ is required + $notBeforeKinds[] = T_ENUM; + } + } + + if (null === $blockKinds) { + $blockKinds = ['before' => [','], 'after' => [',']]; + + foreach (Tokens::getBlockEdgeDefinitions() as $definition) { + $blockKinds['before'][] = $definition['start']; + $blockKinds['after'][] = $definition['end']; + } + } + + $namespaceIsGlobal = $namespace->isGlobalNamespace(); + + for ($index = $namespace->getScopeStartIndex(); $index < $namespace->getScopeEndIndex(); ++$index) { + if (!$tokens[$index]->isGivenKind(T_STRING)) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$nextIndex]->isGivenKind(T_NS_SEPARATOR)) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $nextIndex = $tokens->getNextMeaningfulToken($index); + + $isNamespaceSeparator = $tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR); + + if (!$isNamespaceSeparator && !$namespaceIsGlobal) { + continue; + } + + if ($isNamespaceSeparator) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + + if ($tokens[$prevIndex]->isGivenKind(T_STRING)) { + continue; + } + } elseif ($tokens[$prevIndex]->isGivenKind($notBeforeKinds)) { + continue; + } + + if ($tokens[$prevIndex]->equalsAny($blockKinds['before']) && $tokens[$nextIndex]->equalsAny($blockKinds['after'])) { + continue; + } + + if (!$tokens[$prevIndex]->isGivenKind(T_NEW) && $tokens[$nextIndex]->equalsAny(['(', ';', [T_CLOSE_TAG]])) { + continue; + } + + yield $index; + } + } + + /** + * @return array + */ + private function getClassNames(): array + { + static $classes = null; + + if (null === $classes) { + $classes = []; + + foreach (get_declared_classes() as $class) { + if ((new \ReflectionClass($class))->isInternal()) { + $classes[strtolower($class)] = $class; + } + } + } + + return $classes; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ConstantCaseFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ConstantCaseFixer.php new file mode 100644 index 00000000..14501aaf --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ConstantCaseFixer.php @@ -0,0 +1,155 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for constants case. + * + * @author Pol Dellaiera + */ +final class ConstantCaseFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * Hold the function that will be used to convert the constants. + * + * @var callable + */ + private $fixFunction; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + if ('lower' === $this->configuration['case']) { + $this->fixFunction = static fn (string $content): string => strtolower($content); + } + + if ('upper' === $this->configuration['case']) { + $this->fixFunction = static fn (string $content): string => strtoupper($content); + } + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The PHP constants `true`, `false`, and `null` MUST be written using the correct casing.', + [ + new CodeSample(" 'upper']), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_STRING); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('case', 'Whether to use the `upper` or `lower` case syntax.')) + ->setAllowedValues(['upper', 'lower']) + ->setDefault('lower') + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $fixFunction = $this->fixFunction; + + foreach ($tokens as $index => $token) { + if (!$token->isNativeConstant()) { + continue; + } + + if ( + $this->isNeighbourAccepted($tokens, $tokens->getPrevMeaningfulToken($index)) + && $this->isNeighbourAccepted($tokens, $tokens->getNextMeaningfulToken($index)) + && !$this->isEnumCaseName($tokens, $index) + ) { + $tokens[$index] = new Token([$token->getId(), $fixFunction($token->getContent())]); + } + } + } + + private function isNeighbourAccepted(Tokens $tokens, int $index): bool + { + static $forbiddenTokens = null; + + if (null === $forbiddenTokens) { + $forbiddenTokens = [ + T_AS, + T_CLASS, + T_CONST, + T_EXTENDS, + T_IMPLEMENTS, + T_INSTANCEOF, + T_INSTEADOF, + T_INTERFACE, + T_NEW, + T_NS_SEPARATOR, + T_PAAMAYIM_NEKUDOTAYIM, + T_TRAIT, + T_USE, + CT::T_USE_TRAIT, + CT::T_USE_LAMBDA, + ...Token::getObjectOperatorKinds(), + ]; + } + + $token = $tokens[$index]; + + if ($token->equalsAny(['{', '}'])) { + return false; + } + + return !$token->isGivenKind($forbiddenTokens); + } + + private function isEnumCaseName(Tokens $tokens, int $index): bool + { + if (!\defined('T_ENUM') || !$tokens->isTokenKindFound(T_ENUM)) { // @TODO: drop condition when PHP 8.1+ is required + return false; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if (null === $prevIndex || !$tokens[$prevIndex]->isGivenKind(T_CASE)) { + return false; + } + + if (!$tokens->isTokenKindFound(T_SWITCH)) { + return true; + } + + $prevIndex = $tokens->getPrevTokenOfKind($prevIndex, [[T_ENUM], [T_SWITCH]]); + + return null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(T_ENUM); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/IntegerLiteralCaseFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/IntegerLiteralCaseFixer.php new file mode 100644 index 00000000..1d85abba --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/IntegerLiteralCaseFixer.php @@ -0,0 +1,62 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class IntegerLiteralCaseFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Integer literals must be in correct case.', + [ + new CodeSample( + "isTokenKindFound(T_LNUMBER); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_LNUMBER)) { + continue; + } + + $content = $token->getContent(); + + $newContent = Preg::replaceCallback('#^0([boxBOX])([0-9a-fA-F_]+)$#', static fn ($matches) => '0'.strtolower($matches[1]).strtoupper($matches[2]), $content); + + if ($content === $newContent) { + continue; + } + + $tokens[$index] = new Token([T_LNUMBER, $newContent]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseKeywordsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseKeywordsFixer.php new file mode 100644 index 00000000..120e4cde --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseKeywordsFixer.php @@ -0,0 +1,72 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶2.5. + * + * @author Dariusz Rumiński + */ +final class LowercaseKeywordsFixer extends AbstractFixer +{ + /** + * @var int[] + */ + private static array $excludedTokens = [T_HALT_COMPILER]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHP keywords MUST be in lower case.', + [ + new CodeSample( + 'isAnyTokenKindsFound(Token::getKeywords()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if ($token->isKeyword() && !$token->isGivenKind(self::$excludedTokens)) { + $tokens[$index] = new Token([$token->getId(), strtolower($token->getContent())]); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseStaticReferenceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseStaticReferenceFixer.php new file mode 100644 index 00000000..325264b2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseStaticReferenceFixer.php @@ -0,0 +1,107 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + */ +final class LowercaseStaticReferenceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Class static references `self`, `static` and `parent` MUST be in lower case.', + [ + new CodeSample('isAnyTokenKindsFound([T_STATIC, T_STRING]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->equalsAny([[T_STRING, 'self'], [T_STATIC, 'static'], [T_STRING, 'parent']], false)) { + continue; + } + + $newContent = strtolower($token->getContent()); + if ($token->getContent() === $newContent) { + continue; // case is already correct + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->isGivenKind([T_CONST, T_DOUBLE_COLON, T_FUNCTION, T_NAMESPACE, T_NS_SEPARATOR]) || $tokens[$prevIndex]->isObjectOperator()) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ($tokens[$nextIndex]->isGivenKind([T_FUNCTION, T_NS_SEPARATOR, T_PRIVATE, T_PROTECTED, T_PUBLIC, T_STRING, CT::T_NULLABLE_TYPE])) { + continue; + } + + if ('static' === $newContent && $tokens[$nextIndex]->isGivenKind(T_VARIABLE)) { + continue; + } + + if ($tokens[$prevIndex]->isGivenKind(T_CASE) && !$tokens[$nextIndex]->isGivenKind(T_PAAMAYIM_NEKUDOTAYIM)) { + continue; + } + + $tokens[$index] = new Token([$token->getId(), $newContent]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicConstantCasingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicConstantCasingFixer.php new file mode 100644 index 00000000..f4902b77 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicConstantCasingFixer.php @@ -0,0 +1,92 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author ntzm + */ +final class MagicConstantCasingFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Magic constants should be referred to using the correct casing.', + [new CodeSample("isAnyTokenKindsFound($this->getMagicConstantTokens()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $magicConstants = $this->getMagicConstants(); + $magicConstantTokens = $this->getMagicConstantTokens(); + + foreach ($tokens as $index => $token) { + if ($token->isGivenKind($magicConstantTokens)) { + $tokens[$index] = new Token([$token->getId(), $magicConstants[$token->getId()]]); + } + } + } + + /** + * @return array + */ + private function getMagicConstants(): array + { + static $magicConstants = null; + + if (null === $magicConstants) { + $magicConstants = [ + T_LINE => '__LINE__', + T_FILE => '__FILE__', + T_DIR => '__DIR__', + T_FUNC_C => '__FUNCTION__', + T_CLASS_C => '__CLASS__', + T_METHOD_C => '__METHOD__', + T_NS_C => '__NAMESPACE__', + CT::T_CLASS_CONSTANT => 'class', + T_TRAIT_C => '__TRAIT__', + ]; + } + + return $magicConstants; + } + + /** + * @return array + */ + private function getMagicConstantTokens(): array + { + static $magicConstantTokens = null; + + if (null === $magicConstantTokens) { + $magicConstantTokens = array_keys($this->getMagicConstants()); + } + + return $magicConstantTokens; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicMethodCasingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicMethodCasingFixer.php new file mode 100644 index 00000000..4a203906 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicMethodCasingFixer.php @@ -0,0 +1,197 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class MagicMethodCasingFixer extends AbstractFixer +{ + /** + * @var array + */ + private static array $magicNames = [ + '__call' => '__call', + '__callstatic' => '__callStatic', + '__clone' => '__clone', + '__construct' => '__construct', + '__debuginfo' => '__debugInfo', + '__destruct' => '__destruct', + '__get' => '__get', + '__invoke' => '__invoke', + '__isset' => '__isset', + '__serialize' => '__serialize', + '__set' => '__set', + '__set_state' => '__set_state', + '__sleep' => '__sleep', + '__tostring' => '__toString', + '__unserialize' => '__unserialize', + '__unset' => '__unset', + '__wakeup' => '__wakeup', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Magic method definitions and calls must be using the correct casing.', + [ + new CodeSample( + '__INVOKE(1); +' + ), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_STRING) && $tokens->isAnyTokenKindsFound([T_FUNCTION, T_DOUBLE_COLON, ...Token::getObjectOperatorKinds()]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $inClass = 0; + $tokenCount = \count($tokens); + + for ($index = 1; $index < $tokenCount - 2; ++$index) { + if (0 === $inClass && $tokens[$index]->isClassy()) { + $inClass = 1; + $index = $tokens->getNextTokenOfKind($index, ['{']); + + continue; + } + + if (0 !== $inClass) { + if ($tokens[$index]->equals('{')) { + ++$inClass; + + continue; + } + + if ($tokens[$index]->equals('}')) { + --$inClass; + + continue; + } + } + + if (!$tokens[$index]->isGivenKind(T_STRING)) { + continue; // wrong type + } + + $content = $tokens[$index]->getContent(); + + if (!str_starts_with($content, '__')) { + continue; // cheap look ahead + } + + $name = strtolower($content); + + if (!$this->isMagicMethodName($name)) { + continue; // method name is not one of the magic ones we can fix + } + + $nameInCorrectCasing = $this->getMagicMethodNameInCorrectCasing($name); + if ($nameInCorrectCasing === $content) { + continue; // method name is already in the correct casing, no fix needed + } + + if ($this->isFunctionSignature($tokens, $index)) { + if (0 !== $inClass) { + // this is a method definition we want to fix + $this->setTokenToCorrectCasing($tokens, $index, $nameInCorrectCasing); + } + + continue; + } + + if ($this->isMethodCall($tokens, $index)) { + $this->setTokenToCorrectCasing($tokens, $index, $nameInCorrectCasing); + + continue; + } + + if ( + ('__callstatic' === $name || '__set_state' === $name) + && $this->isStaticMethodCall($tokens, $index) + ) { + $this->setTokenToCorrectCasing($tokens, $index, $nameInCorrectCasing); + } + } + } + + private function isFunctionSignature(Tokens $tokens, int $index): bool + { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->isGivenKind(T_FUNCTION)) { + return false; // not a method signature + } + + return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('('); + } + + private function isMethodCall(Tokens $tokens, int $index): bool + { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->isObjectOperator()) { + return false; // not a "simple" method call + } + + return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('('); + } + + private function isStaticMethodCall(Tokens $tokens, int $index): bool + { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->isGivenKind(T_DOUBLE_COLON)) { + return false; // not a "simple" static method call + } + + return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('('); + } + + private function isMagicMethodName(string $name): bool + { + return isset(self::$magicNames[$name]); + } + + /** + * @param string $name name of a magic method + */ + private function getMagicMethodNameInCorrectCasing(string $name): string + { + return self::$magicNames[$name]; + } + + private function setTokenToCorrectCasing(Tokens $tokens, int $index, string $nameInCorrectCasing): void + { + $tokens[$index] = new Token([T_STRING, $nameInCorrectCasing]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionCasingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionCasingFixer.php new file mode 100644 index 00000000..84c7c643 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionCasingFixer.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class NativeFunctionCasingFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Function defined by PHP should be called using the correct casing.', + [new CodeSample("isTokenKindFound(T_STRING); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + static $nativeFunctionNames = null; + + if (null === $nativeFunctionNames) { + $nativeFunctionNames = $this->getNativeFunctionNames(); + } + + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + // test if we are at a function all + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + // test if the function call is to a native PHP function + $lower = strtolower($tokens[$index]->getContent()); + if (!\array_key_exists($lower, $nativeFunctionNames)) { + continue; + } + + $tokens[$index] = new Token([T_STRING, $nativeFunctionNames[$lower]]); + } + } + + /** + * @return array + */ + private function getNativeFunctionNames(): array + { + $allFunctions = get_defined_functions(); + $functions = []; + foreach ($allFunctions['internal'] as $function) { + $functions[strtolower($function)] = $function; + } + + return $functions; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php new file mode 100644 index 00000000..2b2d5094 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php @@ -0,0 +1,58 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @deprecated in favor of NativeTypeDeclarationCasingFixer + */ +final class NativeFunctionTypeDeclarationCasingFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Native type declarations for functions should use the correct case.', + [ + new CodeSample("proxyFixers); + } + + protected function createProxyFixers(): array + { + $fixer = new NativeTypeDeclarationCasingFixer(); + + return [$fixer]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeTypeDeclarationCasingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeTypeDeclarationCasingFixer.php new file mode 100644 index 00000000..c0e8aa32 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeTypeDeclarationCasingFixer.php @@ -0,0 +1,360 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +final class NativeTypeDeclarationCasingFixer extends AbstractFixer +{ + /* + * https://wiki.php.net/rfc/typed_class_constants + * Supported types + * Class constant type declarations support all type declarations supported by PHP, + * except `void`, `callable`, `never`. + * + * array + * bool + * callable + * float + * int + * iterable + * object + * mixed + * parent + * self + * string + * any class or interface name -> not native, so not applicable for this Fixer + * ?type -> not native, `?` has no casing, so not applicable for this Fixer + * + * Not in the list referenced but supported: + * null + * static + */ + private const CLASS_CONST_SUPPORTED_HINTS = [ + 'array' => true, + 'bool' => true, + 'float' => true, + 'int' => true, + 'iterable' => true, + 'mixed' => true, + 'null' => true, + 'object' => true, + 'parent' => true, + 'self' => true, + 'string' => true, + 'static' => true, + ]; + + private const CLASS_PROPERTY_SUPPORTED_HINTS = [ + 'array' => true, + 'bool' => true, + 'float' => true, + 'int' => true, + 'iterable' => true, + 'mixed' => true, + 'null' => true, + 'object' => true, + 'parent' => true, + 'self' => true, + 'static' => true, + 'string' => true, + ]; + + private const TYPE_SEPARATION_TYPES = [ + CT::T_TYPE_ALTERNATION, + CT::T_TYPE_INTERSECTION, + CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, + CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, + ]; + + /** + * https://secure.php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration. + * + * self PHP 5.0 + * array PHP 5.1 + * callable PHP 5.4 + * bool PHP 7.0 + * float PHP 7.0 + * int PHP 7.0 + * string PHP 7.0 + * iterable PHP 7.1 + * void PHP 7.1 + * object PHP 7.2 + * static PHP 8.0 (return type only) + * mixed PHP 8.0 + * false PHP 8.0 (union return type only) + * null PHP 8.0 (union return type only) + * never PHP 8.1 (return type only) + * true PHP 8.2 (standalone type: https://wiki.php.net/rfc/true-type) + * false PHP 8.2 (standalone type: https://wiki.php.net/rfc/null-false-standalone-types) + * null PHP 8.2 (standalone type: https://wiki.php.net/rfc/null-false-standalone-types) + * + * @var array + */ + private array $functionTypeHints; + + private FunctionsAnalyzer $functionsAnalyzer; + + /** + * @var list> + */ + private array $propertyTypeModifiers; + + public function __construct() + { + parent::__construct(); + + $this->propertyTypeModifiers = [[T_PRIVATE], [T_PROTECTED], [T_PUBLIC]]; + + $this->functionTypeHints = [ + 'array' => true, + 'bool' => true, + 'callable' => true, + 'float' => true, + 'int' => true, + 'iterable' => true, + 'object' => true, + 'self' => true, + 'string' => true, + 'void' => true, + ]; + + if (\PHP_VERSION_ID >= 8_00_00) { + $this->functionTypeHints['false'] = true; + $this->functionTypeHints['mixed'] = true; + $this->functionTypeHints['null'] = true; + $this->functionTypeHints['static'] = true; + } + + if (\PHP_VERSION_ID >= 8_01_00) { + $this->functionTypeHints['never'] = true; + + $this->propertyTypeModifiers[] = [T_READONLY]; + } + + if (\PHP_VERSION_ID >= 8_02_00) { + $this->functionTypeHints['true'] = true; + } + + $this->functionsAnalyzer = new FunctionsAnalyzer(); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Native type declarations should be used in the correct case.', + [ + new CodeSample( + "isAnyTokenKindsFound(Token::getClassyTokenKinds()); + + return + $tokens->isAnyTokenKindsFound([T_FUNCTION, T_FN]) + || ($classyFound && $tokens->isTokenKindFound(T_STRING)) + || ( + \PHP_VERSION_ID >= 8_03_00 + && $tokens->isTokenKindFound(T_CONST) + && $classyFound + ); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->fixFunctions($tokens); + $this->fixClassConstantsAndProperties($tokens); + } + + private function fixFunctions(Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if ($tokens[$index]->isGivenKind([T_FUNCTION, T_FN])) { + $this->fixFunctionReturnType($tokens, $index); + $this->fixFunctionArgumentTypes($tokens, $index); + } + } + } + + private function fixFunctionArgumentTypes(Tokens $tokens, int $index): void + { + foreach ($this->functionsAnalyzer->getFunctionArguments($tokens, $index) as $argument) { + $this->fixArgumentType($tokens, $argument->getTypeAnalysis()); + } + } + + private function fixFunctionReturnType(Tokens $tokens, int $index): void + { + $this->fixArgumentType($tokens, $this->functionsAnalyzer->getFunctionReturnType($tokens, $index)); + } + + private function fixArgumentType(Tokens $tokens, ?TypeAnalysis $type = null): void + { + if (null === $type) { + return; + } + + for ($index = $type->getStartIndex(); $index <= $type->getEndIndex(); ++$index) { + if ($tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(T_NS_SEPARATOR)) { + continue; + } + + $this->fixCasing($this->functionTypeHints, $tokens, $index); + } + } + + private function fixClassConstantsAndProperties(Tokens $tokens): void + { + $analyzer = new TokensAnalyzer($tokens); + $elements = array_reverse($analyzer->getClassyElements(), true); + + foreach ($elements as $index => $element) { + if ('const' === $element['type']) { + if (\PHP_VERSION_ID >= 8_03_00 && !$this->isConstWithoutType($tokens, $index)) { + foreach ($this->getNativeTypeHintCandidatesForConstant($tokens, $index) as $nativeTypeHintIndex) { + $this->fixCasing($this::CLASS_CONST_SUPPORTED_HINTS, $tokens, $nativeTypeHintIndex); + } + } + + continue; + } + + if ('property' === $element['type']) { + foreach ($this->getNativeTypeHintCandidatesForProperty($tokens, $index) as $nativeTypeHintIndex) { + $this->fixCasing($this::CLASS_PROPERTY_SUPPORTED_HINTS, $tokens, $nativeTypeHintIndex); + } + } + } + } + + /** @return iterable */ + private function getNativeTypeHintCandidatesForConstant(Tokens $tokens, int $index): iterable + { + $constNameIndex = $this->getConstNameIndex($tokens, $index); + $index = $this->getFirstIndexOfType($tokens, $index); + + do { + $typeEnd = $this->getTypeEnd($tokens, $index, $constNameIndex); + + if ($typeEnd === $index) { + yield $index; + } + + do { + $index = $tokens->getNextMeaningfulToken($index); + } while ($tokens[$index]->isGivenKind(self::TYPE_SEPARATION_TYPES)); + } while ($index < $constNameIndex); + } + + private function isConstWithoutType(Tokens $tokens, int $index): bool + { + $index = $tokens->getNextMeaningfulToken($index); + + return $tokens[$index]->isGivenKind(T_STRING) && $tokens[$tokens->getNextMeaningfulToken($index)]->equals('='); + } + + private function getConstNameIndex(Tokens $tokens, int $index): int + { + return $tokens->getPrevMeaningfulToken( + $tokens->getNextTokenOfKind($index, ['=']), + ); + } + + /** @return iterable */ + private function getNativeTypeHintCandidatesForProperty(Tokens $tokens, int $index): iterable + { + $propertyNameIndex = $index; + $index = $tokens->getPrevTokenOfKind($index, $this->propertyTypeModifiers); + + $index = $this->getFirstIndexOfType($tokens, $index); + + do { + $typeEnd = $this->getTypeEnd($tokens, $index, $propertyNameIndex); + + if ($typeEnd === $index) { + yield $index; + } + + do { + $index = $tokens->getNextMeaningfulToken($index); + } while ($tokens[$index]->isGivenKind(self::TYPE_SEPARATION_TYPES)); + } while ($index < $propertyNameIndex); + + return []; + } + + private function getFirstIndexOfType(Tokens $tokens, int $index): int + { + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(CT::T_NULLABLE_TYPE)) { + $index = $tokens->getNextMeaningfulToken($index); + } + + if ($tokens[$index]->isGivenKind(CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN)) { + $index = $tokens->getNextMeaningfulToken($index); + } + + return $index; + } + + private function getTypeEnd(Tokens $tokens, int $index, int $upperLimit): int + { + if (!$tokens[$index]->isGivenKind([T_STRING, T_NS_SEPARATOR])) { + return $index; // callable, array, self, static, etc. + } + + $endIndex = $index; + while ($tokens[$index]->isGivenKind([T_STRING, T_NS_SEPARATOR]) && $index < $upperLimit) { + $endIndex = $index; + $index = $tokens->getNextMeaningfulToken($index); + } + + return $endIndex; + } + + /** + * @param array $supportedTypeHints + */ + private function fixCasing(array $supportedTypeHints, Tokens $tokens, int $index): void + { + $typeContent = $tokens[$index]->getContent(); + $typeContentLower = strtolower($typeContent); + + if (isset($supportedTypeHints[$typeContentLower]) && $typeContent !== $typeContentLower) { + $tokens[$index] = new Token([$tokens[$index]->getId(), $typeContentLower]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/CastSpacesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/CastSpacesFixer.php new file mode 100644 index 00000000..bf8c53c3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/CastSpacesFixer.php @@ -0,0 +1,118 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class CastSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const INSIDE_CAST_SPACE_REPLACE_MAP = [ + ' ' => '', + "\t" => '', + "\n" => '', + "\r" => '', + "\0" => '', + "\x0B" => '', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'A single space or none should be between cast and variable.', + [ + new CodeSample( + " 'single'] + ), + new CodeSample( + " 'none'] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run after NoShortBoolCastFixer. + */ + public function getPriority(): int + { + return -10; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getCastTokenKinds()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isCast()) { + continue; + } + + $tokens[$index] = new Token([ + $token->getId(), + strtr($token->getContent(), self::INSIDE_CAST_SPACE_REPLACE_MAP), + ]); + + if ('single' === $this->configuration['space']) { + // force single whitespace after cast token: + if ($tokens[$index + 1]->isWhitespace(" \t")) { + // - if next token is whitespaces that contains only spaces and tabs - override next token with single space + $tokens[$index + 1] = new Token([T_WHITESPACE, ' ']); + } elseif (!$tokens[$index + 1]->isWhitespace()) { + // - if next token is not whitespaces that contains spaces, tabs and new lines - append single space to current token + $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); + } + + continue; + } + + // force no whitespace after cast token: + if ($tokens[$index + 1]->isWhitespace()) { + $tokens->clearAt($index + 1); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('space', 'Spacing to apply between cast and variable.')) + ->setAllowedValues(['none', 'single']) + ->setDefault('single') + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/LowercaseCastFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/LowercaseCastFixer.php new file mode 100644 index 00000000..e50db282 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/LowercaseCastFixer.php @@ -0,0 +1,66 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class LowercaseCastFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Cast should be written in lower case.', + [ + new CodeSample( + 'isAnyTokenKindsFound(Token::getCastTokenKinds()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + if (!$tokens[$index]->isCast()) { + continue; + } + + $tokens[$index] = new Token([$tokens[$index]->getId(), strtolower($tokens[$index]->getContent())]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ModernizeTypesCastingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ModernizeTypesCastingFixer.php new file mode 100644 index 00000000..75f2a437 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ModernizeTypesCastingFixer.php @@ -0,0 +1,164 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Vladimir Reznichenko + */ +final class ModernizeTypesCastingFixer extends AbstractFunctionReferenceFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replaces `intval`, `floatval`, `doubleval`, `strval` and `boolval` function calls with according type casting operator.', + [ + new CodeSample( + ' [T_INT_CAST, '(int)'], + 'floatval' => [T_DOUBLE_CAST, '(float)'], + 'doubleval' => [T_DOUBLE_CAST, '(float)'], + 'strval' => [T_STRING_CAST, '(string)'], + 'boolval' => [T_BOOL_CAST, '(bool)'], + ]; + + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + foreach ($replacement as $functionIdentity => $newToken) { + $currIndex = 0; + + do { + // try getting function reference and translate boundaries for humans + $boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1); + + if (null === $boundaries) { + // next function search, as current one not found + continue 2; + } + + [$functionName, $openParenthesis, $closeParenthesis] = $boundaries; + + // analysing cursor shift + $currIndex = $openParenthesis; + + // indicator that the function is overridden + if (1 !== $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis)) { + continue; + } + + $paramContentEnd = $closeParenthesis; + $commaCandidate = $tokens->getPrevMeaningfulToken($paramContentEnd); + + if ($tokens[$commaCandidate]->equals(',')) { + $tokens->removeTrailingWhitespace($commaCandidate); + $tokens->clearAt($commaCandidate); + $paramContentEnd = $commaCandidate; + } + + // check if something complex passed as an argument and preserve parentheses then + $countParamTokens = 0; + + for ($paramContentIndex = $openParenthesis + 1; $paramContentIndex < $paramContentEnd; ++$paramContentIndex) { + // not a space, means some sensible token + if (!$tokens[$paramContentIndex]->isGivenKind(T_WHITESPACE)) { + ++$countParamTokens; + } + } + + $preserveParentheses = $countParamTokens > 1; + + $afterCloseParenthesisIndex = $tokens->getNextMeaningfulToken($closeParenthesis); + $afterCloseParenthesisToken = $tokens[$afterCloseParenthesisIndex]; + $wrapInParentheses = $afterCloseParenthesisToken->equalsAny(['[', '{']) || $afterCloseParenthesisToken->isGivenKind(T_POW); + + // analyse namespace specification (root one or none) and decide what to do + $prevTokenIndex = $tokens->getPrevMeaningfulToken($functionName); + + if ($tokens[$prevTokenIndex]->isGivenKind(T_NS_SEPARATOR)) { + // get rid of root namespace when it used + $tokens->removeTrailingWhitespace($prevTokenIndex); + $tokens->clearAt($prevTokenIndex); + } + + // perform transformation + $replacementSequence = [ + new Token($newToken), + new Token([T_WHITESPACE, ' ']), + ]; + + if ($wrapInParentheses) { + array_unshift($replacementSequence, new Token('(')); + } + + if (!$preserveParentheses) { + // closing parenthesis removed with leading spaces + $tokens->removeLeadingWhitespace($closeParenthesis); + $tokens->clearAt($closeParenthesis); + + // opening parenthesis removed with trailing spaces + $tokens->removeLeadingWhitespace($openParenthesis); + $tokens->removeTrailingWhitespace($openParenthesis); + $tokens->clearAt($openParenthesis); + } else { + // we'll need to provide a space after a casting operator + $tokens->removeTrailingWhitespace($functionName); + } + + if ($wrapInParentheses) { + $tokens->insertAt($closeParenthesis, new Token(')')); + } + + $tokens->overrideRange($functionName, $functionName, $replacementSequence); + + // nested transformations support + $currIndex = $functionName; + } while (null !== $currIndex); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoShortBoolCastFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoShortBoolCastFixer.php new file mode 100644 index 00000000..80439c17 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoShortBoolCastFixer.php @@ -0,0 +1,88 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class NoShortBoolCastFixer extends AbstractFixer +{ + /** + * {@inheritdoc} + * + * Must run before CastSpacesFixer. + */ + public function getPriority(): int + { + return -9; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Short cast `bool` using double exclamation mark should not be used.', + [new CodeSample("isTokenKindFound('!'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; $index > 1; --$index) { + if ($tokens[$index]->equals('!')) { + $index = $this->fixShortCast($tokens, $index); + } + } + } + + private function fixShortCast(Tokens $tokens, int $index): int + { + for ($i = $index - 1; $i > 1; --$i) { + if ($tokens[$i]->equals('!')) { + $this->fixShortCastToBoolCast($tokens, $i, $index); + + break; + } + + if (!$tokens[$i]->isComment() && !$tokens[$i]->isWhitespace()) { + break; + } + } + + return $i; + } + + private function fixShortCastToBoolCast(Tokens $tokens, int $start, int $end): void + { + for (; $start <= $end; ++$start) { + if ( + !$tokens[$start]->isComment() + && !($tokens[$start]->isWhitespace() && $tokens[$start - 1]->isComment()) + ) { + $tokens->clearAt($start); + } + } + + $tokens->insertAt($start, new Token([T_BOOL_CAST, '(bool)'])); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoUnsetCastFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoUnsetCastFixer.php new file mode 100644 index 00000000..81c1567f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoUnsetCastFixer.php @@ -0,0 +1,88 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class NoUnsetCastFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Variables must be set `null` instead of using `(unset)` casting.', + [new CodeSample("isTokenKindFound(T_UNSET_CAST); + } + + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind(T_UNSET_CAST)) { + $this->fixUnsetCast($tokens, $index); + } + } + } + + private function fixUnsetCast(Tokens $tokens, int $index): void + { + $assignmentIndex = $tokens->getPrevMeaningfulToken($index); + if (null === $assignmentIndex || !$tokens[$assignmentIndex]->equals('=')) { + return; + } + + $varIndex = $tokens->getNextMeaningfulToken($index); + if (null === $varIndex || !$tokens[$varIndex]->isGivenKind(T_VARIABLE)) { + return; + } + + $afterVar = $tokens->getNextMeaningfulToken($varIndex); + if (null === $afterVar || !$tokens[$afterVar]->equalsAny([';', [T_CLOSE_TAG]])) { + return; + } + + $nextIsWhiteSpace = $tokens[$assignmentIndex + 1]->isWhitespace(); + + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($varIndex); + + ++$assignmentIndex; + if (!$nextIsWhiteSpace) { + $tokens->insertAt($assignmentIndex, new Token([T_WHITESPACE, ' '])); + } + + ++$assignmentIndex; + $tokens->insertAt($assignmentIndex, new Token([T_STRING, 'null'])); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ShortScalarCastFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ShortScalarCastFixer.php new file mode 100644 index 00000000..934d8a89 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ShortScalarCastFixer.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class ShortScalarCastFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Cast `(boolean)` and `(integer)` should be written as `(bool)` and `(int)`, `(double)` and `(real)` as `(float)`, `(binary)` as `(string)`.', + [ + new CodeSample( + "isAnyTokenKindsFound(Token::getCastTokenKinds()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + static $castMap = [ + 'boolean' => 'bool', + 'integer' => 'int', + 'double' => 'float', + 'real' => 'float', + 'binary' => 'string', + ]; + + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + if (!$tokens[$index]->isCast()) { + continue; + } + + $castFrom = trim(substr($tokens[$index]->getContent(), 1, -1)); + $castFromLowered = strtolower($castFrom); + + if (!\array_key_exists($castFromLowered, $castMap)) { + continue; + } + + $tokens[$index] = new Token([ + $tokens[$index]->getId(), + str_replace($castFrom, $castMap[$castFromLowered], $tokens[$index]->getContent()), + ]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php new file mode 100644 index 00000000..aa0fe130 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php @@ -0,0 +1,589 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * Make sure there is one blank line above and below class elements. + * + * The exception is when an element is the first or last item in a 'classy'. + */ +final class ClassAttributesSeparationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @internal + */ + public const SPACING_NONE = 'none'; + + /** + * @internal + */ + public const SPACING_ONE = 'one'; + + private const SPACING_ONLY_IF_META = 'only_if_meta'; + + /** + * @var array + */ + private array $classElementTypes = []; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->classElementTypes = []; // reset previous configuration + + foreach ($this->configuration['elements'] as $elementType => $spacing) { + $this->classElementTypes[$elementType] = $spacing; + } + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Class, trait and interface elements must be separated with one or none blank line.', + [ + new CodeSample( + ' ['property' => self::SPACING_ONE]] + ), + new CodeSample( + ' ['const' => self::SPACING_ONE]] + ), + new CodeSample( + ' ['const' => self::SPACING_ONLY_IF_META]] + ), + new VersionSpecificCodeSample( + ' ['property' => self::SPACING_ONLY_IF_META]] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before BracesFixer, IndentationTypeFixer, NoExtraBlankLinesFixer, StatementIndentationFixer. + * Must run after OrderedClassElementsFixer, SingleClassElementPerStatementFixer, VisibilityRequiredFixer. + */ + public function getPriority(): int + { + return 55; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($this->getElementsByClass($tokens) as $class) { + $elements = $class['elements']; + $elementCount = \count($elements); + + if (0 === $elementCount) { + continue; + } + + if (isset($this->classElementTypes[$elements[0]['type']])) { + $this->fixSpaceBelowClassElement($tokens, $class); + $this->fixSpaceAboveClassElement($tokens, $class, 0); + } + + for ($index = 1; $index < $elementCount; ++$index) { + if (isset($this->classElementTypes[$elements[$index]['type']])) { + $this->fixSpaceAboveClassElement($tokens, $class, $index); + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('elements', 'Dictionary of `const|method|property|trait_import|case` => `none|one|only_if_meta` values.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([static function (array $option): bool { + foreach ($option as $type => $spacing) { + $supportedTypes = ['const', 'method', 'property', 'trait_import', 'case']; + + if (!\in_array($type, $supportedTypes, true)) { + throw new InvalidOptionsException( + sprintf( + 'Unexpected element type, expected any of %s, got "%s".', + Utils::naturalLanguageJoin($supportedTypes), + \gettype($type).'#'.$type + ) + ); + } + + $supportedSpacings = [self::SPACING_NONE, self::SPACING_ONE, self::SPACING_ONLY_IF_META]; + + if (!\in_array($spacing, $supportedSpacings, true)) { + throw new InvalidOptionsException( + sprintf( + 'Unexpected spacing for element type "%s", expected any of %s, got "%s".', + $spacing, + Utils::naturalLanguageJoin($supportedSpacings), + \is_object($spacing) ? \get_class($spacing) : (null === $spacing ? 'null' : \gettype($spacing).'#'.$spacing) + ) + ); + } + } + + return true; + }]) + ->setDefault([ + 'const' => self::SPACING_ONE, + 'method' => self::SPACING_ONE, + 'property' => self::SPACING_ONE, + 'trait_import' => self::SPACING_NONE, + 'case' => self::SPACING_NONE, + ]) + ->getOption(), + ]); + } + + /** + * Fix spacing above an element of a class, interface or trait. + * + * Deals with comments, PHPDocs and spaces above the element with respect to the position of the + * element within the class, interface or trait. + * + * @param array{ + * index: int, + * open: int, + * close: int, + * elements: non-empty-list + * } $class + */ + private function fixSpaceAboveClassElement(Tokens $tokens, array $class, int $elementIndex): void + { + $element = $class['elements'][$elementIndex]; + $elementAboveEnd = isset($class['elements'][$elementIndex + 1]) ? $class['elements'][$elementIndex + 1]['end'] : 0; + $nonWhiteAbove = $tokens->getPrevNonWhitespace($element['start']); + + // element is directly after class open brace + if ($nonWhiteAbove === $class['open']) { + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1); + + return; + } + + // deal with comments above an element + if ($tokens[$nonWhiteAbove]->isGivenKind(T_COMMENT)) { + // check if the comment belongs to the previous element + if ($elementAboveEnd === $nonWhiteAbove) { + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], $this->determineRequiredLineCount($tokens, $class, $elementIndex)); + + return; + } + + // more than one line break, always bring it back to 2 line breaks between the element start and what is above it + if ($tokens[$nonWhiteAbove + 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove + 1]->getContent(), "\n") > 1) { + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 2); + + return; + } + + // there are 2 cases: + if ( + 1 === $element['start'] - $nonWhiteAbove + || $tokens[$nonWhiteAbove - 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove - 1]->getContent(), "\n") > 0 + || $tokens[$nonWhiteAbove + 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove + 1]->getContent(), "\n") > 0 + ) { + // 1. The comment is meant for the element (although not a PHPDoc), + // make sure there is one line break between the element and the comment... + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1); + // ... and make sure there is blank line above the comment (with the exception when it is directly after a class opening) + $nonWhiteAbove = $this->findCommentBlockStart($tokens, $nonWhiteAbove, $elementAboveEnd); + $nonWhiteAboveComment = $tokens->getPrevNonWhitespace($nonWhiteAbove); + + $this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, $nonWhiteAboveComment === $class['open'] ? 1 : 2); + } else { + // 2. The comment belongs to the code above the element, + // make sure there is a blank line above the element (i.e. 2 line breaks) + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 2); + } + + return; + } + + // deal with element with a PHPDoc/attribute above it + if ($tokens[$nonWhiteAbove]->isGivenKind([T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE])) { + // there should be one linebreak between the element and the attribute above it + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1); + + // make sure there is blank line above the comment (with the exception when it is directly after a class opening) + $nonWhiteAbove = $this->findCommentBlockStart($tokens, $nonWhiteAbove, $elementAboveEnd); + $nonWhiteAboveComment = $tokens->getPrevNonWhitespace($nonWhiteAbove); + + $this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, $nonWhiteAboveComment === $class['open'] ? 1 : 2); + + return; + } + + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], $this->determineRequiredLineCount($tokens, $class, $elementIndex)); + } + + private function determineRequiredLineCount(Tokens $tokens, array $class, int $elementIndex): int + { + $type = $class['elements'][$elementIndex]['type']; + $spacing = $this->classElementTypes[$type]; + + if (self::SPACING_ONE === $spacing) { + return 2; + } + + if (self::SPACING_NONE === $spacing) { + if (!isset($class['elements'][$elementIndex + 1])) { + return 1; + } + + $aboveElement = $class['elements'][$elementIndex + 1]; + + if ($aboveElement['type'] !== $type) { + return 2; + } + + $aboveElementDocCandidateIndex = $tokens->getPrevNonWhitespace($aboveElement['start']); + + return $tokens[$aboveElementDocCandidateIndex]->isGivenKind([T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE]) ? 2 : 1; + } + + if (self::SPACING_ONLY_IF_META === $spacing) { + $aboveElementDocCandidateIndex = $tokens->getPrevNonWhitespace($class['elements'][$elementIndex]['start']); + + return $tokens[$aboveElementDocCandidateIndex]->isGivenKind([T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE]) ? 2 : 1; + } + + throw new \RuntimeException(sprintf('Unknown spacing "%s".', $spacing)); + } + + /** + * @param array{ + * index: int, + * open: int, + * close: int, + * elements: non-empty-list + * } $class + */ + private function fixSpaceBelowClassElement(Tokens $tokens, array $class): void + { + $element = $class['elements'][0]; + + // if this is last element fix; fix to the class end `}` here if appropriate + if ($class['close'] === $tokens->getNextNonWhitespace($element['end'])) { + $this->correctLineBreaks($tokens, $element['end'], $class['close'], 1); + } + } + + private function correctLineBreaks(Tokens $tokens, int $startIndex, int $endIndex, int $reqLineCount): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + ++$startIndex; + $numbOfWhiteTokens = $endIndex - $startIndex; + + if (0 === $numbOfWhiteTokens) { + $tokens->insertAt($startIndex, new Token([T_WHITESPACE, str_repeat($lineEnding, $reqLineCount)])); + + return; + } + + $lineBreakCount = $this->getLineBreakCount($tokens, $startIndex, $endIndex); + + if ($reqLineCount === $lineBreakCount) { + return; + } + + if ($lineBreakCount < $reqLineCount) { + $tokens[$startIndex] = new Token([ + T_WHITESPACE, + str_repeat($lineEnding, $reqLineCount - $lineBreakCount).$tokens[$startIndex]->getContent(), + ]); + + return; + } + + // $lineCount = > $reqLineCount : check the one Token case first since this one will be true most of the time + if (1 === $numbOfWhiteTokens) { + $tokens[$startIndex] = new Token([ + T_WHITESPACE, + Preg::replace('/\r\n|\n/', '', $tokens[$startIndex]->getContent(), $lineBreakCount - $reqLineCount), + ]); + + return; + } + + // $numbOfWhiteTokens = > 1 + $toReplaceCount = $lineBreakCount - $reqLineCount; + + for ($i = $startIndex; $i < $endIndex && $toReplaceCount > 0; ++$i) { + $tokenLineCount = substr_count($tokens[$i]->getContent(), "\n"); + + if ($tokenLineCount > 0) { + $tokens[$i] = new Token([ + T_WHITESPACE, + Preg::replace('/\r\n|\n/', '', $tokens[$i]->getContent(), min($toReplaceCount, $tokenLineCount)), + ]); + $toReplaceCount -= $tokenLineCount; + } + } + } + + private function getLineBreakCount(Tokens $tokens, int $startIndex, int $endIndex): int + { + $lineCount = 0; + + for ($i = $startIndex; $i < $endIndex; ++$i) { + $lineCount += substr_count($tokens[$i]->getContent(), "\n"); + } + + return $lineCount; + } + + private function findCommentBlockStart(Tokens $tokens, int $start, int $elementAboveEnd): int + { + for ($i = $start; $i > $elementAboveEnd; --$i) { + if ($tokens[$i]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $start = $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $i); + + continue; + } + + if ($tokens[$i]->isComment()) { + $start = $i; + + continue; + } + + if (!$tokens[$i]->isWhitespace() || $this->getLineBreakCount($tokens, $i, $i + 1) > 1) { + break; + } + } + + return $start; + } + + /** + * @TODO Introduce proper DTO instead of an array + * + * @return \Generator + * }> + */ + private function getElementsByClass(Tokens $tokens): \Generator + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $class = $classIndex = false; + $elements = $tokensAnalyzer->getClassyElements(); + + for (end($elements);; prev($elements)) { + $index = key($elements); + + if (null === $index) { + break; + } + + $element = current($elements); + $element['index'] = $index; + + if ($element['classIndex'] !== $classIndex) { + if (false !== $class) { + yield $class; + } + + $classIndex = $element['classIndex']; + $classOpen = $tokens->getNextTokenOfKind($classIndex, ['{']); + $classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpen); + $class = [ + 'index' => $classIndex, + 'open' => $classOpen, + 'close' => $classEnd, + 'elements' => [], + ]; + } + + unset($element['classIndex']); + $element['start'] = $this->getFirstTokenIndexOfClassElement($tokens, $class, $element); + $element['end'] = $this->getLastTokenIndexOfClassElement($tokens, $class, $element, $tokensAnalyzer); + + $class['elements'][] = $element; // reset the key by design + } + + if (false !== $class) { + yield $class; + } + } + + private function getFirstTokenIndexOfClassElement(Tokens $tokens, array $class, array $element): int + { + $modifierTypes = [T_PRIVATE, T_PROTECTED, T_PUBLIC, T_ABSTRACT, T_FINAL, T_STATIC, T_STRING, T_NS_SEPARATOR, T_VAR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE]; + + if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required + $modifierTypes[] = T_READONLY; + } + + $firstElementAttributeIndex = $element['index']; + + do { + $nonWhiteAbove = $tokens->getPrevMeaningfulToken($firstElementAttributeIndex); + + if (null !== $nonWhiteAbove && $tokens[$nonWhiteAbove]->isGivenKind($modifierTypes)) { + $firstElementAttributeIndex = $nonWhiteAbove; + } else { + break; + } + } while ($firstElementAttributeIndex > $class['open']); + + return $firstElementAttributeIndex; + } + + // including trailing single line comments if belonging to the class element + private function getLastTokenIndexOfClassElement(Tokens $tokens, array $class, array $element, TokensAnalyzer $tokensAnalyzer): int + { + // find last token of the element + if ('method' === $element['type'] && !$tokens[$class['index']]->isGivenKind(T_INTERFACE)) { + $attributes = $tokensAnalyzer->getMethodAttributes($element['index']); + + if (true === $attributes['abstract']) { + $elementEndIndex = $tokens->getNextTokenOfKind($element['index'], [';']); + } else { + $elementEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($element['index'], ['{'])); + } + } elseif ('trait_import' === $element['type']) { + $elementEndIndex = $element['index']; + + do { + $elementEndIndex = $tokens->getNextMeaningfulToken($elementEndIndex); + } while ($tokens[$elementEndIndex]->isGivenKind([T_STRING, T_NS_SEPARATOR]) || $tokens[$elementEndIndex]->equals(',')); + + if (!$tokens[$elementEndIndex]->equals(';')) { + $elementEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($element['index'], ['{'])); + } + } else { // 'const', 'property', enum-'case', or 'method' of an interface + $elementEndIndex = $tokens->getNextTokenOfKind($element['index'], [';']); + } + + $singleLineElement = true; + + for ($i = $element['index'] + 1; $i < $elementEndIndex; ++$i) { + if (str_contains($tokens[$i]->getContent(), "\n")) { + $singleLineElement = false; + + break; + } + } + + if ($singleLineElement) { + while (true) { + $nextToken = $tokens[$elementEndIndex + 1]; + + if (($nextToken->isComment() || $nextToken->isWhitespace()) && !str_contains($nextToken->getContent(), "\n")) { + ++$elementEndIndex; + } else { + break; + } + } + + if ($tokens[$elementEndIndex]->isWhitespace()) { + $elementEndIndex = $tokens->getPrevNonWhitespace($elementEndIndex); + } + } + + return $elementEndIndex; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassDefinitionFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassDefinitionFixer.php new file mode 100644 index 00000000..6be1745b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassDefinitionFixer.php @@ -0,0 +1,499 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * Fixer for part of the rules defined in PSR2 ¶4.1 Extends and Implements and PSR12 ¶8. Anonymous Classes. + */ +final class ClassDefinitionFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Whitespace around the keywords of a class, trait, enum or interfaces definition should be one space.', + [ + new CodeSample( + ' true] + ), + new CodeSample( + ' true] + ), + new CodeSample( + ' true] + ), + new CodeSample( + ' true] + ), + new CodeSample( + " true] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before BracesFixer, SingleLineEmptyBodyFixer. + * Must run after NewWithBracesFixer, NewWithParenthesesFixer. + */ + public function getPriority(): int + { + return 36; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + // -4, one for count to index, 3 because min. of tokens for a classy location. + for ($index = $tokens->getSize() - 4; $index > 0; --$index) { + if ($tokens[$index]->isClassy()) { + $this->fixClassyDefinition($tokens, $index); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('multi_line_extends_each_single_line', 'Whether definitions should be multiline.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('single_item_single_line', 'Whether definitions should be single line when including a single item.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('single_line', 'Whether definitions should be single line.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('space_before_parenthesis', 'Whether there should be a single space after the parenthesis of anonymous class (PSR12) or not.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('inline_constructor_arguments', 'Whether constructor argument list in anonymous classes should be single line.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + /** + * @param int $classyIndex Class definition token start index + */ + private function fixClassyDefinition(Tokens $tokens, int $classyIndex): void + { + $classDefInfo = $this->getClassyDefinitionInfo($tokens, $classyIndex); + + // PSR2 4.1 Lists of implements MAY be split across multiple lines, where each subsequent line is indented once. + // When doing so, the first item in the list MUST be on the next line, and there MUST be only one interface per line. + + if (false !== $classDefInfo['implements']) { + $classDefInfo['implements'] = $this->fixClassyDefinitionImplements( + $tokens, + $classDefInfo['open'], + $classDefInfo['implements'] + ); + } + + if (false !== $classDefInfo['extends']) { + $classDefInfo['extends'] = $this->fixClassyDefinitionExtends( + $tokens, + false === $classDefInfo['implements'] ? $classDefInfo['open'] : $classDefInfo['implements']['start'], + $classDefInfo['extends'] + ); + } + + // PSR2: class definition open curly brace must go on a new line. + // PSR12: anonymous class curly brace on same line if not multi line implements. + + $classDefInfo['open'] = $this->fixClassyDefinitionOpenSpacing($tokens, $classDefInfo); + + if ($classDefInfo['implements']) { + $end = $classDefInfo['implements']['start']; + } elseif ($classDefInfo['extends']) { + $end = $classDefInfo['extends']['start']; + } else { + $end = $tokens->getPrevNonWhitespace($classDefInfo['open']); + } + + if ($classDefInfo['anonymousClass'] && !$this->configuration['inline_constructor_arguments']) { + if (!$tokens[$end]->equals(')')) { // anonymous class with `extends` and/or `implements` + $start = $tokens->getPrevMeaningfulToken($end); + $this->makeClassyDefinitionSingleLine($tokens, $start, $end); + $end = $start; + } + + if ($tokens[$end]->equals(')')) { // skip constructor arguments of anonymous class + $end = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $end); + } + } + + // 4.1 The extends and implements keywords MUST be declared on the same line as the class name. + $this->makeClassyDefinitionSingleLine($tokens, $classDefInfo['start'], $end); + + $this->sortClassModifiers($tokens, $classDefInfo); + } + + private function fixClassyDefinitionExtends(Tokens $tokens, int $classOpenIndex, array $classExtendsInfo): array + { + $endIndex = $tokens->getPrevNonWhitespace($classOpenIndex); + + if (true === $this->configuration['single_line'] || false === $classExtendsInfo['multiLine']) { + $this->makeClassyDefinitionSingleLine($tokens, $classExtendsInfo['start'], $endIndex); + $classExtendsInfo['multiLine'] = false; + } elseif (true === $this->configuration['single_item_single_line'] && 1 === $classExtendsInfo['numberOfExtends']) { + $this->makeClassyDefinitionSingleLine($tokens, $classExtendsInfo['start'], $endIndex); + $classExtendsInfo['multiLine'] = false; + } elseif (true === $this->configuration['multi_line_extends_each_single_line'] && $classExtendsInfo['multiLine']) { + $this->makeClassyInheritancePartMultiLine($tokens, $classExtendsInfo['start'], $endIndex); + $classExtendsInfo['multiLine'] = true; + } + + return $classExtendsInfo; + } + + private function fixClassyDefinitionImplements(Tokens $tokens, int $classOpenIndex, array $classImplementsInfo): array + { + $endIndex = $tokens->getPrevNonWhitespace($classOpenIndex); + + if (true === $this->configuration['single_line'] || false === $classImplementsInfo['multiLine']) { + $this->makeClassyDefinitionSingleLine($tokens, $classImplementsInfo['start'], $endIndex); + $classImplementsInfo['multiLine'] = false; + } elseif (true === $this->configuration['single_item_single_line'] && 1 === $classImplementsInfo['numberOfImplements']) { + $this->makeClassyDefinitionSingleLine($tokens, $classImplementsInfo['start'], $endIndex); + $classImplementsInfo['multiLine'] = false; + } else { + $this->makeClassyInheritancePartMultiLine($tokens, $classImplementsInfo['start'], $endIndex); + $classImplementsInfo['multiLine'] = true; + } + + return $classImplementsInfo; + } + + private function fixClassyDefinitionOpenSpacing(Tokens $tokens, array $classDefInfo): int + { + if ($classDefInfo['anonymousClass']) { + if (false !== $classDefInfo['implements']) { + $spacing = $classDefInfo['implements']['multiLine'] ? $this->whitespacesConfig->getLineEnding() : ' '; + } elseif (false !== $classDefInfo['extends']) { + $spacing = $classDefInfo['extends']['multiLine'] ? $this->whitespacesConfig->getLineEnding() : ' '; + } else { + $spacing = ' '; + } + } else { + $spacing = $this->whitespacesConfig->getLineEnding(); + } + + $openIndex = $tokens->getNextTokenOfKind($classDefInfo['classy'], ['{']); + + if (' ' !== $spacing && str_contains($tokens[$openIndex - 1]->getContent(), "\n")) { + return $openIndex; + } + + if ($tokens[$openIndex - 1]->isWhitespace()) { + if (' ' !== $spacing || !$tokens[$tokens->getPrevNonWhitespace($openIndex - 1)]->isComment()) { + $tokens[$openIndex - 1] = new Token([T_WHITESPACE, $spacing]); + } + + return $openIndex; + } + + $tokens->insertAt($openIndex, new Token([T_WHITESPACE, $spacing])); + + return $openIndex + 1; + } + + /** + * @return array{ + * start: int, + * classy: int, + * open: int, + * extends: false|array{start: int, numberOfExtends: int, multiLine: bool}, + * implements: false|array{start: int, numberOfImplements: int, multiLine: bool}, + * anonymousClass: bool, + * final: false|int, + * abstract: false|int, + * readonly: false|int, + * } + */ + private function getClassyDefinitionInfo(Tokens $tokens, int $classyIndex): array + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $openIndex = $tokens->getNextTokenOfKind($classyIndex, ['{']); + $def = [ + 'classy' => $classyIndex, + 'open' => $openIndex, + 'extends' => false, + 'implements' => false, + 'anonymousClass' => false, + 'final' => false, + 'abstract' => false, + 'readonly' => false, + ]; + + if (!$tokens[$classyIndex]->isGivenKind(T_TRAIT)) { + $extends = $tokens->findGivenKind(T_EXTENDS, $classyIndex, $openIndex); + $def['extends'] = [] !== $extends ? $this->getClassyInheritanceInfo($tokens, key($extends), 'numberOfExtends') : false; + + if (!$tokens[$classyIndex]->isGivenKind(T_INTERFACE)) { + $implements = $tokens->findGivenKind(T_IMPLEMENTS, $classyIndex, $openIndex); + $def['implements'] = [] !== $implements ? $this->getClassyInheritanceInfo($tokens, key($implements), 'numberOfImplements') : false; + $def['anonymousClass'] = $tokensAnalyzer->isAnonymousClass($classyIndex); + } + } + + if ($def['anonymousClass']) { + $startIndex = $tokens->getPrevTokenOfKind($classyIndex, [[T_NEW]]); // go to "new" for anonymous class + } else { + $modifiers = $tokensAnalyzer->getClassyModifiers($classyIndex); + $startIndex = $classyIndex; + + foreach (['final', 'abstract', 'readonly'] as $modifier) { + if (isset($modifiers[$modifier])) { + $def[$modifier] = $modifiers[$modifier]; + $startIndex = min($startIndex, $modifiers[$modifier]); + } else { + $def[$modifier] = false; + } + } + } + + $def['start'] = $startIndex; + + return $def; + } + + private function getClassyInheritanceInfo(Tokens $tokens, int $startIndex, string $label): array + { + $implementsInfo = ['start' => $startIndex, $label => 1, 'multiLine' => false]; + ++$startIndex; + $endIndex = $tokens->getNextTokenOfKind($startIndex, ['{', [T_IMPLEMENTS], [T_EXTENDS]]); + $endIndex = $tokens[$endIndex]->equals('{') ? $tokens->getPrevNonWhitespace($endIndex) : $endIndex; + + for ($i = $startIndex; $i < $endIndex; ++$i) { + if ($tokens[$i]->equals(',')) { + ++$implementsInfo[$label]; + + continue; + } + + if (!$implementsInfo['multiLine'] && str_contains($tokens[$i]->getContent(), "\n")) { + $implementsInfo['multiLine'] = true; + } + } + + return $implementsInfo; + } + + private function makeClassyDefinitionSingleLine(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($i = $endIndex; $i >= $startIndex; --$i) { + if ($tokens[$i]->isWhitespace()) { + if ($tokens[$i - 1]->isComment() || $tokens[$i + 1]->isComment()) { + $content = $tokens[$i - 1]->getContent(); + + if (!('#' === $content || str_starts_with($content, '//'))) { + $content = $tokens[$i + 1]->getContent(); + + if (!('#' === $content || str_starts_with($content, '//'))) { + $tokens[$i] = new Token([T_WHITESPACE, ' ']); + } + } + + continue; + } + + if ($tokens[$i - 1]->isGivenKind(T_CLASS) && $tokens[$i + 1]->equals('(')) { + if (true === $this->configuration['space_before_parenthesis']) { + $tokens[$i] = new Token([T_WHITESPACE, ' ']); + } else { + $tokens->clearAt($i); + } + + continue; + } + + if (!$tokens[$i - 1]->equals(',') && $tokens[$i + 1]->equalsAny([',', ')']) || $tokens[$i - 1]->equals('(')) { + $tokens->clearAt($i); + + continue; + } + + $tokens[$i] = new Token([T_WHITESPACE, ' ']); + + continue; + } + + if ($tokens[$i]->equals(',') && !$tokens[$i + 1]->isWhitespace()) { + $tokens->insertAt($i + 1, new Token([T_WHITESPACE, ' '])); + + continue; + } + + if (true === $this->configuration['space_before_parenthesis'] && $tokens[$i]->isGivenKind(T_CLASS) && !$tokens[$i + 1]->isWhitespace()) { + $tokens->insertAt($i + 1, new Token([T_WHITESPACE, ' '])); + + continue; + } + + if (!$tokens[$i]->isComment()) { + continue; + } + + if (!$tokens[$i + 1]->isWhitespace() && !$tokens[$i + 1]->isComment() && !str_contains($tokens[$i]->getContent(), "\n")) { + $tokens->insertAt($i + 1, new Token([T_WHITESPACE, ' '])); + } + + if (!$tokens[$i - 1]->isWhitespace() && !$tokens[$i - 1]->isComment()) { + $tokens->insertAt($i, new Token([T_WHITESPACE, ' '])); + } + } + } + + private function makeClassyInheritancePartMultiLine(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($i = $endIndex; $i > $startIndex; --$i) { + $previousInterfaceImplementingIndex = $tokens->getPrevTokenOfKind($i, [',', [T_IMPLEMENTS], [T_EXTENDS]]); + $breakAtIndex = $tokens->getNextMeaningfulToken($previousInterfaceImplementingIndex); + + // make the part of a ',' or 'implements' single line + $this->makeClassyDefinitionSingleLine( + $tokens, + $breakAtIndex, + $i + ); + + // make sure the part is on its own line + $isOnOwnLine = false; + + for ($j = $breakAtIndex; $j > $previousInterfaceImplementingIndex; --$j) { + if (str_contains($tokens[$j]->getContent(), "\n")) { + $isOnOwnLine = true; + + break; + } + } + + if (!$isOnOwnLine) { + if ($tokens[$breakAtIndex - 1]->isWhitespace()) { + $tokens[$breakAtIndex - 1] = new Token([ + T_WHITESPACE, + $this->whitespacesConfig->getLineEnding().$this->whitespacesConfig->getIndent(), + ]); + } else { + $tokens->insertAt($breakAtIndex, new Token([T_WHITESPACE, $this->whitespacesConfig->getLineEnding().$this->whitespacesConfig->getIndent()])); + } + } + + $i = $previousInterfaceImplementingIndex + 1; + } + } + + /** + * @param array{ + * final: false|int, + * abstract: false|int, + * readonly: false|int, + * } $classDefInfo + */ + private function sortClassModifiers(Tokens $tokens, array $classDefInfo): void + { + if (false === $classDefInfo['readonly']) { + return; + } + + $readonlyIndex = $classDefInfo['readonly']; + + foreach (['final', 'abstract'] as $accessModifier) { + if (false === $classDefInfo[$accessModifier] || $classDefInfo[$accessModifier] < $readonlyIndex) { + continue; + } + + $accessModifierIndex = $classDefInfo[$accessModifier]; + + /** @var Token $readonlyToken */ + $readonlyToken = clone $tokens[$readonlyIndex]; + + /** @var Token $accessToken */ + $accessToken = clone $tokens[$accessModifierIndex]; + + $tokens[$readonlyIndex] = $accessToken; + $tokens[$accessModifierIndex] = $readonlyToken; + + break; + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalClassFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalClassFixer.php new file mode 100644 index 00000000..e13cc8f4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalClassFixer.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @author Filippo Tessarotto + */ +final class FinalClassFixer extends AbstractProxyFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'All classes must be final, except abstract ones and Doctrine entities.', + [ + new CodeSample( + 'configure([ + 'include' => [], + 'consider_absent_docblock_as_internal_class' => true, + ]); + + return [$fixer]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalInternalClassFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalInternalClassFixer.php new file mode 100644 index 00000000..4764dcbc --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalInternalClassFixer.php @@ -0,0 +1,356 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Options; + +/** + * @author Dariusz Rumiński + */ +final class FinalInternalClassFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const DEFAULTS = [ + 'include' => [ + 'internal', + ], + 'exclude' => [ + 'final', + 'Entity', + 'ORM\Entity', + 'ORM\Mapping\Entity', + 'Mapping\Entity', + 'Document', + 'ODM\Document', + ], + ]; + + private bool $checkAttributes; + + public function __construct() + { + parent::__construct(); + + $this->checkAttributes = \PHP_VERSION_ID >= 80000; + } + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->assertConfigHasNoConflicts(); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Internal classes should be `final`.', + [ + new CodeSample(" ['@Custom'], + 'exclude' => ['@not-fix'], + ] + ), + ], + null, + 'Changing classes to `final` might cause code execution to break.' + ); + } + + /** + * {@inheritdoc} + * + * Must run before ProtectedToPrivateFixer, SelfStaticAccessorFixer. + * Must run after PhpUnitInternalClassFixer. + */ + public function getPriority(): int + { + return 67; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_CLASS); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + if (!$tokens[$index]->isGivenKind(T_CLASS) || !$this->isClassCandidate($tokensAnalyzer, $tokens, $index)) { + continue; + } + + // make class 'final' + $tokens->insertSlices([ + $index => [ + new Token([T_FINAL, 'final']), + new Token([T_WHITESPACE, ' ']), + ], + ]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $annotationsAsserts = [static function (array $values): bool { + foreach ($values as $value) { + if (!\is_string($value) || '' === $value) { + return false; + } + } + + return true; + }]; + + $annotationsNormalizer = static function (Options $options, array $value): array { + $newValue = []; + foreach ($value as $key) { + if (str_starts_with($key, '@')) { + $key = substr($key, 1); + } + + $newValue[strtolower($key)] = true; + } + + return $newValue; + }; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('annotation_include', 'Class level attribute or annotation tags that must be set in order to fix the class (case insensitive).')) + ->setAllowedTypes(['array']) + ->setAllowedValues($annotationsAsserts) + ->setDefault( + array_map( + static fn (string $string) => '@'.$string, + self::DEFAULTS['include'], + ), + ) + ->setNormalizer($annotationsNormalizer) + ->setDeprecationMessage('Use `include` to configure PHPDoc annotations tags and attributes.') + ->getOption(), + (new FixerOptionBuilder('annotation_exclude', 'Class level attribute or annotation tags that must be omitted to fix the class, even if all of the white list ones are used as well (case insensitive).')) + ->setAllowedTypes(['array']) + ->setAllowedValues($annotationsAsserts) + ->setDefault( + array_map( + static fn (string $string) => '@'.$string, + self::DEFAULTS['exclude'], + ), + ) + ->setNormalizer($annotationsNormalizer) + ->setDeprecationMessage('Use `exclude` to configure PHPDoc annotations tags and attributes.') + ->getOption(), + (new FixerOptionBuilder('include', 'Class level attribute or annotation tags that must be set in order to fix the class (case insensitive).')) + ->setAllowedTypes(['array']) + ->setAllowedValues($annotationsAsserts) + ->setDefault(self::DEFAULTS['include']) + ->setNormalizer($annotationsNormalizer) + ->getOption(), + (new FixerOptionBuilder('exclude', 'Class level attribute or annotation tags that must be omitted to fix the class, even if all of the white list ones are used as well (case insensitive).')) + ->setAllowedTypes(['array']) + ->setAllowedValues($annotationsAsserts) + ->setDefault(self::DEFAULTS['exclude']) + ->setNormalizer($annotationsNormalizer) + ->getOption(), + (new FixerOptionBuilder('consider_absent_docblock_as_internal_class', 'Whether classes without any DocBlock should be fixed to final.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * @param int $index T_CLASS index + */ + private function isClassCandidate(TokensAnalyzer $tokensAnalyzer, Tokens $tokens, int $index): bool + { + if ($tokensAnalyzer->isAnonymousClass($index)) { + return false; + } + + $modifiers = $tokensAnalyzer->getClassyModifiers($index); + + if (isset($modifiers['final']) || isset($modifiers['abstract'])) { + return false; // ignore class; it is abstract or already final + } + + $decisions = []; + $currentIndex = $index; + + $acceptTypes = [ + CT::T_ATTRIBUTE_CLOSE, + T_DOC_COMMENT, + T_COMMENT, // Skip comments + ]; + + if (\defined('T_READONLY')) { + // Skip readonly classes for PHP 8.2+ + $acceptTypes[] = T_READONLY; + } + + while ($currentIndex) { + $currentIndex = $tokens->getPrevNonWhitespace($currentIndex); + + if (!$tokens[$currentIndex]->isGivenKind($acceptTypes)) { + break; + } + + if ($this->checkAttributes && $tokens[$currentIndex]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $attributeStartIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $currentIndex); + $decisions[] = $this->isClassCandidateBasedOnAttribute($tokens, $attributeStartIndex, $currentIndex); + + $currentIndex = $attributeStartIndex; + } + + if ($tokens[$currentIndex]->isGivenKind([T_DOC_COMMENT])) { + $decisions[] = $this->isClassCandidateBasedOnPhpDoc($tokens, $currentIndex); + } + } + + if (\in_array(false, $decisions, true)) { + return false; + } + + return \in_array(true, $decisions, true) + || ([] === $decisions && $this->configuration['consider_absent_docblock_as_internal_class']); + } + + private function isClassCandidateBasedOnPhpDoc(Tokens $tokens, int $index): ?bool + { + $doc = new DocBlock($tokens[$index]->getContent()); + $tags = []; + + foreach ($doc->getAnnotations() as $annotation) { + if (!Preg::match('/@([^\(\s]+)/', $annotation->getContent(), $matches)) { + continue; + } + $tag = strtolower(substr(array_shift($matches), 1)); + + $tags[$tag] = true; + } + + if (\count(array_intersect_key($this->configuration['exclude'], $tags)) > 0) { + return false; + } + + if ($this->isConfiguredAsInclude($tags)) { + return true; + } + + return null; + } + + private function isClassCandidateBasedOnAttribute(Tokens $tokens, int $startIndex, int $endIndex): ?bool + { + $attributeCandidates = []; + $attributeString = ''; + $currentIndex = $startIndex; + + while ($currentIndex < $endIndex && null !== ($currentIndex = $tokens->getNextMeaningfulToken($currentIndex))) { + if (!$tokens[$currentIndex]->isGivenKind([T_STRING, T_NS_SEPARATOR])) { + if ('' !== $attributeString) { + $attributeCandidates[$attributeString] = true; + $attributeString = ''; + } + + continue; + } + + $attributeString .= strtolower($tokens[$currentIndex]->getContent()); + } + + if (\count(array_intersect_key($this->configuration['exclude'], $attributeCandidates)) > 0) { + return false; + } + + if ($this->isConfiguredAsInclude($attributeCandidates)) { + return true; + } + + return null; + } + + /** + * @param array $attributes + */ + private function isConfiguredAsInclude(array $attributes): bool + { + if (0 === \count($this->configuration['include'])) { + return true; + } + + return \count(array_intersect_key($this->configuration['include'], $attributes)) > 0; + } + + private function assertConfigHasNoConflicts(): void + { + foreach (['include', 'exclude'] as $newConfigKey) { + $oldConfigKey = 'annotation_'.$newConfigKey; + $defaults = []; + + foreach (self::DEFAULTS[$newConfigKey] as $foo) { + $defaults[strtolower($foo)] = true; + } + + $newConfigIsSet = $this->configuration[$newConfigKey] !== $defaults; + $oldConfigIsSet = $this->configuration[$oldConfigKey] !== $defaults; + + if ($newConfigIsSet && $oldConfigIsSet) { + throw new InvalidFixerConfigurationException($this->getName(), sprintf('Configuration cannot contain deprecated option "%s" and new option "%s".', $oldConfigKey, $newConfigKey)); + } + + if ($oldConfigIsSet) { + $this->configuration[$newConfigKey] = $this->configuration[$oldConfigKey]; + $this->checkAttributes = false; // run in old mode + } + + // if ($newConfigIsSet) - only new config is set, all good + // if (!$newConfigIsSet && !$oldConfigIsSet) - both are set as to default values, all good + + unset($this->configuration[$oldConfigKey]); + } + + $intersect = array_intersect_assoc($this->configuration['include'], $this->configuration['exclude']); + + if (\count($intersect) > 0) { + throw new InvalidFixerConfigurationException($this->getName(), sprintf('Annotation cannot be used in both "include" and "exclude" list, got duplicates: %s.', Utils::naturalLanguageJoin(array_keys($intersect)))); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php new file mode 100644 index 00000000..ed9a7ac7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php @@ -0,0 +1,160 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + */ +final class FinalPublicMethodForAbstractClassFixer extends AbstractFixer +{ + /** + * @var array + */ + private array $magicMethods = [ + '__construct' => true, + '__destruct' => true, + '__call' => true, + '__callstatic' => true, + '__get' => true, + '__set' => true, + '__isset' => true, + '__unset' => true, + '__sleep' => true, + '__wakeup' => true, + '__tostring' => true, + '__invoke' => true, + '__set_state' => true, + '__clone' => true, + '__debuginfo' => true, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'All `public` methods of `abstract` classes should be `final`.', + [ + new CodeSample( + 'isAllTokenKindsFound([T_ABSTRACT, T_PUBLIC, T_FUNCTION]); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $abstracts = array_keys($tokens->findGivenKind(T_ABSTRACT)); + + while ($abstractIndex = array_pop($abstracts)) { + $classIndex = $tokens->getNextTokenOfKind($abstractIndex, [[T_CLASS], [T_FUNCTION]]); + if (!$tokens[$classIndex]->isGivenKind(T_CLASS)) { + continue; + } + + $classOpen = $tokens->getNextTokenOfKind($classIndex, ['{']); + $classClose = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpen); + + $this->fixClass($tokens, $classOpen, $classClose); + } + } + + private function fixClass(Tokens $tokens, int $classOpenIndex, int $classCloseIndex): void + { + for ($index = $classCloseIndex - 1; $index > $classOpenIndex; --$index) { + // skip method contents + if ($tokens[$index]->equals('}')) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + + continue; + } + + // skip non public methods + if (!$tokens[$index]->isGivenKind(T_PUBLIC)) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + $nextToken = $tokens[$nextIndex]; + + if ($nextToken->isGivenKind(T_STATIC)) { + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + $nextToken = $tokens[$nextIndex]; + } + + // skip uses, attributes, constants etc + if (!$nextToken->isGivenKind(T_FUNCTION)) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + $nextToken = $tokens[$nextIndex]; + + // skip magic methods + if (isset($this->magicMethods[strtolower($nextToken->getContent())])) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $prevToken = $tokens[$prevIndex]; + + if ($prevToken->isGivenKind(T_STATIC)) { + $index = $prevIndex; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $prevToken = $tokens[$prevIndex]; + } + + // skip abstract or already final methods + if ($prevToken->isGivenKind([T_ABSTRACT, T_FINAL])) { + $index = $prevIndex; + + continue; + } + + $tokens->insertAt( + $index, + [ + new Token([T_FINAL, 'final']), + new Token([T_WHITESPACE, ' ']), + ] + ); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php new file mode 100644 index 00000000..b09c2a2b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php @@ -0,0 +1,93 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Ceeram + */ +final class NoBlankLinesAfterClassOpeningFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should be no empty lines after class opening brace.', + [ + new CodeSample( + ' $token) { + if (!$token->isClassy()) { + continue; + } + + $startBraceIndex = $tokens->getNextTokenOfKind($index, ['{']); + if (!$tokens[$startBraceIndex + 1]->isWhitespace()) { + continue; + } + + $this->fixWhitespace($tokens, $startBraceIndex + 1); + } + } + + /** + * Cleanup a whitespace token. + */ + private function fixWhitespace(Tokens $tokens, int $index): void + { + $content = $tokens[$index]->getContent(); + // if there is more than one new line in the whitespace, then we need to fix it + if (substr_count($content, "\n") > 1) { + // the final bit of the whitespace must be the next statement's indentation + $tokens[$index] = new Token([T_WHITESPACE, $this->whitespacesConfig->getLineEnding().substr($content, strrpos($content, "\n") + 1)]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php new file mode 100644 index 00000000..b08a9231 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php @@ -0,0 +1,141 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author ntzm + */ +final class NoNullPropertyInitializationFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Properties MUST not be explicitly initialized with `null` except when they have a type declaration (PHP 7.4).', + [ + new CodeSample( + 'isAnyTokenKindsFound([T_CLASS, T_TRAIT]) && $tokens->isAnyTokenKindsFound([T_PUBLIC, T_PROTECTED, T_PRIVATE, T_VAR, T_STATIC]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $inClass = []; + $classLevel = 0; + + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + if ($tokens[$index]->isGivenKind([T_CLASS, T_TRAIT])) { // Enums and interfaces do not have properties + ++$classLevel; + $inClass[$classLevel] = 1; + + $index = $tokens->getNextTokenOfKind($index, ['{']); + + continue; + } + + if (0 === $classLevel) { + continue; + } + + if ($tokens[$index]->equals('{')) { + ++$inClass[$classLevel]; + + continue; + } + + if ($tokens[$index]->equals('}')) { + --$inClass[$classLevel]; + + if (0 === $inClass[$classLevel]) { + unset($inClass[$classLevel]); + --$classLevel; + } + + continue; + } + + // Ensure we are in a class but not in a method in case there are static variables defined + if (1 !== $inClass[$classLevel]) { + continue; + } + + if (!$tokens[$index]->isGivenKind([T_PUBLIC, T_PROTECTED, T_PRIVATE, T_VAR, T_STATIC])) { + continue; + } + + while (true) { + $varTokenIndex = $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(T_STATIC)) { + $varTokenIndex = $index = $tokens->getNextMeaningfulToken($index); + } + + if (!$tokens[$index]->isGivenKind(T_VARIABLE)) { + break; + } + + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->equals('=')) { + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(T_NS_SEPARATOR)) { + $index = $tokens->getNextMeaningfulToken($index); + } + + if ($tokens[$index]->equals([T_STRING, 'null'], false)) { + for ($i = $varTokenIndex + 1; $i <= $index; ++$i) { + if ( + !($tokens[$i]->isWhitespace() && str_contains($tokens[$i]->getContent(), "\n")) + && !$tokens[$i]->isComment() + ) { + $tokens->clearAt($i); + } + } + } + + ++$index; + } + + if (!$tokens[$index]->equals(',')) { + break; + } + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php new file mode 100644 index 00000000..be59a15e --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php @@ -0,0 +1,408 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Matteo Beccati + */ +final class NoPhp4ConstructorFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Convert PHP4-style constructors to `__construct`.', + [ + new CodeSample('isTokenKindFound(T_CLASS); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $classes = array_keys($tokens->findGivenKind(T_CLASS)); + $numClasses = \count($classes); + + for ($i = 0; $i < $numClasses; ++$i) { + $index = $classes[$i]; + + // is it an anonymous class definition? + if ($tokensAnalyzer->isAnonymousClass($index)) { + continue; + } + + // is it inside a namespace? + $nspIndex = $tokens->getPrevTokenOfKind($index, [[T_NAMESPACE, 'namespace']]); + + if (null !== $nspIndex) { + $nspIndex = $tokens->getNextMeaningfulToken($nspIndex); + + // make sure it's not the global namespace, as PHP4 constructors are allowed in there + if (!$tokens[$nspIndex]->equals('{')) { + // unless it's the global namespace, the index currently points to the name + $nspIndex = $tokens->getNextTokenOfKind($nspIndex, [';', '{']); + + if ($tokens[$nspIndex]->equals(';')) { + // the class is inside a (non-block) namespace, no PHP4-code should be in there + break; + } + + // the index points to the { of a block-namespace + $nspEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nspIndex); + + if ($index < $nspEnd) { + // the class is inside a block namespace, skip other classes that might be in it + for ($j = $i + 1; $j < $numClasses; ++$j) { + if ($classes[$j] < $nspEnd) { + ++$i; + } + } + + // and continue checking the classes that might follow + continue; + } + } + } + + $classNameIndex = $tokens->getNextMeaningfulToken($index); + $className = $tokens[$classNameIndex]->getContent(); + $classStart = $tokens->getNextTokenOfKind($classNameIndex, ['{']); + $classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classStart); + + $this->fixConstructor($tokens, $className, $classStart, $classEnd); + $this->fixParent($tokens, $classStart, $classEnd); + } + } + + /** + * Fix constructor within a class, if possible. + * + * @param Tokens $tokens the Tokens instance + * @param string $className the class name + * @param int $classStart the class start index + * @param int $classEnd the class end index + */ + private function fixConstructor(Tokens $tokens, string $className, int $classStart, int $classEnd): void + { + $php4 = $this->findFunction($tokens, $className, $classStart, $classEnd); + + if (null === $php4) { + return; // no PHP4-constructor! + } + + if (isset($php4['modifiers'][T_ABSTRACT]) || isset($php4['modifiers'][T_STATIC])) { + return; // PHP4 constructor can't be abstract or static + } + + $php5 = $this->findFunction($tokens, '__construct', $classStart, $classEnd); + + if (null === $php5) { + // no PHP5-constructor, we can rename the old one to __construct + $tokens[$php4['nameIndex']] = new Token([T_STRING, '__construct']); + + // in some (rare) cases we might have just created an infinite recursion issue + $this->fixInfiniteRecursion($tokens, $php4['bodyIndex'], $php4['endIndex']); + + return; + } + + // does the PHP4-constructor only call $this->__construct($args, ...)? + [$sequences, $case] = $this->getWrapperMethodSequence($tokens, '__construct', $php4['startIndex'], $php4['bodyIndex']); + + foreach ($sequences as $seq) { + if (null !== $tokens->findSequence($seq, $php4['bodyIndex'] - 1, $php4['endIndex'], $case)) { + // good, delete it! + for ($i = $php4['startIndex']; $i <= $php4['endIndex']; ++$i) { + $tokens->clearAt($i); + } + + return; + } + } + + // does __construct only call the PHP4-constructor (with the same args)? + [$sequences, $case] = $this->getWrapperMethodSequence($tokens, $className, $php4['startIndex'], $php4['bodyIndex']); + + foreach ($sequences as $seq) { + if (null !== $tokens->findSequence($seq, $php5['bodyIndex'] - 1, $php5['endIndex'], $case)) { + // that was a weird choice, but we can safely delete it and... + for ($i = $php5['startIndex']; $i <= $php5['endIndex']; ++$i) { + $tokens->clearAt($i); + } + + // rename the PHP4 one to __construct + $tokens[$php4['nameIndex']] = new Token([T_STRING, '__construct']); + + return; + } + } + } + + /** + * Fix calls to the parent constructor within a class. + * + * @param Tokens $tokens the Tokens instance + * @param int $classStart the class start index + * @param int $classEnd the class end index + */ + private function fixParent(Tokens $tokens, int $classStart, int $classEnd): void + { + // check calls to the parent constructor + foreach ($tokens->findGivenKind(T_EXTENDS) as $index => $token) { + $parentIndex = $tokens->getNextMeaningfulToken($index); + $parentClass = $tokens[$parentIndex]->getContent(); + + // using parent::ParentClassName() or ParentClassName::ParentClassName() + $parentSeq = $tokens->findSequence([ + [T_STRING], + [T_DOUBLE_COLON], + [T_STRING, $parentClass], + '(', + ], $classStart, $classEnd, [2 => false]); + + if (null !== $parentSeq) { + // we only need indices + $parentSeq = array_keys($parentSeq); + + // match either of the possibilities + if ($tokens[$parentSeq[0]]->equalsAny([[T_STRING, 'parent'], [T_STRING, $parentClass]], false)) { + // replace with parent::__construct + $tokens[$parentSeq[0]] = new Token([T_STRING, 'parent']); + $tokens[$parentSeq[2]] = new Token([T_STRING, '__construct']); + } + } + + foreach (Token::getObjectOperatorKinds() as $objectOperatorKind) { + // using $this->ParentClassName() + $parentSeq = $tokens->findSequence([ + [T_VARIABLE, '$this'], + [$objectOperatorKind], + [T_STRING, $parentClass], + '(', + ], $classStart, $classEnd, [2 => false]); + + if (null !== $parentSeq) { + // we only need indices + $parentSeq = array_keys($parentSeq); + + // replace call with parent::__construct() + $tokens[$parentSeq[0]] = new Token([ + T_STRING, + 'parent', + ]); + $tokens[$parentSeq[1]] = new Token([ + T_DOUBLE_COLON, + '::', + ]); + $tokens[$parentSeq[2]] = new Token([T_STRING, '__construct']); + } + } + } + } + + /** + * Fix a particular infinite recursion issue happening when the parent class has __construct and the child has only + * a PHP4 constructor that calls the parent constructor as $this->__construct(). + * + * @param Tokens $tokens the Tokens instance + * @param int $start the PHP4 constructor body start + * @param int $end the PHP4 constructor body end + */ + private function fixInfiniteRecursion(Tokens $tokens, int $start, int $end): void + { + foreach (Token::getObjectOperatorKinds() as $objectOperatorKind) { + $seq = [ + [T_VARIABLE, '$this'], + [$objectOperatorKind], + [T_STRING, '__construct'], + ]; + + while (true) { + $callSeq = $tokens->findSequence($seq, $start, $end, [2 => false]); + + if (null === $callSeq) { + return; + } + + $callSeq = array_keys($callSeq); + + $tokens[$callSeq[0]] = new Token([T_STRING, 'parent']); + $tokens[$callSeq[1]] = new Token([T_DOUBLE_COLON, '::']); + } + } + } + + /** + * Generate the sequence of tokens necessary for the body of a wrapper method that simply + * calls $this->{$method}( [args...] ) with the same arguments as its own signature. + * + * @param Tokens $tokens the Tokens instance + * @param string $method the wrapped method name + * @param int $startIndex function/method start index + * @param int $bodyIndex function/method body index + * + * @return array an array containing the sequence and case sensitiveness [ 0 => $seq, 1 => $case ] + */ + private function getWrapperMethodSequence(Tokens $tokens, string $method, int $startIndex, int $bodyIndex): array + { + $sequences = []; + + foreach (Token::getObjectOperatorKinds() as $objectOperatorKind) { + // initialise sequence as { $this->{$method}( + $seq = [ + '{', + [T_VARIABLE, '$this'], + [$objectOperatorKind], + [T_STRING, $method], + '(', + ]; + + // parse method parameters, if any + $index = $startIndex; + + while (true) { + // find the next variable name + $index = $tokens->getNextTokenOfKind($index, [[T_VARIABLE]]); + + if (null === $index || $index >= $bodyIndex) { + // we've reached the body already + break; + } + + // append a comma if it's not the first variable + if (\count($seq) > 5) { + $seq[] = ','; + } + + // append variable name to the sequence + $seq[] = [T_VARIABLE, $tokens[$index]->getContent()]; + } + + // almost done, close the sequence with ); } + $seq[] = ')'; + $seq[] = ';'; + $seq[] = '}'; + + $sequences[] = $seq; + } + + return [$sequences, [3 => false]]; + } + + /** + * Find a function or method matching a given name within certain bounds. + * + * Returns: + * - nameIndex (int): The index of the function/method name. + * - startIndex (int): The index of the function/method start. + * - endIndex (int): The index of the function/method end. + * - bodyIndex (int): The index of the function/method body. + * - modifiers (array): The modifiers as array keys and their index as the values, e.g. array(T_PUBLIC => 10) + * + * @param Tokens $tokens the Tokens instance + * @param string $name the function/Method name + * @param int $startIndex the search start index + * @param int $endIndex the search end index + * + * @return null|array{ + * nameIndex: int, + * startIndex: int, + * endIndex: int, + * bodyIndex: int, + * modifiers: list, + * } + */ + private function findFunction(Tokens $tokens, string $name, int $startIndex, int $endIndex): ?array + { + $function = $tokens->findSequence([ + [T_FUNCTION], + [T_STRING, $name], + '(', + ], $startIndex, $endIndex, false); + + if (null === $function) { + return null; + } + + // keep only the indices + $function = array_keys($function); + + // find previous block, saving method modifiers for later use + $possibleModifiers = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_STATIC, T_ABSTRACT, T_FINAL]; + $modifiers = []; + + $prevBlock = $tokens->getPrevMeaningfulToken($function[0]); + + while (null !== $prevBlock && $tokens[$prevBlock]->isGivenKind($possibleModifiers)) { + $modifiers[$tokens[$prevBlock]->getId()] = $prevBlock; + $prevBlock = $tokens->getPrevMeaningfulToken($prevBlock); + } + + if (isset($modifiers[T_ABSTRACT])) { + // abstract methods have no body + $bodyStart = null; + $funcEnd = $tokens->getNextTokenOfKind($function[2], [';']); + } else { + // find method body start and the end of the function definition + $bodyStart = $tokens->getNextTokenOfKind($function[2], ['{']); + $funcEnd = null !== $bodyStart ? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $bodyStart) : null; + } + + return [ + 'nameIndex' => $function[1], + 'startIndex' => $prevBlock + 1, + 'endIndex' => $funcEnd, + 'bodyIndex' => $bodyStart, + 'modifiers' => $modifiers, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php new file mode 100644 index 00000000..276bdaba --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php @@ -0,0 +1,211 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Filippo Tessarotto + */ +final class NoUnneededFinalMethodFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes `final` from methods where possible.', + [ + new CodeSample( + ' false] + ), + ], + null, + 'Risky when child class overrides a `private` method.' + ); + } + + public function isCandidate(Tokens $tokens): bool + { + if (!$tokens->isAllTokenKindsFound([T_FINAL, T_FUNCTION])) { + return false; + } + + if (\defined('T_ENUM') && $tokens->isTokenKindFound(T_ENUM)) { // @TODO: drop condition when PHP 8.1+ is required + return true; + } + + return $tokens->isTokenKindFound(T_CLASS); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($this->getMethods($tokens) as $element) { + $index = $element['method_final_index']; + + if ($element['method_of_enum'] || $element['class_is_final']) { + $this->clearFinal($tokens, $index); + + continue; + } + + if (!$element['method_is_private'] || false === $this->configuration['private_methods'] || $element['method_is_constructor']) { + continue; + } + + $this->clearFinal($tokens, $index); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('private_methods', 'Private methods of non-`final` classes must not be declared `final`.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + /** + * @return \Generator + */ + private function getMethods(Tokens $tokens): \Generator + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $modifierKinds = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FINAL, T_ABSTRACT, T_STATIC]; + + $enums = []; + $classesAreFinal = []; + $elements = $tokensAnalyzer->getClassyElements(); + + for (end($elements);; prev($elements)) { + $index = key($elements); + + if (null === $index) { + break; + } + + $element = current($elements); + + if ('method' !== $element['type']) { + continue; // not a method + } + + $classIndex = $element['classIndex']; + + if (!\array_key_exists($classIndex, $enums)) { + $enums[$classIndex] = \defined('T_ENUM') && $tokens[$classIndex]->isGivenKind(T_ENUM); // @TODO: drop condition when PHP 8.1+ is required + } + + $element['method_final_index'] = null; + $element['method_is_private'] = false; + + $previous = $index; + + do { + $previous = $tokens->getPrevMeaningfulToken($previous); + + if ($tokens[$previous]->isGivenKind(T_PRIVATE)) { + $element['method_is_private'] = true; + } elseif ($tokens[$previous]->isGivenKind(T_FINAL)) { + $element['method_final_index'] = $previous; + } + } while ($tokens[$previous]->isGivenKind($modifierKinds)); + + if ($enums[$classIndex]) { + $element['method_of_enum'] = true; + + yield $element; + + continue; + } + + if (!\array_key_exists($classIndex, $classesAreFinal)) { + $modifiers = $tokensAnalyzer->getClassyModifiers($classIndex); + $classesAreFinal[$classIndex] = isset($modifiers['final']); + } + + $element['method_of_enum'] = false; + $element['class_is_final'] = $classesAreFinal[$classIndex]; + $element['method_is_constructor'] = '__construct' === strtolower($tokens[$tokens->getNextMeaningfulToken($index)]->getContent()); + + yield $element; + } + } + + private function clearFinal(Tokens $tokens, ?int $index): void + { + if (null === $index) { + return; + } + + $tokens->clearAt($index); + + ++$index; + + if ($tokens[$index]->isWhitespace()) { + $tokens->clearAt($index); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedClassElementsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedClassElementsFixer.php new file mode 100644 index 00000000..46778def --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedClassElementsFixer.php @@ -0,0 +1,620 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Gregor Harlan + */ +final class OrderedClassElementsFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @internal */ + public const SORT_ALPHA = 'alpha'; + + /** @internal */ + public const SORT_NONE = 'none'; + + private const SUPPORTED_SORT_ALGORITHMS = [ + self::SORT_NONE, + self::SORT_ALPHA, + ]; + + /** + * @var array> Array containing all class element base types (keys) and their parent types (values) + */ + private static array $typeHierarchy = [ + 'use_trait' => null, + 'public' => null, + 'protected' => null, + 'private' => null, + 'case' => ['public'], + 'constant' => null, + 'constant_public' => ['constant', 'public'], + 'constant_protected' => ['constant', 'protected'], + 'constant_private' => ['constant', 'private'], + 'property' => null, + 'property_static' => ['property'], + 'property_public' => ['property', 'public'], + 'property_protected' => ['property', 'protected'], + 'property_private' => ['property', 'private'], + 'property_public_readonly' => ['property_readonly', 'property_public'], + 'property_protected_readonly' => ['property_readonly', 'property_protected'], + 'property_private_readonly' => ['property_readonly', 'property_private'], + 'property_public_static' => ['property_static', 'property_public'], + 'property_protected_static' => ['property_static', 'property_protected'], + 'property_private_static' => ['property_static', 'property_private'], + 'method' => null, + 'method_abstract' => ['method'], + 'method_static' => ['method'], + 'method_public' => ['method', 'public'], + 'method_protected' => ['method', 'protected'], + 'method_private' => ['method', 'private'], + 'method_public_abstract' => ['method_abstract', 'method_public'], + 'method_protected_abstract' => ['method_abstract', 'method_protected'], + 'method_private_abstract' => ['method_abstract', 'method_private'], + 'method_public_abstract_static' => ['method_abstract', 'method_static', 'method_public'], + 'method_protected_abstract_static' => ['method_abstract', 'method_static', 'method_protected'], + 'method_private_abstract_static' => ['method_abstract', 'method_static', 'method_private'], + 'method_public_static' => ['method_static', 'method_public'], + 'method_protected_static' => ['method_static', 'method_protected'], + 'method_private_static' => ['method_static', 'method_private'], + ]; + + /** + * @var array Array containing special method types + */ + private static array $specialTypes = [ + 'construct' => null, + 'destruct' => null, + 'magic' => null, + 'phpunit' => null, + ]; + + /** + * @var array Resolved configuration array (type => position) + */ + private array $typePosition; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->typePosition = []; + $pos = 0; + + foreach ($this->configuration['order'] as $type) { + $this->typePosition[$type] = $pos++; + } + + foreach (self::$typeHierarchy as $type => $parents) { + if (isset($this->typePosition[$type])) { + continue; + } + + if (null === $parents) { + $this->typePosition[$type] = null; + + continue; + } + + foreach ($parents as $parent) { + if (isset($this->typePosition[$parent])) { + $this->typePosition[$type] = $this->typePosition[$parent]; + + continue 2; + } + } + + $this->typePosition[$type] = null; + } + + $lastPosition = \count($this->configuration['order']); + + foreach ($this->typePosition as &$pos) { + if (null === $pos) { + $pos = $lastPosition; + } + + $pos *= 10; // last digit is used by phpunit method ordering + } + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Orders the elements of classes/interfaces/traits/enums.', + [ + new CodeSample( + ' ['method_private', 'method_public']] + ), + new CodeSample( + ' ['method_public'], 'sort_algorithm' => self::SORT_ALPHA] + ), + new CodeSample( + ' ['method_public'], 'sort_algorithm' => self::SORT_ALPHA, 'case_sensitive' => true] + ), + ], + 'Accepts a subset of pre-defined element types, special element groups, and custom patterns. + +Element types: `[\''.implode('\', \'', array_keys(self::$typeHierarchy)).'\']` + +Special element types: `[\''.implode('\', \'', array_keys(self::$specialTypes)).'\']` + +Custom values: + +- `method:*`: specify a single method name (e.g. `method:__invoke`) to set the order of that specific method.' + ); + } + + /** + * {@inheritdoc} + * + * Must run before ClassAttributesSeparationFixer, NoBlankLinesAfterClassOpeningFixer, SpaceAfterSemicolonFixer. + * Must run after NoPhp4ConstructorFixer, ProtectedToPrivateFixer. + */ + public function getPriority(): int + { + return 65; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($i = 1, $count = $tokens->count(); $i < $count; ++$i) { + if (!$tokens[$i]->isClassy()) { + continue; + } + + $i = $tokens->getNextTokenOfKind($i, ['{']); + $elements = $this->getElements($tokens, $i); + + if (0 === \count($elements)) { + continue; + } + + $sorted = $this->sortElements($elements); + $endIndex = $elements[\count($elements) - 1]['end']; + + if ($sorted !== $elements) { + $this->sortTokens($tokens, $i, $endIndex, $sorted); + } + + $i = $endIndex; + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $builtIns = array_keys(array_merge(self::$typeHierarchy, self::$specialTypes)); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('order', 'List of strings defining order of elements.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([ + static function (array $values) use ($builtIns): bool { + foreach ($values as $value) { + if (\in_array($value, $builtIns, true)) { + return true; + } + + if (\is_string($value) && 'method:' === substr($value, 0, 7)) { + return true; + } + } + + return false; + }, + ]) + ->setDefault([ + 'use_trait', + 'case', + 'constant_public', + 'constant_protected', + 'constant_private', + 'property_public', + 'property_protected', + 'property_private', + 'construct', + 'destruct', + 'magic', + 'phpunit', + 'method_public', + 'method_protected', + 'method_private', + ]) + ->getOption(), + (new FixerOptionBuilder('sort_algorithm', 'How multiple occurrences of same type statements should be sorted.')) + ->setAllowedValues(self::SUPPORTED_SORT_ALGORITHMS) + ->setDefault(self::SORT_NONE) + ->getOption(), + (new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * @return list + */ + private function getElements(Tokens $tokens, int $startIndex): array + { + static $elementTokenKinds = [CT::T_USE_TRAIT, T_CASE, T_CONST, T_VARIABLE, T_FUNCTION]; + + ++$startIndex; + $elements = []; + + while (true) { + $element = [ + 'start' => $startIndex, + 'visibility' => 'public', + 'abstract' => false, + 'static' => false, + 'readonly' => false, + ]; + + for ($i = $startIndex;; ++$i) { + $token = $tokens[$i]; + + // class end + if ($token->equals('}')) { + return $elements; + } + + if ($token->isGivenKind(T_ABSTRACT)) { + $element['abstract'] = true; + + continue; + } + + if ($token->isGivenKind(T_STATIC)) { + $element['static'] = true; + + continue; + } + + if (\defined('T_READONLY') && $token->isGivenKind(T_READONLY)) { // @TODO: drop condition when PHP 8.1+ is required + $element['readonly'] = true; + } + + if ($token->isGivenKind([T_PROTECTED, T_PRIVATE])) { + $element['visibility'] = strtolower($token->getContent()); + + continue; + } + + if (!$token->isGivenKind($elementTokenKinds)) { + continue; + } + + $type = $this->detectElementType($tokens, $i); + + if (\is_array($type)) { + $element['type'] = $type[0]; + $element['name'] = $type[1]; + } else { + $element['type'] = $type; + } + + if ('property' === $element['type']) { + $element['name'] = $tokens[$i]->getContent(); + } elseif (\in_array($element['type'], ['use_trait', 'case', 'constant', 'method', 'magic', 'construct', 'destruct'], true)) { + $element['name'] = $tokens[$tokens->getNextMeaningfulToken($i)]->getContent(); + } + + $element['end'] = $this->findElementEnd($tokens, $i); + + break; + } + + $elements[] = $element; + $startIndex = $element['end'] + 1; + } + } + + /** + * @return array|string type or array of type and name + */ + private function detectElementType(Tokens $tokens, int $index) + { + $token = $tokens[$index]; + + if ($token->isGivenKind(CT::T_USE_TRAIT)) { + return 'use_trait'; + } + + if ($token->isGivenKind(T_CASE)) { + return 'case'; + } + + if ($token->isGivenKind(T_CONST)) { + return 'constant'; + } + + if ($token->isGivenKind(T_VARIABLE)) { + return 'property'; + } + + $nameToken = $tokens[$tokens->getNextMeaningfulToken($index)]; + + if ($nameToken->equals([T_STRING, '__construct'], false)) { + return 'construct'; + } + + if ($nameToken->equals([T_STRING, '__destruct'], false)) { + return 'destruct'; + } + + if ( + $nameToken->equalsAny([ + [T_STRING, 'setUpBeforeClass'], + [T_STRING, 'doSetUpBeforeClass'], + [T_STRING, 'tearDownAfterClass'], + [T_STRING, 'doTearDownAfterClass'], + [T_STRING, 'setUp'], + [T_STRING, 'doSetUp'], + [T_STRING, 'assertPreConditions'], + [T_STRING, 'assertPostConditions'], + [T_STRING, 'tearDown'], + [T_STRING, 'doTearDown'], + ], false) + ) { + return ['phpunit', strtolower($nameToken->getContent())]; + } + + return str_starts_with($nameToken->getContent(), '__') ? 'magic' : 'method'; + } + + private function findElementEnd(Tokens $tokens, int $index): int + { + $index = $tokens->getNextTokenOfKind($index, ['{', ';']); + + if ($tokens[$index]->equals('{')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + } + + for (++$index; $tokens[$index]->isWhitespace(" \t") || $tokens[$index]->isComment(); ++$index); + + --$index; + + return $tokens[$index]->isWhitespace() ? $index - 1 : $index; + } + + /** + * @return list + */ + private function sortElements(array $elements): array + { + static $phpunitPositions = [ + 'setupbeforeclass' => 1, + 'dosetupbeforeclass' => 2, + 'teardownafterclass' => 3, + 'doteardownafterclass' => 4, + 'setup' => 5, + 'dosetup' => 6, + 'assertpreconditions' => 7, + 'assertpostconditions' => 8, + 'teardown' => 9, + 'doteardown' => 10, + ]; + + foreach ($elements as &$element) { + $type = $element['type']; + + if (\in_array($type, ['method', 'magic', 'phpunit'], true) && isset($this->typePosition["method:{$element['name']}"])) { + $element['position'] = $this->typePosition["method:{$element['name']}"]; + + continue; + } + + if (\array_key_exists($type, self::$specialTypes)) { + if (isset($this->typePosition[$type])) { + $element['position'] = $this->typePosition[$type]; + + if ('phpunit' === $type) { + $element['position'] += $phpunitPositions[$element['name']]; + } + + continue; + } + + $type = 'method'; + } + + if (\in_array($type, ['constant', 'property', 'method'], true)) { + $type .= '_'.$element['visibility']; + + if ($element['abstract']) { + $type .= '_abstract'; + } + + if ($element['static']) { + $type .= '_static'; + } + + if ($element['readonly']) { + $type .= '_readonly'; + } + } + + $element['position'] = $this->typePosition[$type]; + } + + unset($element); + + usort($elements, function (array $a, array $b): int { + if ($a['position'] === $b['position']) { + return $this->sortGroupElements($a, $b); + } + + return $a['position'] <=> $b['position']; + }); + + return $elements; + } + + /** + * @param array{ + * start: int, + * visibility: string, + * abstract: bool, + * static: bool, + * readonly: bool, + * type: string, + * name: string, + * end: int, + * position: int, + * } $a + * @param array{ + * start: int, + * visibility: string, + * abstract: bool, + * static: bool, + * readonly: bool, + * type: string, + * name: string, + * end: int, + * position: int, + * } $b + */ + private function sortGroupElements(array $a, array $b): int + { + if (self::SORT_ALPHA === $this->configuration['sort_algorithm']) { + return $this->configuration['case_sensitive'] + ? $a['name'] <=> $b['name'] + : strcasecmp($a['name'], $b['name']); + } + + return $a['start'] <=> $b['start']; + } + + /** + * @param list $elements + */ + private function sortTokens(Tokens $tokens, int $startIndex, int $endIndex, array $elements): void + { + $replaceTokens = []; + + foreach ($elements as $element) { + for ($i = $element['start']; $i <= $element['end']; ++$i) { + $replaceTokens[] = clone $tokens[$i]; + } + } + + $tokens->overrideRange($startIndex + 1, $endIndex, $replaceTokens); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedInterfacesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedInterfacesFixer.php new file mode 100644 index 00000000..1512eea4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedInterfacesFixer.php @@ -0,0 +1,245 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dave van der Brugge + */ +final class OrderedInterfacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @internal */ + public const OPTION_DIRECTION = 'direction'; + + /** @internal */ + public const OPTION_ORDER = 'order'; + + /** @internal */ + public const DIRECTION_ASCEND = 'ascend'; + + /** @internal */ + public const DIRECTION_DESCEND = 'descend'; + + /** @internal */ + public const ORDER_ALPHA = 'alpha'; + + /** @internal */ + public const ORDER_LENGTH = 'length'; + + /** + * Array of supported directions in configuration. + * + * @var string[] + */ + private const SUPPORTED_DIRECTION_OPTIONS = [ + self::DIRECTION_ASCEND, + self::DIRECTION_DESCEND, + ]; + + /** + * Array of supported orders in configuration. + * + * @var string[] + */ + private const SUPPORTED_ORDER_OPTIONS = [ + self::ORDER_ALPHA, + self::ORDER_LENGTH, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Orders the interfaces in an `implements` or `interface extends` clause.', + [ + new CodeSample( + " self::DIRECTION_DESCEND] + ), + new CodeSample( + " self::ORDER_LENGTH] + ), + new CodeSample( + " self::ORDER_LENGTH, + self::OPTION_DIRECTION => self::DIRECTION_DESCEND, + ] + ), + new CodeSample( + " self::ORDER_ALPHA, + ] + ), + new CodeSample( + " self::ORDER_ALPHA, + 'case_sensitive' => true, + ] + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_IMPLEMENTS) + || $tokens->isAllTokenKindsFound([T_INTERFACE, T_EXTENDS]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_IMPLEMENTS)) { + if (!$token->isGivenKind(T_EXTENDS)) { + continue; + } + + $nameTokenIndex = $tokens->getPrevMeaningfulToken($index); + $interfaceTokenIndex = $tokens->getPrevMeaningfulToken($nameTokenIndex); + $interfaceToken = $tokens[$interfaceTokenIndex]; + + if (!$interfaceToken->isGivenKind(T_INTERFACE)) { + continue; + } + } + + $implementsStart = $index + 1; + $implementsEnd = $tokens->getPrevMeaningfulToken($tokens->getNextTokenOfKind($implementsStart, ['{'])); + + $interfaces = $this->getInterfaces($tokens, $implementsStart, $implementsEnd); + + if (1 === \count($interfaces)) { + continue; + } + + foreach ($interfaces as $interfaceIndex => $interface) { + $interfaceTokens = Tokens::fromArray($interface, false); + $normalized = ''; + $actualInterfaceIndex = $interfaceTokens->getNextMeaningfulToken(-1); + + while ($interfaceTokens->offsetExists($actualInterfaceIndex)) { + $token = $interfaceTokens[$actualInterfaceIndex]; + + if ($token->isComment() || $token->isWhitespace()) { + break; + } + + $normalized .= str_replace('\\', ' ', $token->getContent()); + ++$actualInterfaceIndex; + } + + $interfaces[$interfaceIndex] = [ + 'tokens' => $interface, + 'normalized' => $normalized, + 'originalIndex' => $interfaceIndex, + ]; + } + + usort($interfaces, function (array $first, array $second): int { + $score = self::ORDER_LENGTH === $this->configuration[self::OPTION_ORDER] + ? \strlen($first['normalized']) - \strlen($second['normalized']) + : ( + $this->configuration['case_sensitive'] + ? $first['normalized'] <=> $second['normalized'] + : strcasecmp($first['normalized'], $second['normalized']) + ); + + if (self::DIRECTION_DESCEND === $this->configuration[self::OPTION_DIRECTION]) { + $score *= -1; + } + + return $score; + }); + + $changed = false; + + foreach ($interfaces as $interfaceIndex => $interface) { + if ($interface['originalIndex'] !== $interfaceIndex) { + $changed = true; + + break; + } + } + + if (!$changed) { + continue; + } + + $newTokens = array_shift($interfaces)['tokens']; + + foreach ($interfaces as $interface) { + array_push($newTokens, new Token(','), ...$interface['tokens']); + } + + $tokens->overrideRange($implementsStart, $implementsEnd, $newTokens); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder(self::OPTION_ORDER, 'How the interfaces should be ordered.')) + ->setAllowedValues(self::SUPPORTED_ORDER_OPTIONS) + ->setDefault(self::ORDER_ALPHA) + ->getOption(), + (new FixerOptionBuilder(self::OPTION_DIRECTION, 'Which direction the interfaces should be ordered.')) + ->setAllowedValues(self::SUPPORTED_DIRECTION_OPTIONS) + ->setDefault(self::DIRECTION_ASCEND) + ->getOption(), + (new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * @return array> + */ + private function getInterfaces(Tokens $tokens, int $implementsStart, int $implementsEnd): array + { + $interfaces = []; + $interfaceIndex = 0; + + for ($i = $implementsStart; $i <= $implementsEnd; ++$i) { + if ($tokens[$i]->equals(',')) { + ++$interfaceIndex; + $interfaces[$interfaceIndex] = []; + + continue; + } + + $interfaces[$interfaceIndex][] = $tokens[$i]; + } + + return $interfaces; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTraitsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTraitsFixer.php new file mode 100644 index 00000000..8d359f66 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTraitsFixer.php @@ -0,0 +1,212 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +final class OrderedTraitsFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Trait `use` statements must be sorted alphabetically.', + [ + new CodeSample(" true, + ] + ), + ], + null, + 'Risky when depending on order of the imports.' + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(CT::T_USE_TRAIT); + } + + public function isRisky(): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($this->findUseStatementsGroups($tokens) as $uses) { + $this->sortUseStatements($tokens, $uses); + } + } + + /** + * @return iterable> + */ + private function findUseStatementsGroups(Tokens $tokens): iterable + { + $uses = []; + + for ($index = 1, $max = \count($tokens); $index < $max; ++$index) { + $token = $tokens[$index]; + + if ($token->isWhitespace() || $token->isComment()) { + continue; + } + + if (!$token->isGivenKind(CT::T_USE_TRAIT)) { + if (\count($uses) > 0) { + yield $uses; + + $uses = []; + } + + continue; + } + + $startIndex = $tokens->getNextNonWhitespace($tokens->getPrevMeaningfulToken($index)); + $endIndex = $tokens->getNextTokenOfKind($index, [';', '{']); + + if ($tokens[$endIndex]->equals('{')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $endIndex); + } + + $use = []; + + for ($i = $startIndex; $i <= $endIndex; ++$i) { + $use[] = $tokens[$i]; + } + + $uses[$startIndex] = Tokens::fromArray($use); + + $index = $endIndex; + } + } + + /** + * @param array $uses + */ + private function sortUseStatements(Tokens $tokens, array $uses): void + { + foreach ($uses as $use) { + $this->sortMultipleTraitsInStatement($use); + } + + $this->sort($tokens, $uses); + } + + private function sortMultipleTraitsInStatement(Tokens $use): void + { + $traits = []; + $indexOfName = null; + $name = []; + + for ($index = 0, $max = \count($use); $index < $max; ++$index) { + $token = $use[$index]; + + if ($token->isGivenKind([T_STRING, T_NS_SEPARATOR])) { + $name[] = $token; + + if (null === $indexOfName) { + $indexOfName = $index; + } + + continue; + } + + if ($token->equalsAny([',', ';', '{'])) { + $traits[$indexOfName] = Tokens::fromArray($name); + + $name = []; + $indexOfName = null; + } + + if ($token->equals('{')) { + $index = $use->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + } + } + + $this->sort($use, $traits); + } + + /** + * @param array $elements + */ + private function sort(Tokens $tokens, array $elements): void + { + $toTraitName = static function (Tokens $use): string { + $string = ''; + + foreach ($use as $token) { + if ($token->equalsAny([';', '{'])) { + break; + } + + if ($token->isGivenKind([T_NS_SEPARATOR, T_STRING])) { + $string .= $token->getContent(); + } + } + + return ltrim($string, '\\'); + }; + + $sortedElements = $elements; + uasort( + $sortedElements, + fn (Tokens $useA, Tokens $useB): int => $this->configuration['case_sensitive'] + ? $toTraitName($useA) <=> $toTraitName($useB) + : strcasecmp($toTraitName($useA), $toTraitName($useB)) + ); + + $sortedElements = array_combine( + array_keys($elements), + array_values($sortedElements) + ); + + $beforeOverrideCount = $tokens->count(); + + foreach (array_reverse($sortedElements, true) as $index => $tokensToInsert) { + $tokens->overrideRange( + $index, + $index + \count($elements[$index]) - 1, + $tokensToInsert + ); + } + + if ($beforeOverrideCount < $tokens->count()) { + $tokens->clearEmptyTokens(); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTypesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTypesFixer.php new file mode 100644 index 00000000..d8418e57 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTypesFixer.php @@ -0,0 +1,436 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author John Paul E. Balandan, CPA + */ +final class OrderedTypesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Sort union types and intersection types using configured order.', + [ + new CodeSample( + 'save($foo); +} catch (\RuntimeException|CacheException $e) { + logger($e); + + throw $e; +} +' + ), + new VersionSpecificCodeSample( + ' true, + ] + ), + new VersionSpecificCodeSample( + ' 'always_last'] + ), + new VersionSpecificCodeSample( + ' 'none', + 'null_adjustment' => 'always_last', + ] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before TypesSpacesFixer. + * Must run after NullableTypeDeclarationFixer, NullableTypeDeclarationForDefaultNullValueFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('sort_algorithm', 'Whether the types should be sorted alphabetically, or not sorted.')) + ->setAllowedValues(['alpha', 'none']) + ->setDefault('alpha') + ->getOption(), + (new FixerOptionBuilder('null_adjustment', 'Forces the position of `null` (overrides `sort_algorithm`).')) + ->setAllowedValues(['always_first', 'always_last', 'none']) + ->setDefault('always_first') + ->getOption(), + (new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + foreach ($this->getElements($tokens) as $index => $type) { + if ('catch' === $type) { + $this->fixCatchArgumentType($tokens, $index); + + continue; + } + + if ('property' === $type) { + $this->fixPropertyType($tokens, $index); + + continue; + } + + $this->fixMethodArgumentType($functionsAnalyzer, $tokens, $index); + $this->fixMethodReturnType($functionsAnalyzer, $tokens, $index); + } + } + + /** + * @return array + * + * @phpstan-return array + */ + private function getElements(Tokens $tokens): array + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $elements = array_map( + static fn (array $element): string => $element['type'], + array_filter( + $tokensAnalyzer->getClassyElements(), + static fn (array $element): bool => \in_array($element['type'], ['method', 'property'], true) + ) + ); + + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(T_CATCH)) { + $elements[$index] = 'catch'; + + continue; + } + + if ( + $token->isGivenKind(T_FN) + || ($token->isGivenKind(T_FUNCTION) && !isset($elements[$index])) + ) { + $elements[$index] = 'method'; + } + } + + return $elements; + } + + private function collectTypeAnalysis(Tokens $tokens, int $startIndex, int $endIndex): ?TypeAnalysis + { + $type = ''; + $typeStartIndex = $tokens->getNextMeaningfulToken($startIndex); + $typeEndIndex = $typeStartIndex; + + for ($i = $typeStartIndex; $i < $endIndex; ++$i) { + if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { + continue; + } + + $type .= $tokens[$i]->getContent(); + $typeEndIndex = $i; + } + + return '' !== $type ? new TypeAnalysis($type, $typeStartIndex, $typeEndIndex) : null; + } + + private function fixCatchArgumentType(Tokens $tokens, int $index): void + { + $catchStart = $tokens->getNextTokenOfKind($index, ['(']); + $catchEnd = $tokens->getNextTokenOfKind($catchStart, [')', [T_VARIABLE]]); + + $catchArgumentType = $this->collectTypeAnalysis($tokens, $catchStart, $catchEnd); + + if (null === $catchArgumentType || !$this->isTypeSortable($catchArgumentType)) { + return; // nothing to fix + } + + $this->sortTypes($catchArgumentType, $tokens); + } + + private function fixPropertyType(Tokens $tokens, int $index): void + { + $propertyIndex = $index; + $propertyModifiers = [T_PRIVATE, T_PROTECTED, T_PUBLIC, T_STATIC, T_VAR]; + + if (\defined('T_READONLY')) { + $propertyModifiers[] = T_READONLY; // @TODO drop condition when PHP 8.1 is supported + } + + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while (!$tokens[$index]->isGivenKind($propertyModifiers)); + + $propertyType = $this->collectTypeAnalysis($tokens, $index, $propertyIndex); + + if (null === $propertyType || !$this->isTypeSortable($propertyType)) { + return; // nothing to fix + } + + $this->sortTypes($propertyType, $tokens); + } + + private function fixMethodArgumentType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void + { + foreach ($functionsAnalyzer->getFunctionArguments($tokens, $index) as $argumentInfo) { + $argumentType = $argumentInfo->getTypeAnalysis(); + + if (null === $argumentType || !$this->isTypeSortable($argumentType)) { + continue; // nothing to fix + } + + $this->sortTypes($argumentType, $tokens); + } + } + + private function fixMethodReturnType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void + { + $returnType = $functionsAnalyzer->getFunctionReturnType($tokens, $index); + + if (null === $returnType || !$this->isTypeSortable($returnType)) { + return; // nothing to fix + } + + $this->sortTypes($returnType, $tokens); + } + + private function sortTypes(TypeAnalysis $typeAnalysis, Tokens $tokens): void + { + $type = $typeAnalysis->getName(); + + if (str_contains($type, '|') && str_contains($type, '&')) { + // a DNF type of the form (A&B)|C, available as of PHP 8.2 + [$originalTypes, $glue] = $this->collectDisjunctiveNormalFormTypes($type); + } else { + [$originalTypes, $glue] = $this->collectUnionOrIntersectionTypes($type); + } + + // If the $types array is coming from a DNF type, then we have parts + // which are also array. If so, we sort those sub-types first before + // running the sorting algorithm to the entire $types array. + $sortedTypes = array_map(function ($subType) { + if (\is_array($subType)) { + return $this->runTypesThroughSortingAlgorithm($subType); + } + + return $subType; + }, $originalTypes); + + $sortedTypes = $this->runTypesThroughSortingAlgorithm($sortedTypes); + + if ($sortedTypes === $originalTypes) { + return; + } + + $tokens->overrideRange( + $typeAnalysis->getStartIndex(), + $typeAnalysis->getEndIndex(), + $this->createTypeDeclarationTokens($sortedTypes, $glue) + ); + } + + private function isTypeSortable(TypeAnalysis $type): bool + { + return str_contains($type->getName(), '|') || str_contains($type->getName(), '&'); + } + + /** + * @return array{0: array, 1: string} + */ + private function collectDisjunctiveNormalFormTypes(string $type): array + { + $types = array_map(static function ($subType) { + if (str_starts_with($subType, '(')) { + return explode('&', trim($subType, '()')); + } + + return $subType; + }, explode('|', $type)); + + return [$types, '|']; + } + + /** + * @return array{0: string[], 1: string} + */ + private function collectUnionOrIntersectionTypes(string $type): array + { + $types = explode('|', $type); + $glue = '|'; + + if (1 === \count($types)) { + $types = explode('&', $type); + $glue = '&'; + } + + return [$types, $glue]; + } + + /** + * @param array $types + * + * @return array + */ + private function runTypesThroughSortingAlgorithm(array $types): array + { + $normalizeType = static fn (string $type): string => Preg::replace('/^\\\\?/', '', $type); + + usort($types, function ($a, $b) use ($normalizeType): int { + if (\is_array($a)) { + $a = implode('&', $a); + } + + if (\is_array($b)) { + $b = implode('&', $b); + } + + $a = $normalizeType($a); + $b = $normalizeType($b); + $lowerCaseA = strtolower($a); + $lowerCaseB = strtolower($b); + + if ('none' !== $this->configuration['null_adjustment']) { + if ('null' === $lowerCaseA && 'null' !== $lowerCaseB) { + return 'always_last' === $this->configuration['null_adjustment'] ? 1 : -1; + } + + if ('null' !== $lowerCaseA && 'null' === $lowerCaseB) { + return 'always_last' === $this->configuration['null_adjustment'] ? -1 : 1; + } + } + + if ('alpha' === $this->configuration['sort_algorithm']) { + return $this->configuration['case_sensitive'] ? $a <=> $b : strcasecmp($a, $b); + } + + return 0; + }); + + return $types; + } + + /** + * @param array $types + * + * @return array + */ + private function createTypeDeclarationTokens(array $types, string $glue, bool $isDisjunctive = false): array + { + static $specialTypes = [ + 'array' => [CT::T_ARRAY_TYPEHINT, 'array'], + 'callable' => [T_CALLABLE, 'callable'], + 'static' => [T_STATIC, 'static'], + ]; + + static $glues = [ + '|' => [CT::T_TYPE_ALTERNATION, '|'], + '&' => [CT::T_TYPE_INTERSECTION, '&'], + ]; + + $count = \count($types); + $newTokens = []; + + foreach ($types as $i => $type) { + if (\is_array($type)) { + $newTokens = [ + ...$newTokens, + ...$this->createTypeDeclarationTokens($type, '&', true), + ]; + } elseif (isset($specialTypes[$type])) { + $newTokens[] = new Token($specialTypes[$type]); + } else { + foreach (explode('\\', $type) as $nsIndex => $value) { + if (0 === $nsIndex && '' === $value) { + continue; + } + + if ($nsIndex > 0) { + $newTokens[] = new Token([T_NS_SEPARATOR, '\\']); + } + + $newTokens[] = new Token([T_STRING, $value]); + } + } + + if ($i <= $count - 2) { + $newTokens[] = new Token($glues[$glue]); + } + } + + if ($isDisjunctive) { + array_unshift($newTokens, new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '('])); + $newTokens[] = new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')']); + } + + return $newTokens; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/PhpdocReadonlyClassCommentToKeywordFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/PhpdocReadonlyClassCommentToKeywordFixer.php new file mode 100644 index 00000000..78916047 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/PhpdocReadonlyClassCommentToKeywordFixer.php @@ -0,0 +1,129 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Marcel Behrmann + */ +final class PhpdocReadonlyClassCommentToKeywordFixer extends AbstractFixer +{ + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, NoExtraBlankLinesFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 4; + } + + public function isCandidate(Tokens $tokens): bool + { + return \PHP_VERSION_ID >= 8_02_00 && $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + public function isRisky(): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts readonly comment on classes to the readonly keyword.', + [ + new VersionSpecificCodeSample( + << $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + + $annotations = $doc->getAnnotationsOfType('readonly'); + + if (0 === \count($annotations)) { + continue; + } + + foreach ($annotations as $annotation) { + $annotation->remove(); + } + + $mainIndex = $index; + $index = $tokens->getNextMeaningfulToken($index); + $addReadonly = true; + + while ($tokens[$index]->isGivenKind([ + T_ABSTRACT, + T_FINAL, + T_PRIVATE, + T_PUBLIC, + T_PROTECTED, + T_READONLY, + ])) { + if ($tokens[$index]->isGivenKind([T_READONLY])) { + $addReadonly = false; + } + + $index = $tokens->getNextMeaningfulToken($index); + } + + if (!$tokens[$index]->isGivenKind(T_CLASS)) { + continue; + } + + if ($addReadonly) { + $tokens->insertAt($index, [new Token([T_READONLY, 'readonly']), new Token([T_WHITESPACE, ' '])]); + } + + $newContent = $doc->getContent(); + + if ('' === $newContent) { + $tokens->clearTokenAndMergeSurroundingWhitespace($mainIndex); + + continue; + } + + $tokens[$mainIndex] = new Token([T_DOC_COMMENT, $doc->getContent()]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ProtectedToPrivateFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ProtectedToPrivateFixer.php new file mode 100644 index 00000000..168bbb3b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ProtectedToPrivateFixer.php @@ -0,0 +1,170 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Filippo Tessarotto + */ +final class ProtectedToPrivateFixer extends AbstractFixer +{ + private TokensAnalyzer $tokensAnalyzer; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts `protected` variables and methods to `private` where possible.', + [ + new CodeSample( + 'isAllTokenKindsFound([T_ENUM, T_PROTECTED])) { // @TODO: drop condition when PHP 8.1+ is required + return true; + } + + return $tokens->isAllTokenKindsFound([T_CLASS, T_FINAL, T_PROTECTED]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + $modifierKinds = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FINAL, T_ABSTRACT, T_NS_SEPARATOR, T_STRING, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, T_STATIC, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]; + + if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required + $modifierKinds[] = T_READONLY; + } + + $classesCandidate = []; + $classElementTypes = ['method' => true, 'property' => true, 'const' => true]; + + foreach ($this->tokensAnalyzer->getClassyElements() as $index => $element) { + $classIndex = $element['classIndex']; + + if (!\array_key_exists($classIndex, $classesCandidate)) { + $classesCandidate[$classIndex] = $this->isClassCandidate($tokens, $classIndex); + } + + if (false === $classesCandidate[$classIndex]) { + continue; + } + + if (!isset($classElementTypes[$element['type']])) { + continue; + } + + $previous = $index; + $isProtected = false; + $isFinal = false; + + do { + $previous = $tokens->getPrevMeaningfulToken($previous); + + if ($tokens[$previous]->isGivenKind(T_PROTECTED)) { + $isProtected = $previous; + } elseif ($tokens[$previous]->isGivenKind(T_FINAL)) { + $isFinal = $previous; + } + } while ($tokens[$previous]->isGivenKind($modifierKinds)); + + if (false === $isProtected) { + continue; + } + + if ($isFinal && 'const' === $element['type']) { + continue; // Final constants cannot be private + } + + $element['protected_index'] = $isProtected; + $tokens[$element['protected_index']] = new Token([T_PRIVATE, 'private']); + } + } + + /** + * Consider symbol as candidate for fixing if it's: + * - an Enum (PHP8.1+) + * - a class, which: + * - is not anonymous + * - is not final + * - does not use traits + * - does not extend other class. + */ + private function isClassCandidate(Tokens $tokens, int $classIndex): bool + { + if (\defined('T_ENUM') && $tokens[$classIndex]->isGivenKind(T_ENUM)) { // @TODO: drop condition when PHP 8.1+ is required + return true; + } + + if (!$tokens[$classIndex]->isGivenKind(T_CLASS) || $this->tokensAnalyzer->isAnonymousClass($classIndex)) { + return false; + } + + $modifiers = $this->tokensAnalyzer->getClassyModifiers($classIndex); + + if (!isset($modifiers['final'])) { + return false; + } + + $classNameIndex = $tokens->getNextMeaningfulToken($classIndex); // move to class name as anonymous class is never "final" + $classExtendsIndex = $tokens->getNextMeaningfulToken($classNameIndex); // move to possible "extends" + + if ($tokens[$classExtendsIndex]->isGivenKind(T_EXTENDS)) { + return false; + } + + if (!$tokens->isTokenKindFound(CT::T_USE_TRAIT)) { + return true; // cheap test + } + + $classOpenIndex = $tokens->getNextTokenOfKind($classNameIndex, ['{']); + $classCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpenIndex); + $useIndex = $tokens->getNextTokenOfKind($classOpenIndex, [[CT::T_USE_TRAIT]]); + + return null === $useIndex || $useIndex > $classCloseIndex; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfAccessorFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfAccessorFixer.php new file mode 100644 index 00000000..1ad573c9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfAccessorFixer.php @@ -0,0 +1,200 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Gregor Harlan + */ +final class SelfAccessorFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Inside class or interface element `self` should be preferred to the class name itself.', + [ + new CodeSample( + 'isAnyTokenKindsFound([T_CLASS, T_INTERFACE]); + } + + /** + * {@inheritdoc} + * + * Must run after PsrAutoloadingFixer. + */ + public function getPriority(): int + { + return -11; + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + foreach ($tokens->getNamespaceDeclarations() as $namespace) { + for ($index = $namespace->getScopeStartIndex(); $index < $namespace->getScopeEndIndex(); ++$index) { + if (!$tokens[$index]->isGivenKind([T_CLASS, T_INTERFACE]) || $tokensAnalyzer->isAnonymousClass($index)) { + continue; + } + + $nameIndex = $tokens->getNextTokenOfKind($index, [[T_STRING]]); + $startIndex = $tokens->getNextTokenOfKind($nameIndex, ['{']); + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex); + + $name = $tokens[$nameIndex]->getContent(); + + $this->replaceNameOccurrences($tokens, $namespace->getFullName(), $name, $startIndex, $endIndex); + + $index = $endIndex; + } + } + } + + /** + * Replace occurrences of the name of the classy element by "self" (if possible). + */ + private function replaceNameOccurrences(Tokens $tokens, string $namespace, string $name, int $startIndex, int $endIndex): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $insideMethodSignatureUntil = null; + + for ($i = $startIndex; $i < $endIndex; ++$i) { + if ($i === $insideMethodSignatureUntil) { + $insideMethodSignatureUntil = null; + } + + $token = $tokens[$i]; + + // skip anonymous classes + if ($token->isGivenKind(T_CLASS) && $tokensAnalyzer->isAnonymousClass($i)) { + $i = $tokens->getNextTokenOfKind($i, ['{']); + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $i); + + continue; + } + + if ($token->isGivenKind(T_FN)) { + $i = $tokensAnalyzer->getLastTokenIndexOfArrowFunction($i); + $i = $tokens->getNextMeaningfulToken($i); + + continue; + } + + if ($token->isGivenKind(T_FUNCTION)) { + if ($tokensAnalyzer->isLambda($i)) { + $i = $tokens->getNextTokenOfKind($i, ['{']); + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $i); + + continue; + } + + $i = $tokens->getNextTokenOfKind($i, ['(']); + $insideMethodSignatureUntil = $tokens->getNextTokenOfKind($i, ['{', ';']); + + continue; + } + + if (!$token->equals([T_STRING, $name], false)) { + continue; + } + + $nextToken = $tokens[$tokens->getNextMeaningfulToken($i)]; + if ($nextToken->isGivenKind(T_NS_SEPARATOR)) { + continue; + } + + $classStartIndex = $i; + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($i)]; + if ($prevToken->isGivenKind(T_NS_SEPARATOR)) { + $classStartIndex = $this->getClassStart($tokens, $i, $namespace); + if (null === $classStartIndex) { + continue; + } + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($classStartIndex)]; + } + if ($prevToken->isGivenKind(T_STRING) || $prevToken->isObjectOperator()) { + continue; + } + + if ( + $prevToken->isGivenKind([T_INSTANCEOF, T_NEW]) + || $nextToken->isGivenKind(T_PAAMAYIM_NEKUDOTAYIM) + || ( + null !== $insideMethodSignatureUntil + && $i < $insideMethodSignatureUntil + && $prevToken->equalsAny(['(', ',', [CT::T_NULLABLE_TYPE], [CT::T_TYPE_ALTERNATION], [CT::T_TYPE_COLON]]) + ) + ) { + for ($j = $classStartIndex; $j < $i; ++$j) { + $tokens->clearTokenAndMergeSurroundingWhitespace($j); + } + $tokens[$i] = new Token([T_STRING, 'self']); + } + } + } + + private function getClassStart(Tokens $tokens, int $index, string $namespace): ?int + { + $namespace = ('' !== $namespace ? '\\'.$namespace : '').'\\'; + + foreach (array_reverse(Preg::split('/(\\\\)/', $namespace, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)) as $piece) { + $index = $tokens->getPrevMeaningfulToken($index); + if ('\\' === $piece) { + if (!$tokens[$index]->isGivenKind(T_NS_SEPARATOR)) { + return null; + } + } elseif (!$tokens[$index]->equals([T_STRING, $piece], false)) { + return null; + } + } + + return $index; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfStaticAccessorFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfStaticAccessorFixer.php new file mode 100644 index 00000000..0bf56ab0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfStaticAccessorFixer.php @@ -0,0 +1,224 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +final class SelfStaticAccessorFixer extends AbstractFixer +{ + private TokensAnalyzer $tokensAnalyzer; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Inside an enum or `final`/anonymous class, `self` should be preferred over `static`.', + [ + new CodeSample( + 'isTokenKindFound(T_STATIC) + && $tokens->isAnyTokenKindsFound($classyTypes) + && $tokens->isAnyTokenKindsFound([T_DOUBLE_COLON, T_NEW, T_INSTANCEOF]); + } + + /** + * {@inheritdoc} + * + * Must run after FinalClassFixer, FinalInternalClassFixer, FunctionToConstantFixer, PhpUnitTestCaseStaticMethodCallsFixer. + */ + public function getPriority(): int + { + return -10; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $classyTokensOfInterest = [[T_CLASS]]; + + if (\defined('T_ENUM')) { + $classyTokensOfInterest[] = [T_ENUM]; // @TODO drop condition when PHP 8.1+ is required + } + + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + $classyIndex = $tokens->getNextTokenOfKind(0, $classyTokensOfInterest); + + while (null !== $classyIndex) { + if ($tokens[$classyIndex]->isGivenKind(T_CLASS)) { + $modifiers = $this->tokensAnalyzer->getClassyModifiers($classyIndex); + + if ( + isset($modifiers['final']) + || $this->tokensAnalyzer->isAnonymousClass($classyIndex) + ) { + $classyIndex = $this->fixClassy($tokens, $classyIndex); + } + } else { + $classyIndex = $this->fixClassy($tokens, $classyIndex); + } + + $classyIndex = $tokens->getNextTokenOfKind($classyIndex, $classyTokensOfInterest); + } + } + + private function fixClassy(Tokens $tokens, int $index): int + { + $index = $tokens->getNextTokenOfKind($index, ['{']); + $classOpenCount = 1; + + while ($classOpenCount > 0) { + ++$index; + + if ($tokens[$index]->equals('{')) { + ++$classOpenCount; + + continue; + } + + if ($tokens[$index]->equals('}')) { + --$classOpenCount; + + continue; + } + + if ($tokens[$index]->isGivenKind(T_FUNCTION)) { + // do not fix inside lambda + if ($this->tokensAnalyzer->isLambda($index)) { + // figure out where the lambda starts + $index = $tokens->getNextTokenOfKind($index, ['{']); + $openCount = 1; + + do { + $index = $tokens->getNextTokenOfKind($index, ['}', '{', [T_CLASS]]); + if ($tokens[$index]->equals('}')) { + --$openCount; + } elseif ($tokens[$index]->equals('{')) { + ++$openCount; + } else { + $index = $this->fixClassy($tokens, $index); + } + } while ($openCount > 0); + } + + continue; + } + + if ($tokens[$index]->isGivenKind([T_NEW, T_INSTANCEOF])) { + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(T_STATIC)) { + $tokens[$index] = new Token([T_STRING, 'self']); + } + + continue; + } + + if (!$tokens[$index]->isGivenKind(T_STATIC)) { + continue; + } + + $staticIndex = $index; + $index = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$index]->isGivenKind(T_DOUBLE_COLON)) { + continue; + } + + $tokens[$staticIndex] = new Token([T_STRING, 'self']); + } + + return $index; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php new file mode 100644 index 00000000..2eed2464 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php @@ -0,0 +1,228 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * Fixer for rules defined in PSR2 ¶4.2. + * + * @author Javier Spagnoletti + * @author Dariusz Rumiński + */ +final class SingleClassElementPerStatementFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + /** + * {@inheritdoc} + * + * Must run before ClassAttributesSeparationFixer. + */ + public function getPriority(): int + { + return 56; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There MUST NOT be more than one property or constant declared per statement.', + [ + new CodeSample( + ' ['property']] + ), + ] + ); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $analyzer = new TokensAnalyzer($tokens); + $elements = array_reverse($analyzer->getClassyElements(), true); + + foreach ($elements as $index => $element) { + if (!\in_array($element['type'], $this->configuration['elements'], true)) { + continue; // not in configuration + } + + $this->fixElement($tokens, $element['type'], $index); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $values = ['const', 'property']; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('elements', 'List of strings which element should be modified.')) + ->setDefault($values) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset($values)]) + ->getOption(), + ]); + } + + private function fixElement(Tokens $tokens, string $type, int $index): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $repeatIndex = $index; + + while (true) { + $repeatIndex = $tokens->getNextMeaningfulToken($repeatIndex); + $repeatToken = $tokens[$repeatIndex]; + + if ($tokensAnalyzer->isArray($repeatIndex)) { + if ($repeatToken->isGivenKind(T_ARRAY)) { + $repeatIndex = $tokens->getNextTokenOfKind($repeatIndex, ['(']); + $repeatIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $repeatIndex); + } else { + $repeatIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $repeatIndex); + } + + continue; + } + + if ($repeatToken->equals(';')) { + return; // no repeating found, no fixing needed + } + + if ($repeatToken->equals(',')) { + break; + } + } + + $start = $tokens->getPrevTokenOfKind($index, [';', '{', '}']); + $this->expandElement( + $tokens, + $type, + $tokens->getNextMeaningfulToken($start), + $tokens->getNextTokenOfKind($index, [';']) + ); + } + + private function expandElement(Tokens $tokens, string $type, int $startIndex, int $endIndex): void + { + $divisionContent = null; + + if ($tokens[$startIndex - 1]->isWhitespace()) { + $divisionContent = $tokens[$startIndex - 1]->getContent(); + + if (Preg::match('#(\n|\r\n)#', $divisionContent, $matches)) { + $divisionContent = $matches[0].trim($divisionContent, "\r\n"); + } + } + + // iterate variables to split up + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + $token = $tokens[$i]; + + if ($token->equals(')')) { + $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $i); + + continue; + } + + if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_CLOSE)) { + $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $i); + + continue; + } + + if (!$tokens[$i]->equals(',')) { + continue; + } + + $tokens[$i] = new Token(';'); + + if ($tokens[$i + 1]->isWhitespace()) { + $tokens->clearAt($i + 1); + } + + if (null !== $divisionContent && '' !== $divisionContent) { + $tokens->insertAt($i + 1, new Token([T_WHITESPACE, $divisionContent])); + } + + // collect modifiers + $sequence = $this->getModifiersSequences($tokens, $type, $startIndex, $endIndex); + $tokens->insertAt($i + 2, $sequence); + } + } + + /** + * @return Token[] + */ + private function getModifiersSequences(Tokens $tokens, string $type, int $startIndex, int $endIndex): array + { + if ('property' === $type) { + $tokenKinds = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_STATIC, T_VAR, T_STRING, T_NS_SEPARATOR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]; + + if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required + $tokenKinds[] = T_READONLY; + } + } else { + $tokenKinds = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_CONST]; + } + + $sequence = []; + + for ($i = $startIndex; $i < $endIndex - 1; ++$i) { + if ($tokens[$i]->isComment()) { + continue; + } + + if (!$tokens[$i]->isWhitespace() && !$tokens[$i]->isGivenKind($tokenKinds)) { + break; + } + + $sequence[] = clone $tokens[$i]; + } + + return $sequence; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php new file mode 100644 index 00000000..ec20f3ca --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php @@ -0,0 +1,116 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class SingleTraitInsertPerStatementFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Each trait `use` must be done as single statement.', + [ + new CodeSample( + 'isTokenKindFound(CT::T_USE_TRAIT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; 1 < $index; --$index) { + if ($tokens[$index]->isGivenKind(CT::T_USE_TRAIT)) { + $candidates = $this->getCandidates($tokens, $index); + if (\count($candidates) > 0) { + $this->fixTraitUse($tokens, $index, $candidates); + } + } + } + } + + /** + * @param int[] $candidates ',' indices to fix + */ + private function fixTraitUse(Tokens $tokens, int $useTraitIndex, array $candidates): void + { + foreach ($candidates as $commaIndex) { + $inserts = [ + new Token([CT::T_USE_TRAIT, 'use']), + new Token([T_WHITESPACE, ' ']), + ]; + + $nextImportStartIndex = $tokens->getNextMeaningfulToken($commaIndex); + + if ($tokens[$nextImportStartIndex - 1]->isWhitespace()) { + if (Preg::match('/\R/', $tokens[$nextImportStartIndex - 1]->getContent())) { + array_unshift($inserts, clone $tokens[$useTraitIndex - 1]); + } + $tokens->clearAt($nextImportStartIndex - 1); + } + + $tokens[$commaIndex] = new Token(';'); + $tokens->insertAt($nextImportStartIndex, $inserts); + } + } + + /** + * @return int[] + */ + private function getCandidates(Tokens $tokens, int $index): array + { + $indices = []; + $index = $tokens->getNextTokenOfKind($index, [',', ';', '{']); + + while (!$tokens[$index]->equals(';')) { + if ($tokens[$index]->equals('{')) { + return []; // do not fix use cases with grouping + } + + $indices[] = $index; + $index = $tokens->getNextTokenOfKind($index, [',', ';', '{']); + } + + return array_reverse($indices); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/VisibilityRequiredFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/VisibilityRequiredFixer.php new file mode 100644 index 00000000..d98168c8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/VisibilityRequiredFixer.php @@ -0,0 +1,199 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * Fixer for rules defined in PSR2 ¶4.3, ¶4.5. + * + * @author Dariusz Rumiński + */ +final class VisibilityRequiredFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Visibility MUST be declared on all properties and methods; `abstract` and `final` MUST be declared before the visibility; `static` MUST be declared after the visibility.', + [ + new CodeSample( + ' ['const']] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before ClassAttributesSeparationFixer. + */ + public function getPriority(): int + { + return 56; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('elements', 'The structural elements to fix (PHP >= 7.1 required for `const`).')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset(['property', 'method', 'const'])]) + ->setDefault(['property', 'method', 'const']) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $propertyTypeDeclarationKinds = [T_STRING, T_NS_SEPARATOR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE]; + + if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required + $propertyReadOnlyType = T_READONLY; + $propertyTypeDeclarationKinds[] = T_READONLY; + } else { + $propertyReadOnlyType = -999; + } + + $expectedKindsGeneric = [T_ABSTRACT, T_FINAL, T_PRIVATE, T_PROTECTED, T_PUBLIC, T_STATIC, T_VAR]; + $expectedKindsPropertyKinds = [...$expectedKindsGeneric, ...$propertyTypeDeclarationKinds]; + + foreach (array_reverse($tokensAnalyzer->getClassyElements(), true) as $index => $element) { + if (!\in_array($element['type'], $this->configuration['elements'], true)) { + continue; + } + + $abstractFinalIndex = null; + $visibilityIndex = null; + $staticIndex = null; + $typeIndex = null; + $readOnlyIndex = null; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $expectedKinds = 'property' === $element['type'] + ? $expectedKindsPropertyKinds + : $expectedKindsGeneric; + + while ($tokens[$prevIndex]->isGivenKind($expectedKinds)) { + if ($tokens[$prevIndex]->isGivenKind([T_ABSTRACT, T_FINAL])) { + $abstractFinalIndex = $prevIndex; + } elseif ($tokens[$prevIndex]->isGivenKind(T_STATIC)) { + $staticIndex = $prevIndex; + } elseif ($tokens[$prevIndex]->isGivenKind($propertyReadOnlyType)) { + $readOnlyIndex = $prevIndex; + } elseif ($tokens[$prevIndex]->isGivenKind($propertyTypeDeclarationKinds)) { + $typeIndex = $prevIndex; + } else { + $visibilityIndex = $prevIndex; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + } + + if (null !== $typeIndex) { + $index = $typeIndex; + } + + if ($tokens[$prevIndex]->equals(',')) { + continue; + } + + $swapIndex = $staticIndex ?? $readOnlyIndex; // "static" property cannot be "readonly", so there can always be at most one swap + + if (null !== $swapIndex) { + if ($this->isKeywordPlacedProperly($tokens, $swapIndex, $index)) { + $index = $swapIndex; + } else { + $this->moveTokenAndEnsureSingleSpaceFollows($tokens, $swapIndex, $index); + } + } + + if (null === $visibilityIndex) { + $tokens->insertAt($index, [new Token([T_PUBLIC, 'public']), new Token([T_WHITESPACE, ' '])]); + } else { + if ($tokens[$visibilityIndex]->isGivenKind(T_VAR)) { + $tokens[$visibilityIndex] = new Token([T_PUBLIC, 'public']); + } + if ($this->isKeywordPlacedProperly($tokens, $visibilityIndex, $index)) { + $index = $visibilityIndex; + } else { + $this->moveTokenAndEnsureSingleSpaceFollows($tokens, $visibilityIndex, $index); + } + } + + if (null === $abstractFinalIndex) { + continue; + } + + if ($this->isKeywordPlacedProperly($tokens, $abstractFinalIndex, $index)) { + continue; + } + + $this->moveTokenAndEnsureSingleSpaceFollows($tokens, $abstractFinalIndex, $index); + } + } + + private function isKeywordPlacedProperly(Tokens $tokens, int $keywordIndex, int $comparedIndex): bool + { + return $keywordIndex + 2 === $comparedIndex && ' ' === $tokens[$keywordIndex + 1]->getContent(); + } + + private function moveTokenAndEnsureSingleSpaceFollows(Tokens $tokens, int $fromIndex, int $toIndex): void + { + $tokens->insertAt($toIndex, [$tokens[$fromIndex], new Token([T_WHITESPACE, ' '])]); + $tokens->clearAt($fromIndex); + + if ($tokens[$fromIndex + 1]->isWhitespace()) { + $tokens->clearAt($fromIndex + 1); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassUsage/DateTimeImmutableFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassUsage/DateTimeImmutableFixer.php new file mode 100644 index 00000000..2add0308 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassUsage/DateTimeImmutableFixer.php @@ -0,0 +1,146 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassUsage; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + */ +final class DateTimeImmutableFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Class `DateTimeImmutable` should be used instead of `DateTime`.', + [new CodeSample("isTokenKindFound(T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $functionMap = [ + 'date_create' => 'date_create_immutable', + 'date_create_from_format' => 'date_create_immutable_from_format', + ]; + + $isInNamespace = false; + $isImported = false; // e.g. use DateTime; + + for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(T_NAMESPACE)) { + $isInNamespace = true; + + continue; + } + + if ($isInNamespace && $token->isGivenKind(T_USE)) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if ('datetime' !== strtolower($tokens[$nextIndex]->getContent())) { + continue; + } + + $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); + + if ($tokens[$nextNextIndex]->equals(';')) { + $isImported = true; + } + + $index = $nextNextIndex; + + continue; + } + + if (!$token->isGivenKind(T_STRING)) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prevIndex]->isGivenKind(T_FUNCTION)) { + continue; + } + + $lowercaseContent = strtolower($token->getContent()); + + if ('datetime' === $lowercaseContent) { + $this->fixClassUsage($tokens, $index, $isInNamespace, $isImported); + $limit = $tokens->count(); // update limit, as fixing class usage may insert new token + + continue; + } + + if (isset($functionMap[$lowercaseContent]) && $functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + $tokens[$index] = new Token([T_STRING, $functionMap[$lowercaseContent]]); + } + } + } + + private function fixClassUsage(Tokens $tokens, int $index, bool $isInNamespace, bool $isImported): void + { + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ($tokens[$nextIndex]->isGivenKind(T_DOUBLE_COLON)) { + $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); + if ($tokens[$nextNextIndex]->isGivenKind(T_STRING)) { + $nextNextNextIndex = $tokens->getNextMeaningfulToken($nextNextIndex); + if (!$tokens[$nextNextNextIndex]->equals('(')) { + return; + } + } + } + + $isUsedAlone = false; // e.g. new DateTime(); + $isUsedWithLeadingBackslash = false; // e.g. new \DateTime(); + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { + $prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + if (!$tokens[$prevPrevIndex]->isGivenKind(T_STRING)) { + $isUsedWithLeadingBackslash = true; + } + } elseif (!$tokens[$prevIndex]->isGivenKind(T_DOUBLE_COLON) && !$tokens[$prevIndex]->isObjectOperator()) { + $isUsedAlone = true; + } + + if ($isUsedWithLeadingBackslash || $isUsedAlone && ($isInNamespace && $isImported || !$isInNamespace)) { + $tokens[$index] = new Token([T_STRING, \DateTimeImmutable::class]); + if ($isInNamespace && $isUsedAlone) { + $tokens->insertAt($index, new Token([T_NS_SEPARATOR, '\\'])); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/CommentToPhpdocFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/CommentToPhpdocFixer.php new file mode 100644 index 00000000..61026059 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/CommentToPhpdocFixer.php @@ -0,0 +1,219 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\CommentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Utils; + +/** + * @author Kuba Werłos + */ +final class CommentToPhpdocFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @var string[] + */ + private array $ignoredTags = []; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_COMMENT); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocAnnotationWithoutDotFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagTypeFixer, PhpdocToCommentFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. + * Must run after AlignMultilineCommentFixer. + */ + public function getPriority(): int + { + // Should be run before all other PHPDoc fixers + return 26; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Comments with annotation should be docblock when used on structural elements.', + [ + new CodeSample(" ['todo']]), + ], + null, + 'Risky as new docblocks might mean more, e.g. a Doctrine entity might have a new column in database.' + ); + } + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->ignoredTags = array_map( + static fn (string $tag): string => strtolower($tag), + $this->configuration['ignored_tags'] + ); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('ignored_tags', 'List of ignored tags.')) + ->setAllowedTypes(['array']) + ->setDefault([]) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $commentsAnalyzer = new CommentsAnalyzer(); + + for ($index = 0, $limit = \count($tokens); $index < $limit; ++$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(T_COMMENT)) { + continue; + } + + if ($commentsAnalyzer->isHeaderComment($tokens, $index)) { + continue; + } + + if (!$commentsAnalyzer->isBeforeStructuralElement($tokens, $index)) { + continue; + } + + $commentIndices = $commentsAnalyzer->getCommentBlockIndices($tokens, $index); + + if ($this->isCommentCandidate($tokens, $commentIndices)) { + $this->fixComment($tokens, $commentIndices); + } + + $index = max($commentIndices); + } + } + + /** + * @param int[] $indices + */ + private function isCommentCandidate(Tokens $tokens, array $indices): bool + { + return array_reduce( + $indices, + function (bool $carry, int $index) use ($tokens): bool { + if ($carry) { + return true; + } + if (!Preg::match('~(?:#|//|/\*+|\R(?:\s*\*)?)\s*\@([a-zA-Z0-9_\\\\-]+)(?=\s|\(|$)~', $tokens[$index]->getContent(), $matches)) { + return false; + } + + return !\in_array(strtolower($matches[1]), $this->ignoredTags, true); + }, + false + ); + } + + /** + * @param int[] $indices + */ + private function fixComment(Tokens $tokens, array $indices): void + { + if (1 === \count($indices)) { + $this->fixCommentSingleLine($tokens, reset($indices)); + } else { + $this->fixCommentMultiLine($tokens, $indices); + } + } + + private function fixCommentSingleLine(Tokens $tokens, int $index): void + { + $message = $this->getMessage($tokens[$index]->getContent()); + + if ('' !== trim(substr($message, 0, 1))) { + $message = ' '.$message; + } + + if ('' !== trim(substr($message, -1))) { + $message .= ' '; + } + + $tokens[$index] = new Token([T_DOC_COMMENT, '/**'.$message.'*/']); + } + + /** + * @param int[] $indices + */ + private function fixCommentMultiLine(Tokens $tokens, array $indices): void + { + $startIndex = reset($indices); + $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$startIndex - 1]); + + $newContent = '/**'.$this->whitespacesConfig->getLineEnding(); + $count = max($indices); + + for ($index = $startIndex; $index <= $count; ++$index) { + if (!$tokens[$index]->isComment()) { + continue; + } + if (str_contains($tokens[$index]->getContent(), '*/')) { + return; + } + $message = $this->getMessage($tokens[$index]->getContent()); + if ('' !== trim(substr($message, 0, 1))) { + $message = ' '.$message; + } + $newContent .= $indent.' *'.$message.$this->whitespacesConfig->getLineEnding(); + } + + for ($index = $startIndex; $index <= $count; ++$index) { + $tokens->clearAt($index); + } + + $newContent .= $indent.' */'; + + $tokens->insertAt($startIndex, new Token([T_DOC_COMMENT, $newContent])); + } + + private function getMessage(string $content): string + { + if (str_starts_with($content, '#')) { + return substr($content, 1); + } + if (str_starts_with($content, '//')) { + return substr($content, 2); + } + + return rtrim(ltrim($content, '/*'), '*/'); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/HeaderCommentFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/HeaderCommentFixer.php new file mode 100644 index 00000000..e6da49d8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/HeaderCommentFixer.php @@ -0,0 +1,442 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Options; + +/** + * @author Antonio J. García Lagar + */ +final class HeaderCommentFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @internal + */ + public const HEADER_PHPDOC = 'PHPDoc'; + + /** + * @internal + */ + public const HEADER_COMMENT = 'comment'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Add, replace or remove header comment.', + [ + new CodeSample( + ' 'Made with love.', + ] + ), + new CodeSample( + ' 'Made with love.', + 'comment_type' => 'PHPDoc', + 'location' => 'after_open', + 'separate' => 'bottom', + ] + ), + new CodeSample( + ' 'Made with love.', + 'comment_type' => 'comment', + 'location' => 'after_declare_strict', + ] + ), + new CodeSample( + ' '', + ] + ), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isMonolithicPhp(); + } + + /** + * {@inheritdoc} + * + * Must run before BlankLinesBeforeNamespaceFixer, SingleBlankLineBeforeNamespaceFixer, SingleLineCommentStyleFixer. + * Must run after DeclareStrictTypesFixer, NoBlankLinesAfterPhpdocFixer. + */ + public function getPriority(): int + { + // When this fixer is configured with ["separate" => "bottom", "comment_type" => "PHPDoc"] + // and the target file has no namespace or declare() construct, + // the fixed header comment gets trimmed by NoBlankLinesAfterPhpdocFixer if we run before it. + return -30; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $location = $this->configuration['location']; + $locationIndices = []; + + foreach (['after_open', 'after_declare_strict'] as $possibleLocation) { + $locationIndex = $this->findHeaderCommentInsertionIndex($tokens, $possibleLocation); + + if (!isset($locationIndices[$locationIndex]) || $possibleLocation === $location) { + $locationIndices[$locationIndex] = $possibleLocation; + } + } + + foreach ($locationIndices as $possibleLocation) { + // figure out where the comment should be placed + $headerNewIndex = $this->findHeaderCommentInsertionIndex($tokens, $possibleLocation); + + // check if there is already a comment + $headerCurrentIndex = $this->findHeaderCommentCurrentIndex($tokens, $headerNewIndex - 1); + + if (null === $headerCurrentIndex) { + if ('' === $this->configuration['header'] || $possibleLocation !== $location) { + continue; + } + + $this->insertHeader($tokens, $headerNewIndex); + + continue; + } + + $sameComment = $this->getHeaderAsComment() === $tokens[$headerCurrentIndex]->getContent(); + $expectedLocation = $possibleLocation === $location; + + if (!$sameComment || !$expectedLocation) { + if ($expectedLocation xor $sameComment) { + $this->removeHeader($tokens, $headerCurrentIndex); + } + + if ('' === $this->configuration['header']) { + continue; + } + + if ($possibleLocation === $location) { + $this->insertHeader($tokens, $headerNewIndex); + } + + continue; + } + + $this->fixWhiteSpaceAroundHeader($tokens, $headerCurrentIndex); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $fixerName = $this->getName(); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('header', 'Proper header content.')) + ->setAllowedTypes(['string']) + ->setNormalizer(static function (Options $options, string $value) use ($fixerName): string { + if ('' === trim($value)) { + return ''; + } + + if (str_contains($value, '*/')) { + throw new InvalidFixerConfigurationException($fixerName, 'Cannot use \'*/\' in header.'); + } + + return $value; + }) + ->getOption(), + (new FixerOptionBuilder('comment_type', 'Comment syntax type.')) + ->setAllowedValues([self::HEADER_PHPDOC, self::HEADER_COMMENT]) + ->setDefault(self::HEADER_COMMENT) + ->getOption(), + (new FixerOptionBuilder('location', 'The location of the inserted header.')) + ->setAllowedValues(['after_open', 'after_declare_strict']) + ->setDefault('after_declare_strict') + ->getOption(), + (new FixerOptionBuilder('separate', 'Whether the header should be separated from the file content with a new line.')) + ->setAllowedValues(['both', 'top', 'bottom', 'none']) + ->setDefault('both') + ->getOption(), + ]); + } + + /** + * Enclose the given text in a comment block. + */ + private function getHeaderAsComment(): string + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + $comment = (self::HEADER_COMMENT === $this->configuration['comment_type'] ? '/*' : '/**').$lineEnding; + $lines = explode("\n", str_replace("\r", '', $this->configuration['header'])); + + foreach ($lines as $line) { + $comment .= rtrim(' * '.$line).$lineEnding; + } + + return $comment.' */'; + } + + private function findHeaderCommentCurrentIndex(Tokens $tokens, int $headerNewIndex): ?int + { + $index = $tokens->getNextNonWhitespace($headerNewIndex); + + if (null === $index || !$tokens[$index]->isComment()) { + return null; + } + + $next = $index + 1; + + if (!isset($tokens[$next]) || \in_array($this->configuration['separate'], ['top', 'none'], true) || !$tokens[$index]->isGivenKind(T_DOC_COMMENT)) { + return $index; + } + + if ($tokens[$next]->isWhitespace()) { + if (!Preg::match('/^\h*\R\h*$/D', $tokens[$next]->getContent())) { + return $index; + } + + ++$next; + } + + if (!isset($tokens[$next]) || !$tokens[$next]->isClassy() && !$tokens[$next]->isGivenKind(T_FUNCTION)) { + return $index; + } + + return $this->getHeaderAsComment() === $tokens[$index]->getContent() ? $index : null; + } + + /** + * Find the index where the header comment must be inserted. + */ + private function findHeaderCommentInsertionIndex(Tokens $tokens, string $location): int + { + $openTagIndex = $tokens[0]->isGivenKind(T_OPEN_TAG) ? 0 : $tokens->getNextTokenOfKind(0, [[T_OPEN_TAG]]); + + if (null === $openTagIndex) { + return 1; + } + + if ('after_open' === $location) { + return $openTagIndex + 1; + } + + $index = $tokens->getNextMeaningfulToken($openTagIndex); + + if (null === $index) { + return $openTagIndex + 1; // file without meaningful tokens but an open tag, comment should always be placed directly after the open tag + } + + if (!$tokens[$index]->isGivenKind(T_DECLARE)) { + return $openTagIndex + 1; + } + + $next = $tokens->getNextMeaningfulToken($index); + + if (null === $next || !$tokens[$next]->equals('(')) { + return $openTagIndex + 1; + } + + $next = $tokens->getNextMeaningfulToken($next); + + if (null === $next || !$tokens[$next]->equals([T_STRING, 'strict_types'], false)) { + return $openTagIndex + 1; + } + + $next = $tokens->getNextMeaningfulToken($next); + + if (null === $next || !$tokens[$next]->equals('=')) { + return $openTagIndex + 1; + } + + $next = $tokens->getNextMeaningfulToken($next); + + if (null === $next || !$tokens[$next]->isGivenKind(T_LNUMBER)) { + return $openTagIndex + 1; + } + + $next = $tokens->getNextMeaningfulToken($next); + + if (null === $next || !$tokens[$next]->equals(')')) { + return $openTagIndex + 1; + } + + $next = $tokens->getNextMeaningfulToken($next); + + if (null === $next || !$tokens[$next]->equals(';')) { // don't insert after close tag + return $openTagIndex + 1; + } + + return $next + 1; + } + + private function fixWhiteSpaceAroundHeader(Tokens $tokens, int $headerIndex): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + // fix lines after header comment + if ( + ('both' === $this->configuration['separate'] || 'bottom' === $this->configuration['separate']) + && null !== $tokens->getNextMeaningfulToken($headerIndex) + ) { + $expectedLineCount = 2; + } else { + $expectedLineCount = 1; + } + + if ($headerIndex === \count($tokens) - 1) { + $tokens->insertAt($headerIndex + 1, new Token([T_WHITESPACE, str_repeat($lineEnding, $expectedLineCount)])); + } else { + $lineBreakCount = $this->getLineBreakCount($tokens, $headerIndex, 1); + + if ($lineBreakCount < $expectedLineCount) { + $missing = str_repeat($lineEnding, $expectedLineCount - $lineBreakCount); + + if ($tokens[$headerIndex + 1]->isWhitespace()) { + $tokens[$headerIndex + 1] = new Token([T_WHITESPACE, $missing.$tokens[$headerIndex + 1]->getContent()]); + } else { + $tokens->insertAt($headerIndex + 1, new Token([T_WHITESPACE, $missing])); + } + } elseif ($lineBreakCount > $expectedLineCount && $tokens[$headerIndex + 1]->isWhitespace()) { + $newLinesToRemove = $lineBreakCount - $expectedLineCount; + $tokens[$headerIndex + 1] = new Token([ + T_WHITESPACE, + Preg::replace("/^\\R{{$newLinesToRemove}}/", '', $tokens[$headerIndex + 1]->getContent()), + ]); + } + } + + // fix lines before header comment + $expectedLineCount = 'both' === $this->configuration['separate'] || 'top' === $this->configuration['separate'] ? 2 : 1; + $prev = $tokens->getPrevNonWhitespace($headerIndex); + + $regex = '/\h$/'; + + if ($tokens[$prev]->isGivenKind(T_OPEN_TAG) && Preg::match($regex, $tokens[$prev]->getContent())) { + $tokens[$prev] = new Token([T_OPEN_TAG, Preg::replace($regex, $lineEnding, $tokens[$prev]->getContent())]); + } + + $lineBreakCount = $this->getLineBreakCount($tokens, $headerIndex, -1); + + if ($lineBreakCount < $expectedLineCount) { + // because of the way the insert index was determined for header comment there cannot be an empty token here + $tokens->insertAt($headerIndex, new Token([T_WHITESPACE, str_repeat($lineEnding, $expectedLineCount - $lineBreakCount)])); + } + } + + private function getLineBreakCount(Tokens $tokens, int $index, int $direction): int + { + $whitespace = ''; + + for ($index += $direction; isset($tokens[$index]); $index += $direction) { + $token = $tokens[$index]; + + if ($token->isWhitespace()) { + $whitespace .= $token->getContent(); + + continue; + } + + if (-1 === $direction && $token->isGivenKind(T_OPEN_TAG)) { + $whitespace .= $token->getContent(); + } + + if ('' !== $token->getContent()) { + break; + } + } + + return substr_count($whitespace, "\n"); + } + + private function removeHeader(Tokens $tokens, int $index): void + { + $prevIndex = $index - 1; + $prevToken = $tokens[$prevIndex]; + $newlineRemoved = false; + + if ($prevToken->isWhitespace()) { + $content = $prevToken->getContent(); + + if (Preg::match('/\R/', $content)) { + $newlineRemoved = true; + } + + $content = Preg::replace('/\R?\h*$/', '', $content); + + $tokens->ensureWhitespaceAtIndex($prevIndex, 0, $content); + } + + $nextIndex = $index + 1; + $nextToken = $tokens[$nextIndex] ?? null; + + if (!$newlineRemoved && null !== $nextToken && $nextToken->isWhitespace()) { + $content = Preg::replace('/^\R/', '', $nextToken->getContent()); + + $tokens->ensureWhitespaceAtIndex($nextIndex, 0, $content); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + + private function insertHeader(Tokens $tokens, int $index): void + { + $tokens->insertAt($index, new Token([self::HEADER_COMMENT === $this->configuration['comment_type'] ? T_COMMENT : T_DOC_COMMENT, $this->getHeaderAsComment()])); + $this->fixWhiteSpaceAroundHeader($tokens, $index); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php new file mode 100644 index 00000000..dc4b7dc3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + */ +final class MultilineCommentOpeningClosingFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'DocBlocks must start with two asterisks, multiline comments must start with a single asterisk, after the opening slash. Both must end with a single asterisk before the closing slash.', + [ + new CodeSample( + <<<'EOT' + isAnyTokenKindsFound([T_COMMENT, T_DOC_COMMENT]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + $originalContent = $token->getContent(); + + if ( + !$token->isGivenKind(T_DOC_COMMENT) + && !($token->isGivenKind(T_COMMENT) && str_starts_with($originalContent, '/*')) + ) { + continue; + } + + $newContent = $originalContent; + + // Fix opening + if ($token->isGivenKind(T_COMMENT)) { + $newContent = Preg::replace('/^\\/\\*{2,}(?!\\/)/', '/*', $newContent); + } + + // Fix closing + $newContent = Preg::replace('/(?getId(), $newContent]); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoEmptyCommentFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoEmptyCommentFixer.php new file mode 100644 index 00000000..c2d6c744 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoEmptyCommentFixer.php @@ -0,0 +1,148 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; + +final class NoEmptyCommentFixer extends AbstractFixer +{ + private const TYPE_HASH = 1; + + private const TYPE_DOUBLE_SLASH = 2; + + private const TYPE_SLASH_ASTERISK = 3; + + /** + * {@inheritdoc} + * + * Must run before NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer, NoWhitespaceInBlankLineFixer. + * Must run after PhpdocToCommentFixer. + */ + public function getPriority(): int + { + return 2; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be any empty comments.', + [new CodeSample("isTokenKindFound(T_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = 1, $count = \count($tokens); $index < $count; ++$index) { + if (!$tokens[$index]->isGivenKind(T_COMMENT)) { + continue; + } + + [$blockStart, $index, $isEmpty] = $this->getCommentBlock($tokens, $index); + if (false === $isEmpty) { + continue; + } + + for ($i = $blockStart; $i <= $index; ++$i) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } + } + + /** + * Return the start index, end index and a flag stating if the comment block is empty. + * + * @param int $index T_COMMENT index + */ + private function getCommentBlock(Tokens $tokens, int $index): array + { + $commentType = $this->getCommentType($tokens[$index]->getContent()); + $empty = $this->isEmptyComment($tokens[$index]->getContent()); + + if (self::TYPE_SLASH_ASTERISK === $commentType) { + return [$index, $index, $empty]; + } + + $start = $index; + $count = \count($tokens); + ++$index; + + for (; $index < $count; ++$index) { + if ($tokens[$index]->isComment()) { + if ($commentType !== $this->getCommentType($tokens[$index]->getContent())) { + break; + } + + if ($empty) { // don't retest if already known the block not being empty + $empty = $this->isEmptyComment($tokens[$index]->getContent()); + } + + continue; + } + + if (!$tokens[$index]->isWhitespace() || $this->getLineBreakCount($tokens, $index, $index + 1) > 1) { + break; + } + } + + return [$start, $index - 1, $empty]; + } + + private function getCommentType(string $content): int + { + if (str_starts_with($content, '#')) { + return self::TYPE_HASH; + } + + if ('*' === $content[1]) { + return self::TYPE_SLASH_ASTERISK; + } + + return self::TYPE_DOUBLE_SLASH; + } + + private function getLineBreakCount(Tokens $tokens, int $whiteStart, int $whiteEnd): int + { + $lineCount = 0; + for ($i = $whiteStart; $i < $whiteEnd; ++$i) { + $lineCount += Preg::matchAll('/\R/u', $tokens[$i]->getContent(), $matches); + } + + return $lineCount; + } + + private function isEmptyComment(string $content): bool + { + static $mapper = [ + self::TYPE_HASH => '|^#\s*$|', // single line comment starting with '#' + self::TYPE_SLASH_ASTERISK => '|^/\*[\s\*]*\*+/$|', // comment starting with '/*' and ending with '*/' (but not a PHPDoc) + self::TYPE_DOUBLE_SLASH => '|^//\s*$|', // single line comment starting with '//' + ]; + + $type = $this->getCommentType($content); + + return Preg::match($mapper[$type], $content); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php new file mode 100644 index 00000000..d17a4495 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php @@ -0,0 +1,75 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class NoTrailingWhitespaceInCommentFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There MUST be no trailing spaces inside comment or PHPDoc.', + [new CodeSample('isAnyTokenKindsFound([T_COMMENT, T_DOC_COMMENT]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(T_DOC_COMMENT)) { + $tokens[$index] = new Token([T_DOC_COMMENT, Preg::replace('/(*ANY)[\h]+$/m', '', $token->getContent())]); + + continue; + } + + if ($token->isGivenKind(T_COMMENT)) { + if (str_starts_with($token->getContent(), '/*')) { + $tokens[$index] = new Token([T_COMMENT, Preg::replace('/(*ANY)[\h]+$/m', '', $token->getContent())]); + } elseif (isset($tokens[$index + 1]) && $tokens[$index + 1]->isWhitespace()) { + $trimmedContent = ltrim($tokens[$index + 1]->getContent(), " \t"); + $tokens->ensureWhitespaceAtIndex($index + 1, 0, $trimmedContent); + } + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentSpacingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentSpacingFixer.php new file mode 100644 index 00000000..ecf09eca --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentSpacingFixer.php @@ -0,0 +1,110 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class SingleLineCommentSpacingFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Single-line comments must have proper spacing.', + [ + new CodeSample( + 'isTokenKindFound(T_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(T_COMMENT)) { + continue; + } + + $content = $token->getContent(); + $contentLength = \strlen($content); + + if ('/' === $content[0]) { + if ($contentLength < 3) { + continue; // cheap check for "//" + } + + if ('*' === $content[1]) { // slash asterisk comment + if ($contentLength < 5 || '*' === $content[2] || str_contains($content, "\n")) { + continue; // cheap check for "/**/", comment that looks like a PHPDoc, or multi line comment + } + + $newContent = rtrim(substr($content, 0, -2)).' '.substr($content, -2); + $newContent = $this->fixCommentLeadingSpace($newContent, '/*'); + } else { // double slash comment + $newContent = $this->fixCommentLeadingSpace($content, '//'); + } + } else { // hash comment + if ($contentLength < 2 || '[' === $content[1]) { // cheap check for "#" or annotation (like) comment + continue; + } + + $newContent = $this->fixCommentLeadingSpace($content, '#'); + } + + if ($newContent !== $content) { + $tokens[$index] = new Token([T_COMMENT, $newContent]); + } + } + } + + // fix space between comment open and leading text + private function fixCommentLeadingSpace(string $content, string $prefix): string + { + if (Preg::match(sprintf('@^%s\h+.*$@', preg_quote($prefix, '@')), $content)) { + return $content; + } + + $position = \strlen($prefix); + + return substr($content, 0, $position).' '.substr($content, $position); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentStyleFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentStyleFixer.php new file mode 100644 index 00000000..aaf81ed9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentStyleFixer.php @@ -0,0 +1,171 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + */ +final class SingleLineCommentStyleFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var bool + */ + private $asteriskEnabled; + + /** + * @var bool + */ + private $hashEnabled; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->asteriskEnabled = \in_array('asterisk', $this->configuration['comment_types'], true); + $this->hashEnabled = \in_array('hash', $this->configuration['comment_types'], true); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Single-line comments and multi-line comments with only one line of actual content should use the `//` syntax.', + [ + new CodeSample( + ' ['asterisk']] + ), + new CodeSample( + " ['hash']] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run after HeaderCommentFixer, NoUselessReturnFixer, PhpdocToCommentFixer. + */ + public function getPriority(): int + { + return -31; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_COMMENT)) { + continue; + } + + $content = $token->getContent(); + $commentContent = substr($content, 2, -2) ?: ''; + + if ($this->hashEnabled && str_starts_with($content, '#')) { + if (isset($content[1]) && '[' === $content[1]) { + continue; // This might be an attribute on PHP8, do not change + } + + $tokens[$index] = new Token([$token->getId(), '//'.substr($content, 1)]); + + continue; + } + + if ( + !$this->asteriskEnabled + || str_contains($commentContent, '?>') + || !str_starts_with($content, '/*') + || Preg::match('/[^\s\*].*\R.*[^\s\*]/s', $commentContent) + ) { + continue; + } + + $nextTokenIndex = $index + 1; + if (isset($tokens[$nextTokenIndex])) { + $nextToken = $tokens[$nextTokenIndex]; + if (!$nextToken->isWhitespace() || !Preg::match('/\R/', $nextToken->getContent())) { + continue; + } + + $tokens[$nextTokenIndex] = new Token([$nextToken->getId(), ltrim($nextToken->getContent(), " \t")]); + } + + $content = '//'; + if (Preg::match('/[^\s\*]/', $commentContent)) { + $content = '// '.Preg::replace('/[\s\*]*([^\s\*](?:.+[^\s\*])?)[\s\*]*/', '\1', $commentContent); + } + $tokens[$index] = new Token([$token->getId(), $content]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('comment_types', 'List of comment types to fix.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset(['asterisk', 'hash'])]) + ->setDefault(['asterisk', 'hash']) + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConfigurableFixerInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConfigurableFixerInterface.php new file mode 100644 index 00000000..24ce993b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConfigurableFixerInterface.php @@ -0,0 +1,47 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; + +/** + * @author Dariusz Rumiński + */ +interface ConfigurableFixerInterface extends FixerInterface +{ + /** + * Set configuration. + * + * New configuration must override current one, not patch it. + * Using empty array makes fixer to use default configuration + * (or reset configuration from previously configured back to default one). + * + * Some fixers may have no configuration, then - simply don't implement this interface. + * Other ones may have configuration that will change behavior of fixer, + * eg `php_unit_strict` fixer allows to configure which methods should be fixed. + * Finally, some fixers need configuration to work, eg `header_comment`. + * + * @param array $configuration configuration depends on Fixer + * + * @throws InvalidFixerConfigurationException + */ + public function configure(array $configuration): void; + + /** + * Defines the available configuration options of the fixer. + */ + public function getConfigurationDefinition(): FixerConfigurationResolverInterface; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConstantNotation/NativeConstantInvocationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConstantNotation/NativeConstantInvocationFixer.php new file mode 100644 index 00000000..ed767cf0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConstantNotation/NativeConstantInvocationFixer.php @@ -0,0 +1,287 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ConstantNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @author Filippo Tessarotto + */ +final class NativeConstantInvocationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private array $constantsToEscape = []; + + /** + * @var array + */ + private array $caseInsensitiveConstantsToEscape = []; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Add leading `\` before constant invocation of internal constant to speed up resolving. Constant name match is case-sensitive, except for `null`, `false` and `true`.', + [ + new CodeSample(" 'namespaced'] + ), + new CodeSample( + " [ + 'MY_CUSTOM_PI', + ], + ] + ), + new CodeSample( + " false, + 'include' => [ + 'MY_CUSTOM_PI', + ], + ] + ), + new CodeSample( + " [ + 'M_PI', + ], + ] + ), + ], + null, + 'Risky when any of the constants are namespaced or overridden.' + ); + } + + /** + * {@inheritdoc} + * + * Must run before GlobalNamespaceImportFixer. + * Must run after FunctionToConstantFixer. + */ + public function getPriority(): int + { + return 1; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $uniqueConfiguredExclude = array_unique($this->configuration['exclude']); + + // Case-sensitive constants handling + $constantsToEscape = array_values($this->configuration['include']); + + if (true === $this->configuration['fix_built_in']) { + $getDefinedConstants = get_defined_constants(true); + unset($getDefinedConstants['user']); + foreach ($getDefinedConstants as $constants) { + $constantsToEscape = [...$constantsToEscape, ...array_keys($constants)]; + } + } + + $constantsToEscape = array_diff( + array_unique($constantsToEscape), + $uniqueConfiguredExclude + ); + + // Case-insensitive constants handling + static $caseInsensitiveConstants = ['null', 'false', 'true']; + $caseInsensitiveConstantsToEscape = []; + + foreach ($constantsToEscape as $constantIndex => $constant) { + $loweredConstant = strtolower($constant); + if (\in_array($loweredConstant, $caseInsensitiveConstants, true)) { + $caseInsensitiveConstantsToEscape[] = $loweredConstant; + unset($constantsToEscape[$constantIndex]); + } + } + + $caseInsensitiveConstantsToEscape = array_diff( + array_unique($caseInsensitiveConstantsToEscape), + array_map( + static fn (string $function): string => strtolower($function), + $uniqueConfiguredExclude, + ), + ); + + // Store the cache + $this->constantsToEscape = array_fill_keys($constantsToEscape, true); + ksort($this->constantsToEscape); + + $this->caseInsensitiveConstantsToEscape = array_fill_keys($caseInsensitiveConstantsToEscape, true); + ksort($this->caseInsensitiveConstantsToEscape); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if ('all' === $this->configuration['scope']) { + $this->fixConstantInvocations($tokens, 0, \count($tokens) - 1); + + return; + } + + $namespaces = $tokens->getNamespaceDeclarations(); + + // 'scope' is 'namespaced' here + /** @var NamespaceAnalysis $namespace */ + foreach (array_reverse($namespaces) as $namespace) { + if ($namespace->isGlobalNamespace()) { + continue; + } + + $this->fixConstantInvocations($tokens, $namespace->getScopeStartIndex(), $namespace->getScopeEndIndex()); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $constantChecker = static function (array $value): bool { + foreach ($value as $constantName) { + if (!\is_string($constantName) || '' === trim($constantName) || trim($constantName) !== $constantName) { + throw new InvalidOptionsException(sprintf( + 'Each element must be a non-empty, trimmed string, got "%s" instead.', + get_debug_type($constantName) + )); + } + } + + return true; + }; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('fix_built_in', 'Whether to fix constants returned by `get_defined_constants`. User constants are not accounted in this list and must be specified in the include one.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('include', 'List of additional constants to fix.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([$constantChecker]) + ->setDefault([]) + ->getOption(), + (new FixerOptionBuilder('exclude', 'List of constants to ignore.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([$constantChecker]) + ->setDefault(['null', 'false', 'true']) + ->getOption(), + (new FixerOptionBuilder('scope', 'Only fix constant invocations that are made within a namespace or fix all.')) + ->setAllowedValues(['all', 'namespaced']) + ->setDefault('all') + ->getOption(), + (new FixerOptionBuilder('strict', 'Whether leading `\` of constant invocation not meant to have it should be removed.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + private function fixConstantInvocations(Tokens $tokens, int $startIndex, int $endIndex): void + { + $useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens); + $useConstantDeclarations = []; + + foreach ($useDeclarations as $use) { + if ($use->isConstant()) { + $useConstantDeclarations[$use->getShortName()] = true; + } + } + + $tokenAnalyzer = new TokensAnalyzer($tokens); + + for ($index = $endIndex; $index > $startIndex; --$index) { + $token = $tokens[$index]; + + // test if we are at a constant call + if (!$token->isGivenKind(T_STRING)) { + continue; + } + + if (!$tokenAnalyzer->isConstantInvocation($index)) { + continue; + } + + $tokenContent = $token->getContent(); + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if (!isset($this->constantsToEscape[$tokenContent]) && !isset($this->caseInsensitiveConstantsToEscape[strtolower($tokenContent)])) { + if (false === $this->configuration['strict']) { + continue; + } + + if (!$tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { + continue; + } + + $prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + + if ($tokens[$prevPrevIndex]->isGivenKind(T_STRING)) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + + continue; + } + + if (isset($useConstantDeclarations[$tokenContent])) { + continue; + } + + if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { + continue; + } + + $tokens->insertAt($index, new Token([T_NS_SEPARATOR, '\\'])); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureBracesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureBracesFixer.php new file mode 100644 index 00000000..f89d959a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureBracesFixer.php @@ -0,0 +1,256 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class ControlStructureBracesFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The body of each control structure MUST be enclosed within braces.', + [new CodeSample("getControlTokens(); + + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind($controlTokens)) { + continue; + } + + if ( + $token->isGivenKind(T_ELSE) + && $tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(T_IF) + ) { + continue; + } + + $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); + $nextAfterParenthesisEndIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); + $tokenAfterParenthesis = $tokens[$nextAfterParenthesisEndIndex]; + + if ($tokenAfterParenthesis->equalsAny([';', '{', ':', [T_CLOSE_TAG]])) { + continue; + } + + $statementEndIndex = null; + + if ($tokenAfterParenthesis->isGivenKind([T_IF, T_FOR, T_FOREACH, T_SWITCH, T_WHILE])) { + $tokenAfterParenthesisBlockEnd = $tokens->findBlockEnd( // go to ')' + Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, + $tokens->getNextMeaningfulToken($nextAfterParenthesisEndIndex) + ); + + if ($tokens[$tokens->getNextMeaningfulToken($tokenAfterParenthesisBlockEnd)]->equals(':')) { + $statementEndIndex = $alternativeSyntaxAnalyzer->findAlternativeSyntaxBlockEnd($tokens, $nextAfterParenthesisEndIndex); + + $tokenAfterStatementEndIndex = $tokens->getNextMeaningfulToken($statementEndIndex); + if ($tokens[$tokenAfterStatementEndIndex]->equals(';')) { + $statementEndIndex = $tokenAfterStatementEndIndex; + } + } + } + + if (null === $statementEndIndex) { + $statementEndIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex); + } + + $tokensToInsertAfterStatement = [ + new Token([T_WHITESPACE, ' ']), + new Token('}'), + ]; + + if (!$tokens[$statementEndIndex]->equalsAny([';', '}'])) { + array_unshift($tokensToInsertAfterStatement, new Token(';')); + } + + $tokens->insertSlices([$statementEndIndex + 1 => $tokensToInsertAfterStatement]); + + // insert opening brace + $tokens->insertSlices([$parenthesisEndIndex + 1 => [ + new Token([T_WHITESPACE, ' ']), + new Token('{'), + ]]); + } + } + + private function findParenthesisEnd(Tokens $tokens, int $structureTokenIndex): int + { + $nextIndex = $tokens->getNextMeaningfulToken($structureTokenIndex); + $nextToken = $tokens[$nextIndex]; + + if (!$nextToken->equals('(')) { + return $structureTokenIndex; + } + + return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex); + } + + private function findStatementEnd(Tokens $tokens, int $parenthesisEndIndex): int + { + $nextIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); + if (null === $nextIndex) { + return $parenthesisEndIndex; + } + + $nextToken = $tokens[$nextIndex]; + + if ($nextToken->equals('{')) { + return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nextIndex); + } + + if ($nextToken->isGivenKind($this->getControlTokens())) { + $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $nextIndex); + + $endIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex); + + if ($nextToken->isGivenKind([T_IF, T_TRY, T_DO])) { + $openingTokenKind = $nextToken->getId(); + + while (true) { + $nextIndex = $tokens->getNextMeaningfulToken($endIndex); + if (null !== $nextIndex && $tokens[$nextIndex]->isGivenKind($this->getControlContinuationTokensForOpeningToken($openingTokenKind))) { + $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $nextIndex); + + $endIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex); + + if ($tokens[$nextIndex]->isGivenKind($this->getFinalControlContinuationTokensForOpeningToken($openingTokenKind))) { + return $endIndex; + } + } else { + break; + } + } + } + + return $endIndex; + } + + $index = $parenthesisEndIndex; + + while (true) { + $token = $tokens[++$index]; + + // if there is some block in statement (eg lambda function) we need to skip it + if ($token->equals('{')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + + continue; + } + + if ($token->equals(';')) { + return $index; + } + + if ($token->isGivenKind(T_CLOSE_TAG)) { + return $tokens->getPrevNonWhitespace($index); + } + } + } + + /** + * @return list + */ + private function getControlTokens(): array + { + static $tokens = [ + T_DECLARE, + T_DO, + T_ELSE, + T_ELSEIF, + T_FINALLY, + T_FOR, + T_FOREACH, + T_IF, + T_WHILE, + T_TRY, + T_CATCH, + T_SWITCH, + ]; + + return $tokens; + } + + /** + * @return list + */ + private function getControlContinuationTokensForOpeningToken(int $openingTokenKind): array + { + if (T_IF === $openingTokenKind) { + return [ + T_ELSE, + T_ELSEIF, + ]; + } + + if (T_DO === $openingTokenKind) { + return [T_WHILE]; + } + + if (T_TRY === $openingTokenKind) { + return [ + T_CATCH, + T_FINALLY, + ]; + } + + return []; + } + + /** + * @return list + */ + private function getFinalControlContinuationTokensForOpeningToken(int $openingTokenKind): array + { + if (T_IF === $openingTokenKind) { + return [T_ELSE]; + } + + if (T_TRY === $openingTokenKind) { + return [T_FINALLY]; + } + + return []; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureContinuationPositionFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureContinuationPositionFixer.php new file mode 100644 index 00000000..a51fa779 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureContinuationPositionFixer.php @@ -0,0 +1,143 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; + +final class ControlStructureContinuationPositionFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @internal + */ + public const NEXT_LINE = 'next_line'; + + /** + * @internal + */ + public const SAME_LINE = 'same_line'; + + private const CONTROL_CONTINUATION_TOKENS = [ + T_CATCH, + T_ELSE, + T_ELSEIF, + T_FINALLY, + T_WHILE, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Control structure continuation keyword must be on the configured line.', + [ + new CodeSample( + ' self::NEXT_LINE] + ), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(self::CONTROL_CONTINUATION_TOKENS); + } + + /** + * {@inheritdoc} + * + * Must run after ControlStructureBracesFixer. + */ + public function getPriority(): int + { + return parent::getPriority(); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('position', 'The position of the keyword that continues the control structure.')) + ->setAllowedValues([self::NEXT_LINE, self::SAME_LINE]) + ->setDefault(self::SAME_LINE) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->fixControlContinuationBraces($tokens); + } + + private function fixControlContinuationBraces(Tokens $tokens): void + { + for ($index = \count($tokens) - 1; 0 < $index; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(self::CONTROL_CONTINUATION_TOKENS)) { + continue; + } + + $prevIndex = $tokens->getPrevNonWhitespace($index); + $prevToken = $tokens[$prevIndex]; + + if (!$prevToken->equals('}')) { + continue; + } + + if ($token->isGivenKind(T_WHILE)) { + $prevIndex = $tokens->getPrevMeaningfulToken( + $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $prevIndex) + ); + + if (!$tokens[$prevIndex]->isGivenKind(T_DO)) { + continue; + } + } + + $tokens->ensureWhitespaceAtIndex( + $index - 1, + 1, + self::NEXT_LINE === $this->configuration['position'] ? + $this->whitespacesConfig->getLineEnding().WhitespacesAnalyzer::detectIndent($tokens, $index) + : ' ' + ); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ElseifFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ElseifFixer.php new file mode 100644 index 00000000..19c810ec --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ElseifFixer.php @@ -0,0 +1,98 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶5.1. + * + * @author Dariusz Rumiński + */ +final class ElseifFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The keyword `elseif` should be used instead of `else if` so that all control keywords look like single words.', + [new CodeSample("isAllTokenKindsFound([T_IF, T_ELSE]); + } + + /** + * Replace all `else if` (T_ELSE T_IF) with `elseif` (T_ELSEIF). + * + * {@inheritdoc} + */ + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_ELSE)) { + continue; + } + + $ifTokenIndex = $tokens->getNextMeaningfulToken($index); + + // if next meaningful token is not T_IF - continue searching, this is not the case for fixing + if (!$tokens[$ifTokenIndex]->isGivenKind(T_IF)) { + continue; + } + + // if next meaningful token is T_IF, but uses an alternative syntax - this is not the case for fixing neither + $conditionEndBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextMeaningfulToken($ifTokenIndex)); + $afterConditionIndex = $tokens->getNextMeaningfulToken($conditionEndBraceIndex); + if ($tokens[$afterConditionIndex]->equals(':')) { + continue; + } + + // now we have T_ELSE following by T_IF with no alternative syntax so we could fix this + // 1. clear whitespaces between T_ELSE and T_IF + $tokens->clearAt($index + 1); + + // 2. change token from T_ELSE into T_ELSEIF + $tokens[$index] = new Token([T_ELSEIF, 'elseif']); + + // 3. clear succeeding T_IF + $tokens->clearAt($ifTokenIndex); + + $beforeIfTokenIndex = $tokens->getPrevNonWhitespace($ifTokenIndex); + + // 4. clear extra whitespace after T_IF in T_COMMENT,T_WHITESPACE?,T_IF,T_WHITESPACE sequence + if ($tokens[$beforeIfTokenIndex]->isComment() && $tokens[$ifTokenIndex + 1]->isWhitespace()) { + $tokens->clearAt($ifTokenIndex + 1); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopBodyFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopBodyFixer.php new file mode 100644 index 00000000..54f804fe --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopBodyFixer.php @@ -0,0 +1,125 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +final class EmptyLoopBodyFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const STYLE_BRACES = 'braces'; + + private const STYLE_SEMICOLON = 'semicolon'; + + private const TOKEN_LOOP_KINDS = [T_FOR, T_FOREACH, T_WHILE]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Empty loop-body must be in configured style.', + [ + new CodeSample(" 'braces', + ] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before BracesFixer, NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer. + * Must run after NoEmptyStatementFixer. + */ + public function getPriority(): int + { + return 39; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(self::TOKEN_LOOP_KINDS); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if (self::STYLE_BRACES === $this->configuration['style']) { + $analyzer = new TokensAnalyzer($tokens); + $fixLoop = static function (int $index, int $endIndex) use ($tokens, $analyzer): void { + if ($tokens[$index]->isGivenKind(T_WHILE) && $analyzer->isWhilePartOfDoWhile($index)) { + return; + } + + $semiColonIndex = $tokens->getNextMeaningfulToken($endIndex); + + if (!$tokens[$semiColonIndex]->equals(';')) { + return; + } + + $tokens[$semiColonIndex] = new Token('{'); + $tokens->insertAt($semiColonIndex + 1, new Token('}')); + }; + } else { + $fixLoop = static function (int $index, int $endIndex) use ($tokens): void { + $braceOpenIndex = $tokens->getNextMeaningfulToken($endIndex); + + if (!$tokens[$braceOpenIndex]->equals('{')) { + return; + } + + $braceCloseIndex = $tokens->getNextNonWhitespace($braceOpenIndex); + + if (!$tokens[$braceCloseIndex]->equals('}')) { + return; + } + + $tokens[$braceOpenIndex] = new Token(';'); + $tokens->clearTokenAndMergeSurroundingWhitespace($braceCloseIndex); + }; + } + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind(self::TOKEN_LOOP_KINDS)) { + $endIndex = $tokens->getNextTokenOfKind($index, ['(']); // proceed to open '(' + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endIndex); // proceed to close ')' + $fixLoop($index, $endIndex); // fix loop if needs fixing + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('style', 'Style of empty loop-bodies.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([self::STYLE_BRACES, self::STYLE_SEMICOLON]) + ->setDefault(self::STYLE_SEMICOLON) + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopConditionFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopConditionFixer.php new file mode 100644 index 00000000..6e3c81fc --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopConditionFixer.php @@ -0,0 +1,188 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class EmptyLoopConditionFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const STYLE_FOR = 'for'; + + private const STYLE_WHILE = 'while'; + + private const TOKEN_LOOP_KINDS = [T_FOR, T_WHILE]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Empty loop-condition must be in configured style.', + [ + new CodeSample(" 'for']), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer. + */ + public function getPriority(): int + { + return 1; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(self::TOKEN_LOOP_KINDS); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if (self::STYLE_WHILE === $this->configuration['style']) { + $candidateLoopKinds = [T_FOR, T_WHILE]; + $replacement = [new Token([T_WHILE, 'while']), new Token([T_WHITESPACE, ' ']), new Token('('), new Token([T_STRING, 'true']), new Token(')')]; + + $fixLoop = static function (int $index, int $openIndex, int $endIndex) use ($tokens, $replacement): void { + if (self::isForLoopWithEmptyCondition($tokens, $index, $openIndex, $endIndex)) { + self::clearNotCommentsInRange($tokens, $index, $endIndex); + self::cloneAndInsert($tokens, $index, $replacement); + } elseif (self::isWhileLoopWithEmptyCondition($tokens, $index, $openIndex, $endIndex)) { + $doIndex = self::getDoIndex($tokens, $index); + + if (null !== $doIndex) { + self::clearNotCommentsInRange($tokens, $index, $tokens->getNextMeaningfulToken($endIndex)); // clear including `;` + $tokens->clearAt($doIndex); + self::cloneAndInsert($tokens, $doIndex, $replacement); + } + } + }; + } else { // self::STYLE_FOR + $candidateLoopKinds = [T_WHILE]; + $replacement = [new Token([T_FOR, 'for']), new Token('('), new Token(';'), new Token(';'), new Token(')')]; + + $fixLoop = static function (int $index, int $openIndex, int $endIndex) use ($tokens, $replacement): void { + if (!self::isWhileLoopWithEmptyCondition($tokens, $index, $openIndex, $endIndex)) { + return; + } + + $doIndex = self::getDoIndex($tokens, $index); + + if (null === $doIndex) { + self::clearNotCommentsInRange($tokens, $index, $endIndex); + self::cloneAndInsert($tokens, $index, $replacement); + } else { + self::clearNotCommentsInRange($tokens, $index, $tokens->getNextMeaningfulToken($endIndex)); // clear including `;` + $tokens->clearAt($doIndex); + self::cloneAndInsert($tokens, $doIndex, $replacement); + } + }; + } + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind($candidateLoopKinds)) { + $openIndex = $tokens->getNextTokenOfKind($index, ['(']); // proceed to open '(' + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); // proceed to close ')' + $fixLoop($index, $openIndex, $endIndex); // fix loop if needed + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('style', 'Style of empty loop-condition.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([self::STYLE_WHILE, self::STYLE_FOR]) + ->setDefault(self::STYLE_WHILE) + ->getOption(), + ]); + } + + private static function clearNotCommentsInRange(Tokens $tokens, int $indexStart, int $indexEnd): void + { + for ($i = $indexStart; $i <= $indexEnd; ++$i) { + if (!$tokens[$i]->isComment()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } + } + + /** + * @param Token[] $replacement + */ + private static function cloneAndInsert(Tokens $tokens, int $index, array $replacement): void + { + $replacementClones = []; + + foreach ($replacement as $token) { + $replacementClones[] = clone $token; + } + + $tokens->insertAt($index, $replacementClones); + } + + private static function getDoIndex(Tokens $tokens, int $index): ?int + { + $endIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$endIndex]->equals('}')) { + return null; + } + + $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $endIndex); + $index = $tokens->getPrevMeaningfulToken($startIndex); + + return null === $index || !$tokens[$index]->isGivenKind(T_DO) ? null : $index; + } + + private static function isForLoopWithEmptyCondition(Tokens $tokens, int $index, int $openIndex, int $endIndex): bool + { + if (!$tokens[$index]->isGivenKind(T_FOR)) { + return false; + } + + $index = $tokens->getNextMeaningfulToken($openIndex); + + if (null === $index || !$tokens[$index]->equals(';')) { + return false; + } + + $index = $tokens->getNextMeaningfulToken($index); + + return null !== $index && $tokens[$index]->equals(';') && $endIndex === $tokens->getNextMeaningfulToken($index); + } + + private static function isWhileLoopWithEmptyCondition(Tokens $tokens, int $index, int $openIndex, int $endIndex): bool + { + if (!$tokens[$index]->isGivenKind(T_WHILE)) { + return false; + } + + $index = $tokens->getNextMeaningfulToken($openIndex); + + return null !== $index && $tokens[$index]->equals([T_STRING, 'true']) && $endIndex === $tokens->getNextMeaningfulToken($index); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/IncludeFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/IncludeFixer.php new file mode 100644 index 00000000..a0bd5acc --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/IncludeFixer.php @@ -0,0 +1,153 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\BlocksAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Sebastiaan Stok + * @author Dariusz Rumiński + * @author Kuba Werłos + */ +final class IncludeFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Include/Require and file path should be divided with a single space. File path should not be placed within parentheses.', + [ + new CodeSample( + 'isAnyTokenKindsFound([T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->clearIncludies($tokens, $this->findIncludies($tokens)); + } + + /** + * @param array $includies + */ + private function clearIncludies(Tokens $tokens, array $includies): void + { + $blocksAnalyzer = new BlocksAnalyzer(); + + foreach ($includies as $includy) { + if (!$tokens[$includy['end']]->isGivenKind(T_CLOSE_TAG)) { + $afterEndIndex = $tokens->getNextNonWhitespace($includy['end']); + + if (null === $afterEndIndex || !$tokens[$afterEndIndex]->isComment()) { + $tokens->removeLeadingWhitespace($includy['end']); + } + } + + $braces = $includy['braces']; + + if (null !== $braces) { + $prevIndex = $tokens->getPrevMeaningfulToken($includy['begin']); + $nextIndex = $tokens->getNextMeaningfulToken($braces['close']); + + // Include is also legal as function parameter or condition statement but requires being wrapped then. + if (!$tokens[$nextIndex]->equalsAny([';', [T_CLOSE_TAG]]) && !$blocksAnalyzer->isBlock($tokens, $prevIndex, $nextIndex)) { + continue; + } + + $this->removeWhitespaceAroundIfPossible($tokens, $braces['open']); + $this->removeWhitespaceAroundIfPossible($tokens, $braces['close']); + $tokens->clearTokenAndMergeSurroundingWhitespace($braces['open']); + $tokens->clearTokenAndMergeSurroundingWhitespace($braces['close']); + } + + $nextIndex = $tokens->getNonEmptySibling($includy['begin'], 1); + + if ($tokens[$nextIndex]->isWhitespace()) { + $tokens[$nextIndex] = new Token([T_WHITESPACE, ' ']); + } elseif (null !== $braces || $tokens[$nextIndex]->isGivenKind([T_VARIABLE, T_CONSTANT_ENCAPSED_STRING, T_COMMENT])) { + $tokens->insertAt($includy['begin'] + 1, new Token([T_WHITESPACE, ' '])); + } + } + } + + /** + * @return array + */ + private function findIncludies(Tokens $tokens): array + { + static $includyTokenKinds = [T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE]; + + $includies = []; + + foreach ($tokens->findGivenKind($includyTokenKinds) as $includyTokens) { + foreach ($includyTokens as $index => $token) { + $includy = [ + 'begin' => $index, + 'braces' => null, + 'end' => $tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]), + ]; + + $braceOpenIndex = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$braceOpenIndex]->equals('(')) { + $braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $braceOpenIndex); + + $includy['braces'] = [ + 'open' => $braceOpenIndex, + 'close' => $braceCloseIndex, + ]; + } + + $includies[$index] = $includy; + } + } + + krsort($includies); + + return $includies; + } + + private function removeWhitespaceAroundIfPossible(Tokens $tokens, int $index): void + { + $nextIndex = $tokens->getNextNonWhitespace($index); + + if (null === $nextIndex || !$tokens[$nextIndex]->isComment()) { + $tokens->removeLeadingWhitespace($index); + } + + $prevIndex = $tokens->getPrevNonWhitespace($index); + + if (null === $prevIndex || !$tokens[$prevIndex]->isComment()) { + $tokens->removeTrailingWhitespace($index); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php new file mode 100644 index 00000000..e994ad92 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php @@ -0,0 +1,231 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Eddilbert Macharia + */ +final class NoAlternativeSyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace control structure alternative syntax to use braces.', + [ + new CodeSample( + "\nLorem ipsum.\n\n", + ['fix_non_monolithic_code' => true] + ), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->hasAlternativeSyntax() && (true === $this->configuration['fix_non_monolithic_code'] || $tokens->isMonolithicPhp()); + } + + /** + * {@inheritdoc} + * + * Must run before BracesFixer, ElseifFixer, NoSuperfluousElseifFixer, NoUnneededControlParenthesesFixer, NoUselessElseFixer, SwitchContinueToBreakFixer. + */ + public function getPriority(): int + { + return 42; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('fix_non_monolithic_code', 'Whether to also fix code with inline HTML.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) // @TODO change to "false" on next major 4.0 + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + $this->fixElseif($index, $token, $tokens); + $this->fixElse($index, $token, $tokens); + $this->fixOpenCloseControls($index, $token, $tokens); + } + } + + private function findParenthesisEnd(Tokens $tokens, int $structureTokenIndex): int + { + $nextIndex = $tokens->getNextMeaningfulToken($structureTokenIndex); + $nextToken = $tokens[$nextIndex]; + + return $nextToken->equals('(') + ? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex) + : $structureTokenIndex; // return if next token is not opening parenthesis + } + + /** + * Handle both extremes of the control structures. + * e.g. if(): or endif;. + * + * @param int $index the index of the token being processed + * @param Token $token the token being processed + * @param Tokens $tokens the collection of tokens + */ + private function fixOpenCloseControls(int $index, Token $token, Tokens $tokens): void + { + if ($token->isGivenKind([T_IF, T_FOREACH, T_WHILE, T_FOR, T_SWITCH, T_DECLARE])) { + $openIndex = $tokens->getNextTokenOfKind($index, ['(']); + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); + $afterParenthesisIndex = $tokens->getNextMeaningfulToken($closeIndex); + $afterParenthesis = $tokens[$afterParenthesisIndex]; + + if (!$afterParenthesis->equals(':')) { + return; + } + + $items = []; + + if (!$tokens[$afterParenthesisIndex - 1]->isWhitespace()) { + $items[] = new Token([T_WHITESPACE, ' ']); + } + + $items[] = new Token('{'); + + if (!$tokens[$afterParenthesisIndex + 1]->isWhitespace()) { + $items[] = new Token([T_WHITESPACE, ' ']); + } + + $tokens->clearAt($afterParenthesisIndex); + $tokens->insertAt($afterParenthesisIndex, $items); + } + + if (!$token->isGivenKind([T_ENDIF, T_ENDFOREACH, T_ENDWHILE, T_ENDFOR, T_ENDSWITCH, T_ENDDECLARE])) { + return; + } + + $nextTokenIndex = $tokens->getNextMeaningfulToken($index); + $nextToken = $tokens[$nextTokenIndex]; + $tokens[$index] = new Token('}'); + + if ($nextToken->equals(';')) { + $tokens->clearAt($nextTokenIndex); + } + } + + /** + * Handle the else: cases. + * + * @param int $index the index of the token being processed + * @param Token $token the token being processed + * @param Tokens $tokens the collection of tokens + */ + private function fixElse(int $index, Token $token, Tokens $tokens): void + { + if (!$token->isGivenKind(T_ELSE)) { + return; + } + + $tokenAfterElseIndex = $tokens->getNextMeaningfulToken($index); + $tokenAfterElse = $tokens[$tokenAfterElseIndex]; + + if (!$tokenAfterElse->equals(':')) { + return; + } + + $this->addBraces($tokens, new Token([T_ELSE, 'else']), $index, $tokenAfterElseIndex); + } + + /** + * Handle the elsif(): cases. + * + * @param int $index the index of the token being processed + * @param Token $token the token being processed + * @param Tokens $tokens the collection of tokens + */ + private function fixElseif(int $index, Token $token, Tokens $tokens): void + { + if (!$token->isGivenKind(T_ELSEIF)) { + return; + } + + $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); + $tokenAfterParenthesisIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); + $tokenAfterParenthesis = $tokens[$tokenAfterParenthesisIndex]; + + if (!$tokenAfterParenthesis->equals(':')) { + return; + } + + $this->addBraces($tokens, new Token([T_ELSEIF, 'elseif']), $index, $tokenAfterParenthesisIndex); + } + + /** + * Add opening and closing braces to the else: and elseif: cases. + * + * @param Tokens $tokens the tokens collection + * @param Token $token the current token + * @param int $index the current token index + * @param int $colonIndex the index of the colon + */ + private function addBraces(Tokens $tokens, Token $token, int $index, int $colonIndex): void + { + $items = [ + new Token('}'), + new Token([T_WHITESPACE, ' ']), + $token, + ]; + + if (!$tokens[$index + 1]->isWhitespace()) { + $items[] = new Token([T_WHITESPACE, ' ']); + } + + $tokens->clearAt($index); + $tokens->insertAt( + $index, + $items + ); + + // increment the position of the colon by number of items inserted + $colonIndex += \count($items); + + $items = [new Token('{')]; + + if (!$tokens[$colonIndex + 1]->isWhitespace()) { + $items[] = new Token([T_WHITESPACE, ' ']); + } + + $tokens->clearAt($colonIndex); + $tokens->insertAt( + $colonIndex, + $items + ); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoBreakCommentFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoBreakCommentFixer.php new file mode 100644 index 00000000..b50a6c85 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoBreakCommentFixer.php @@ -0,0 +1,353 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use Symfony\Component\OptionsResolver\Options; + +/** + * Fixer for rule defined in PSR2 ¶5.2. + */ +final class NoBreakCommentFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There must be a comment when fall-through is intentional in a non-empty case body.', + [ + new CodeSample( + ' 'some comment'] + ), + ], + 'Adds a "no break" comment before fall-through cases, and removes it if there is no fall-through.' + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_SWITCH); + } + + /** + * {@inheritdoc} + * + * Must run after NoUselessElseFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('comment_text', 'The text to use in the added comment and to detect it.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([ + static function (string $value): bool { + if (Preg::match('/\R/', $value)) { + throw new InvalidOptionsException('The comment text must not contain new lines.'); + } + + return true; + }, + ]) + ->setNormalizer(static fn (Options $options, string $value): string => rtrim($value)) + ->setDefault('no break') + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; $index >= 0; --$index) { + if ($tokens[$index]->isGivenKind(T_DEFAULT)) { + if ($tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(T_DOUBLE_ARROW)) { + continue; // this is "default" from "match" + } + } elseif (!$tokens[$index]->isGivenKind(T_CASE)) { + continue; + } + + $this->fixCase($tokens, $tokens->getNextTokenOfKind($index, [':', ';'])); + } + } + + private function fixCase(Tokens $tokens, int $casePosition): void + { + $empty = true; + $fallThrough = true; + $commentPosition = null; + + for ($i = $casePosition + 1, $max = \count($tokens); $i < $max; ++$i) { + if ($tokens[$i]->isGivenKind([...self::getParenthesisedStructureKinds(), T_ELSE, T_DO, T_CLASS])) { + $empty = false; + $i = $this->getStructureEnd($tokens, $i); + + continue; + } + + if ($tokens[$i]->isGivenKind([T_BREAK, T_CONTINUE, T_RETURN, T_EXIT, T_GOTO])) { + $fallThrough = false; + + continue; + } + + if ($tokens[$i]->isGivenKind(T_THROW)) { + $previousIndex = $tokens->getPrevMeaningfulToken($i); + + if ($previousIndex === $casePosition || $tokens[$previousIndex]->equalsAny(['{', ';', '}', [T_OPEN_TAG]])) { + $fallThrough = false; + } + + continue; + } + + if ($tokens[$i]->equals('}') || $tokens[$i]->isGivenKind(T_ENDSWITCH)) { + if (null !== $commentPosition) { + $this->removeComment($tokens, $commentPosition); + } + + break; + } + + if ($this->isNoBreakComment($tokens[$i])) { + $commentPosition = $i; + + continue; + } + + if ($tokens[$i]->isGivenKind([T_CASE, T_DEFAULT])) { + if (!$empty && $fallThrough) { + if (null !== $commentPosition && $tokens->getPrevNonWhitespace($i) !== $commentPosition) { + $this->removeComment($tokens, $commentPosition); + $commentPosition = null; + } + + if (null === $commentPosition) { + $this->insertCommentAt($tokens, $i); + } else { + $text = $this->configuration['comment_text']; + $tokens[$commentPosition] = new Token([ + $tokens[$commentPosition]->getId(), + str_ireplace($text, $text, $tokens[$commentPosition]->getContent()), + ]); + + $this->ensureNewLineAt($tokens, $commentPosition); + } + } elseif (null !== $commentPosition) { + $this->removeComment($tokens, $commentPosition); + } + + break; + } + + if (!$tokens[$i]->isGivenKind([T_COMMENT, T_WHITESPACE])) { + $empty = false; + } + } + } + + private function isNoBreakComment(Token $token): bool + { + if (!$token->isComment()) { + return false; + } + + $text = preg_quote($this->configuration['comment_text'], '~'); + + return Preg::match("~^((//|#)\\s*{$text}\\s*)|(/\\*\\*?\\s*{$text}(\\s+.*)*\\*/)$~i", $token->getContent()); + } + + private function insertCommentAt(Tokens $tokens, int $casePosition): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + $newlinePosition = $this->ensureNewLineAt($tokens, $casePosition); + $newlineToken = $tokens[$newlinePosition]; + $nbNewlines = substr_count($newlineToken->getContent(), $lineEnding); + + if ($newlineToken->isGivenKind(T_OPEN_TAG) && Preg::match('/\R/', $newlineToken->getContent())) { + ++$nbNewlines; + } elseif ($tokens[$newlinePosition - 1]->isGivenKind(T_OPEN_TAG) && Preg::match('/\R/', $tokens[$newlinePosition - 1]->getContent())) { + ++$nbNewlines; + + if (!Preg::match('/\R/', $newlineToken->getContent())) { + $tokens[$newlinePosition] = new Token([$newlineToken->getId(), $lineEnding.$newlineToken->getContent()]); + } + } + + if ($nbNewlines > 1) { + Preg::match('/^(.*?)(\R\h*)$/s', $newlineToken->getContent(), $matches); + + $indent = WhitespacesAnalyzer::detectIndent($tokens, $newlinePosition - 1); + $tokens[$newlinePosition] = new Token([$newlineToken->getId(), $matches[1].$lineEnding.$indent]); + $tokens->insertAt(++$newlinePosition, new Token([T_WHITESPACE, $matches[2]])); + } + + $tokens->insertAt($newlinePosition, new Token([T_COMMENT, '// '.$this->configuration['comment_text']])); + $this->ensureNewLineAt($tokens, $newlinePosition); + } + + /** + * @return int The newline token position + */ + private function ensureNewLineAt(Tokens $tokens, int $position): int + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + $content = $lineEnding.WhitespacesAnalyzer::detectIndent($tokens, $position); + $whitespaceToken = $tokens[$position - 1]; + + if (!$whitespaceToken->isGivenKind(T_WHITESPACE)) { + if ($whitespaceToken->isGivenKind(T_OPEN_TAG)) { + $content = Preg::replace('/\R/', '', $content); + + if (!Preg::match('/\R/', $whitespaceToken->getContent())) { + $tokens[$position - 1] = new Token([T_OPEN_TAG, Preg::replace('/\s+$/', $lineEnding, $whitespaceToken->getContent())]); + } + } + + if ('' !== $content) { + $tokens->insertAt($position, new Token([T_WHITESPACE, $content])); + + return $position; + } + + return $position - 1; + } + + if ($tokens[$position - 2]->isGivenKind(T_OPEN_TAG) && Preg::match('/\R/', $tokens[$position - 2]->getContent())) { + $content = Preg::replace('/^\R/', '', $content); + } + + if (!Preg::match('/\R/', $whitespaceToken->getContent())) { + $tokens[$position - 1] = new Token([T_WHITESPACE, $content]); + } + + return $position - 1; + } + + private function removeComment(Tokens $tokens, int $commentPosition): void + { + if ($tokens[$tokens->getPrevNonWhitespace($commentPosition)]->isGivenKind(T_OPEN_TAG)) { + $whitespacePosition = $commentPosition + 1; + $regex = '/^\R\h*/'; + } else { + $whitespacePosition = $commentPosition - 1; + $regex = '/\R\h*$/'; + } + + $whitespaceToken = $tokens[$whitespacePosition]; + + if ($whitespaceToken->isGivenKind(T_WHITESPACE)) { + $content = Preg::replace($regex, '', $whitespaceToken->getContent()); + + $tokens->ensureWhitespaceAtIndex($whitespacePosition, 0, $content); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($commentPosition); + } + + private function getStructureEnd(Tokens $tokens, int $position): int + { + $initialToken = $tokens[$position]; + + if ($initialToken->isGivenKind(self::getParenthesisedStructureKinds())) { + $position = $tokens->findBlockEnd( + Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, + $tokens->getNextTokenOfKind($position, ['(']) + ); + } elseif ($initialToken->isGivenKind(T_CLASS)) { + $openParenthesisPosition = $tokens->getNextMeaningfulToken($position); + + if ('(' === $tokens[$openParenthesisPosition]->getContent()) { + $position = $tokens->findBlockEnd( + Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, + $openParenthesisPosition + ); + } + } + + $position = $tokens->getNextMeaningfulToken($position); + + if ('{' !== $tokens[$position]->getContent()) { + return $tokens->getNextTokenOfKind($position, [';']); + } + + $position = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $position); + + if ($initialToken->isGivenKind(T_DO)) { + $position = $tokens->findBlockEnd( + Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, + $tokens->getNextTokenOfKind($position, ['(']) + ); + + return $tokens->getNextTokenOfKind($position, [';']); + } + + return $position; + } + + /** + * @return array + */ + private static function getParenthesisedStructureKinds(): array + { + static $structureKinds = null; + + if (null === $structureKinds) { + $structureKinds = [T_FOR, T_FOREACH, T_WHILE, T_IF, T_ELSEIF, T_SWITCH, T_FUNCTION]; + if (\defined('T_MATCH')) { // @TODO: drop condition when PHP 8.0+ is required + $structureKinds[] = T_MATCH; + } + } + + return $structureKinds; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php new file mode 100644 index 00000000..93dbb083 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php @@ -0,0 +1,100 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractNoUselessElseFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class NoSuperfluousElseifFixer extends AbstractNoUselessElseFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([T_ELSE, T_ELSEIF]); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replaces superfluous `elseif` with `if`.', + [ + new CodeSample(" $token) { + if ($this->isElseif($tokens, $index) && $this->isSuperfluousElse($tokens, $index)) { + $this->convertElseifToIf($tokens, $index); + } + } + } + + private function isElseif(Tokens $tokens, int $index): bool + { + return + $tokens[$index]->isGivenKind(T_ELSEIF) + || ($tokens[$index]->isGivenKind(T_ELSE) && $tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(T_IF)); + } + + private function convertElseifToIf(Tokens $tokens, int $index): void + { + if ($tokens[$index]->isGivenKind(T_ELSE)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } else { + $tokens[$index] = new Token([T_IF, 'if']); + } + + $whitespace = ''; + + for ($previous = $index - 1; $previous > 0; --$previous) { + $token = $tokens[$previous]; + if ($token->isWhitespace() && Preg::match('/(\R\N*)$/', $token->getContent(), $matches)) { + $whitespace = $matches[1]; + + break; + } + } + + if ('' === $whitespace) { + return; + } + + $previousToken = $tokens[$index - 1]; + + if (!$previousToken->isWhitespace()) { + $tokens->insertAt($index, new Token([T_WHITESPACE, $whitespace])); + } elseif (!Preg::match('/\R/', $previousToken->getContent())) { + $tokens[$index - 1] = new Token([T_WHITESPACE, $whitespace]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php new file mode 100644 index 00000000..4b710058 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\Basic\NoTrailingCommaInSinglelineFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @deprecated + * + * @author Dariusz Rumiński + */ +final class NoTrailingCommaInListCallFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Remove trailing commas in list function calls.', + [new CodeSample("proxyFixers); + } + + protected function createProxyFixers(): array + { + $fixer = new NoTrailingCommaInSinglelineFixer(); + $fixer->configure(['elements' => ['array_destructuring']]); + + return [$fixer]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededBracesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededBracesFixer.php new file mode 100644 index 00000000..281eca16 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededBracesFixer.php @@ -0,0 +1,160 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class NoUnneededBracesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes unneeded braces that are superfluous and aren\'t part of a control structure\'s body.', + [ + new CodeSample( + ' true] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoUselessElseFixer, NoUselessReturnFixer, ReturnAssignmentFixer, SimplifiedIfReturnFixer. + */ + public function getPriority(): int + { + return 40; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound('}'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($this->findBraceOpen($tokens) as $index) { + if ($this->isOverComplete($tokens, $index)) { + $this->clearOverCompleteBraces($tokens, $index, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index)); + } + } + + if (true === $this->configuration['namespaces']) { + $this->clearIfIsOverCompleteNamespaceBlock($tokens); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('namespaces', 'Remove unneeded braces from bracketed namespaces.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * @param int $openIndex index of `{` token + * @param int $closeIndex index of `}` token + */ + private function clearOverCompleteBraces(Tokens $tokens, int $openIndex, int $closeIndex): void + { + $tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($openIndex); + } + + /** + * @return iterable + */ + private function findBraceOpen(Tokens $tokens): iterable + { + for ($i = \count($tokens) - 1; $i > 0; --$i) { + if ($tokens[$i]->equals('{')) { + yield $i; + } + } + } + + /** + * @param int $index index of `{` token + */ + private function isOverComplete(Tokens $tokens, int $index): bool + { + static $include = ['{', '}', [T_OPEN_TAG], ':', ';']; + + return $tokens[$tokens->getPrevMeaningfulToken($index)]->equalsAny($include); + } + + private function clearIfIsOverCompleteNamespaceBlock(Tokens $tokens): void + { + if (1 !== $tokens->countTokenKind(T_NAMESPACE)) { + return; // fast check, we never fix if multiple namespaces are defined + } + + $index = $tokens->getNextTokenOfKind(0, [[T_NAMESPACE]]); + + do { + $index = $tokens->getNextMeaningfulToken($index); + } while ($tokens[$index]->isGivenKind([T_STRING, T_NS_SEPARATOR])); + + if (!$tokens[$index]->equals('{')) { + return; // `;` + } + + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + $afterCloseIndex = $tokens->getNextMeaningfulToken($closeIndex); + + if (null !== $afterCloseIndex && (!$tokens[$afterCloseIndex]->isGivenKind(T_CLOSE_TAG) || null !== $tokens->getNextMeaningfulToken($afterCloseIndex))) { + return; + } + + // clear up + $tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex); + $tokens[$index] = new Token(';'); + + if ($tokens[$index - 1]->isWhitespace(" \t") && !$tokens[$index - 2]->isComment()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index - 1); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php new file mode 100644 index 00000000..b0156c27 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php @@ -0,0 +1,747 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Sullivan Senechal + * @author Dariusz Rumiński + * @author Gregor Harlan + */ +final class NoUnneededControlParenthesesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var int[] + */ + private const BLOCK_TYPES = [ + Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE, + Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, + Tokens::BLOCK_TYPE_CURLY_BRACE, + Tokens::BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE, + Tokens::BLOCK_TYPE_DYNAMIC_PROP_BRACE, + Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE, + Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, + Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, + ]; + + private const BEFORE_TYPES = [ + ';', + '{', + [T_OPEN_TAG], + [T_OPEN_TAG_WITH_ECHO], + [T_ECHO], + [T_PRINT], + [T_RETURN], + [T_THROW], + [T_YIELD], + [T_YIELD_FROM], + [T_BREAK], + [T_CONTINUE], + // won't be fixed, but true in concept, helpful for fast check + [T_REQUIRE], + [T_REQUIRE_ONCE], + [T_INCLUDE], + [T_INCLUDE_ONCE], + ]; + + private const CONFIG_OPTIONS = [ + 'break', + 'clone', + 'continue', + 'echo_print', + 'negative_instanceof', + 'others', + 'return', + 'switch_case', + 'yield', + 'yield_from', + ]; + + private const TOKEN_TYPE_CONFIG_MAP = [ + T_BREAK => 'break', + T_CASE => 'switch_case', + T_CONTINUE => 'continue', + T_ECHO => 'echo_print', + T_PRINT => 'echo_print', + T_RETURN => 'return', + T_YIELD => 'yield', + T_YIELD_FROM => 'yield_from', + ]; + + // handled by the `include` rule + private const TOKEN_TYPE_NO_CONFIG = [ + T_REQUIRE, + T_REQUIRE_ONCE, + T_INCLUDE, + T_INCLUDE_ONCE, + ]; + + /** + * @var list|string> + */ + private array $noopTypes; + + private TokensAnalyzer $tokensAnalyzer; + + public function __construct() + { + parent::__construct(); + + $this->noopTypes = [ + '$', + [T_CONSTANT_ENCAPSED_STRING], + [T_DNUMBER], + [T_DOUBLE_COLON], + [T_LNUMBER], + [T_NS_SEPARATOR], + [T_STRING], + [T_VARIABLE], + [T_STATIC], + // magic constants + [T_CLASS_C], + [T_DIR], + [T_FILE], + [T_FUNC_C], + [T_LINE], + [T_METHOD_C], + [T_NS_C], + [T_TRAIT_C], + ]; + + foreach (Token::getObjectOperatorKinds() as $kind) { + $this->noopTypes[] = [$kind]; + } + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes unneeded parentheses around control statements.', + [ + new CodeSample( + ' ['break', 'continue']] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before ConcatSpaceFixer, NoTrailingWhitespaceFixer. + * Must run after ModernizeTypesCastingFixer, NoAlternativeSyntaxFixer. + */ + public function getPriority(): int + { + return 30; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(['(', CT::T_BRACE_CLASS_INSTANTIATION_OPEN]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + + foreach ($tokens as $openIndex => $token) { + if ($token->equals('(')) { + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); + } elseif ($token->isGivenKind(CT::T_BRACE_CLASS_INSTANTIATION_OPEN)) { + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE_CLASS_INSTANTIATION, $openIndex); + } else { + continue; + } + + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($openIndex); + $afterCloseIndex = $tokens->getNextMeaningfulToken($closeIndex); + + // do a cheap check for negative case: `X()` + + if ($tokens->getNextMeaningfulToken($openIndex) === $closeIndex) { + if ($this->isExitStatement($tokens, $beforeOpenIndex)) { + $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, 'others'); + } + + continue; + } + + // do a cheap check for negative case: `foo(1,2)` + + if ($this->isKnownNegativePre($tokens[$beforeOpenIndex])) { + continue; + } + + // check for the simple useless wrapped cases + + if ($this->isUselessWrapped($tokens, $beforeOpenIndex, $afterCloseIndex)) { + $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, $this->getConfigType($tokens, $beforeOpenIndex)); + + continue; + } + + // handle `clone` statements + + if ($this->isCloneStatement($tokens, $beforeOpenIndex)) { + if ($this->isWrappedCloneArgument($tokens, $beforeOpenIndex, $openIndex, $closeIndex, $afterCloseIndex)) { + $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, 'clone'); + } + + continue; + } + + // handle `instance of` statements + + $instanceOfIndex = $this->getIndexOfInstanceOfStatement($tokens, $openIndex, $closeIndex); + + if (null !== $instanceOfIndex) { + if ($this->isWrappedInstanceOf($tokens, $instanceOfIndex, $beforeOpenIndex, $openIndex, $closeIndex, $afterCloseIndex)) { + $this->removeUselessParenthesisPair( + $tokens, + $beforeOpenIndex, + $afterCloseIndex, + $openIndex, + $closeIndex, + $tokens[$beforeOpenIndex]->equals('!') ? 'negative_instanceof' : 'others' + ); + } + + continue; + } + + // last checks deal with operators, do not swap around + + if ($this->isWrappedPartOfOperation($tokens, $beforeOpenIndex, $openIndex, $closeIndex, $afterCloseIndex)) { + $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, $this->getConfigType($tokens, $beforeOpenIndex)); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $defaults = array_filter( + self::CONFIG_OPTIONS, + static fn (string $option): bool => 'negative_instanceof' !== $option && 'others' !== $option && 'yield_from' !== $option + ); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('statements', 'List of control statements to fix.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset(self::CONFIG_OPTIONS)]) + ->setDefault(array_values($defaults)) + ->getOption(), + ]); + } + + private function isUselessWrapped(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex): bool + { + return + $this->isSingleStatement($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedFnBody($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedForElement($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedLanguageConstructArgument($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex); + } + + private function isExitStatement(Tokens $tokens, int $beforeOpenIndex): bool + { + return $tokens[$beforeOpenIndex]->isGivenKind(T_EXIT); + } + + private function isCloneStatement(Tokens $tokens, int $beforeOpenIndex): bool + { + return $tokens[$beforeOpenIndex]->isGivenKind(T_CLONE); + } + + private function isWrappedCloneArgument(Tokens $tokens, int $beforeOpenIndex, int $openIndex, int $closeIndex, int $afterCloseIndex): bool + { + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + + if ( + !( + $tokens[$beforeOpenIndex]->equals('?') // For BC reasons + || $this->isSimpleAssignment($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isSingleStatement($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedFnBody($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedForElement($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex) + ) + ) { + return false; + } + + $newCandidateIndex = $tokens->getNextMeaningfulToken($openIndex); + + if ($tokens[$newCandidateIndex]->isGivenKind(T_NEW)) { + $openIndex = $newCandidateIndex; // `clone (new X)`, `clone (new X())`, clone (new X(Y))` + } + + return !$this->containsOperation($tokens, $openIndex, $closeIndex); + } + + private function getIndexOfInstanceOfStatement(Tokens $tokens, int $openIndex, int $closeIndex): ?int + { + $instanceOfIndex = $tokens->findGivenKind(T_INSTANCEOF, $openIndex, $closeIndex); + + return 1 === \count($instanceOfIndex) ? array_key_first($instanceOfIndex) : null; + } + + private function isWrappedInstanceOf(Tokens $tokens, int $instanceOfIndex, int $beforeOpenIndex, int $openIndex, int $closeIndex, int $afterCloseIndex): bool + { + if ( + $this->containsOperation($tokens, $openIndex, $instanceOfIndex) + || $this->containsOperation($tokens, $instanceOfIndex, $closeIndex) + ) { + return false; + } + + if ($tokens[$beforeOpenIndex]->equals('!')) { + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + } + + return + $this->isSimpleAssignment($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isSingleStatement($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedFnBody($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedForElement($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex); + } + + private function isWrappedPartOfOperation(Tokens $tokens, int $beforeOpenIndex, int $openIndex, int $closeIndex, int $afterCloseIndex): bool + { + if ($this->containsOperation($tokens, $openIndex, $closeIndex)) { + return false; + } + + $boundariesMoved = false; + + if ($this->isPreUnaryOperation($tokens, $beforeOpenIndex)) { + $beforeOpenIndex = $this->getBeforePreUnaryOperation($tokens, $beforeOpenIndex); + $boundariesMoved = true; + } + + if ($this->isAccess($tokens, $afterCloseIndex)) { + $afterCloseIndex = $this->getAfterAccess($tokens, $afterCloseIndex); + $boundariesMoved = true; + + if ($this->tokensAnalyzer->isUnarySuccessorOperator($afterCloseIndex)) { // post unary operation are only valid here + $afterCloseIndex = $tokens->getNextMeaningfulToken($afterCloseIndex); + } + } + + if ($boundariesMoved) { + if ($this->isKnownNegativePre($tokens[$beforeOpenIndex])) { + return false; + } + + if ($this->isUselessWrapped($tokens, $beforeOpenIndex, $afterCloseIndex)) { + return true; + } + } + + // check if part of some operation sequence + + $beforeIsBinaryOperation = $this->tokensAnalyzer->isBinaryOperator($beforeOpenIndex); + $afterIsBinaryOperation = $this->tokensAnalyzer->isBinaryOperator($afterCloseIndex); + + if ($beforeIsBinaryOperation && $afterIsBinaryOperation) { + return true; // `+ (x) +` + } + + $beforeToken = $tokens[$beforeOpenIndex]; + $afterToken = $tokens[$afterCloseIndex]; + + $beforeIsBlockOpenOrComma = $beforeToken->equals(',') || null !== $this->getBlock($tokens, $beforeOpenIndex, true); + $afterIsBlockEndOrComma = $afterToken->equals(',') || null !== $this->getBlock($tokens, $afterCloseIndex, false); + + if (($beforeIsBlockOpenOrComma && $afterIsBinaryOperation) || ($beforeIsBinaryOperation && $afterIsBlockEndOrComma)) { + // $beforeIsBlockOpenOrComma && $afterIsBlockEndOrComma is covered by `isWrappedSequenceElement` + // `[ (x) +` or `+ (X) ]` or `, (X) +` or `+ (X) ,` + + return true; + } + + if ($tokens[$beforeOpenIndex]->equals('}')) { + $beforeIsStatementOpen = !$this->closeCurlyBelongsToDynamicElement($tokens, $beforeOpenIndex); + } else { + $beforeIsStatementOpen = $beforeToken->equalsAny(self::BEFORE_TYPES) || $beforeToken->isGivenKind(T_CASE); + } + + $afterIsStatementEnd = $afterToken->equalsAny([';', [T_CLOSE_TAG]]); + + return + ($beforeIsStatementOpen && $afterIsBinaryOperation) // `isGivenKind([T_PRINT, T_YIELD, T_YIELD_FROM, T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE])) { + return false; + } + + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + + return $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex); + } + + // any of `isGivenKind(T_CASE)) { + return $tokens[$afterCloseIndex]->equalsAny([':', ';']); // `switch case` + } + + if (!$tokens[$afterCloseIndex]->equalsAny([';', [T_CLOSE_TAG]])) { + return false; + } + + if ($tokens[$beforeOpenIndex]->equals('}')) { + return !$this->closeCurlyBelongsToDynamicElement($tokens, $beforeOpenIndex); + } + + return $tokens[$beforeOpenIndex]->equalsAny(self::BEFORE_TYPES); + } + + private function isSimpleAssignment(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex): bool + { + return $tokens[$beforeOpenIndex]->equals('=') && $tokens[$afterCloseIndex]->equalsAny([';', [T_CLOSE_TAG]]); // `= (X) ;` + } + + private function isWrappedSequenceElement(Tokens $tokens, int $startIndex, int $endIndex): bool + { + $startIsComma = $tokens[$startIndex]->equals(','); + $endIsComma = $tokens[$endIndex]->equals(','); + + if ($startIsComma && $endIsComma) { + return true; // `,(X),` + } + + $blockTypeStart = $this->getBlock($tokens, $startIndex, true); + $blockTypeEnd = $this->getBlock($tokens, $endIndex, false); + + return + ($startIsComma && null !== $blockTypeEnd) // `,(X)]` + || ($endIsComma && null !== $blockTypeStart) // `[(X),` + || (null !== $blockTypeEnd && null !== $blockTypeStart); // any type of `{(X)}`, `[(X)]` and `((X))` + } + + // any of `for( (X); ;(X)) ;` note that the middle element is covered as 'single statement' as it is `; (X) ;` + private function isWrappedForElement(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex): bool + { + $forCandidateIndex = null; + + if ($tokens[$beforeOpenIndex]->equals('(') && $tokens[$afterCloseIndex]->equals(';')) { + $forCandidateIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + } elseif ($tokens[$afterCloseIndex]->equals(')') && $tokens[$beforeOpenIndex]->equals(';')) { + $forCandidateIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $afterCloseIndex); + $forCandidateIndex = $tokens->getPrevMeaningfulToken($forCandidateIndex); + } + + return null !== $forCandidateIndex && $tokens[$forCandidateIndex]->isGivenKind(T_FOR); + } + + // `fn() => (X);` + private function isWrappedFnBody(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex): bool + { + if (!$tokens[$beforeOpenIndex]->isGivenKind(T_DOUBLE_ARROW)) { + return false; + } + + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + + if ($tokens[$beforeOpenIndex]->isGivenKind(T_STRING)) { + while (true) { + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + + if (!$tokens[$beforeOpenIndex]->isGivenKind([T_STRING, CT::T_TYPE_INTERSECTION, CT::T_TYPE_ALTERNATION])) { + break; + } + } + + if (!$tokens[$beforeOpenIndex]->isGivenKind(CT::T_TYPE_COLON)) { + return false; + } + + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + } + + if (!$tokens[$beforeOpenIndex]->equals(')')) { + return false; + } + + $beforeOpenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $beforeOpenIndex); + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + + if ($tokens[$beforeOpenIndex]->isGivenKind(CT::T_RETURN_REF)) { + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + } + + if (!$tokens[$beforeOpenIndex]->isGivenKind(T_FN)) { + return false; + } + + return $tokens[$afterCloseIndex]->equalsAny([';', ',', [T_CLOSE_TAG]]); + } + + private function isPreUnaryOperation(Tokens $tokens, int $index): bool + { + return $this->tokensAnalyzer->isUnaryPredecessorOperator($index) || $tokens[$index]->isCast(); + } + + private function getBeforePreUnaryOperation(Tokens $tokens, int $index): int + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while ($this->isPreUnaryOperation($tokens, $index)); + + return $index; + } + + // array access `(X)[` or `(X){` or object access `(X)->` or `(X)?->` + private function isAccess(Tokens $tokens, int $index): bool + { + $token = $tokens[$index]; + + return $token->isObjectOperator() || $token->equals('[') || $token->isGivenKind([CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN]); + } + + private function getAfterAccess(Tokens $tokens, int $index): int + { + while (true) { + $block = $this->getBlock($tokens, $index, true); + + if (null !== $block) { + $index = $tokens->findBlockEnd($block['type'], $index); + $index = $tokens->getNextMeaningfulToken($index); + + continue; + } + + if ( + $tokens[$index]->isObjectOperator() + || $tokens[$index]->equalsAny(['$', [T_PAAMAYIM_NEKUDOTAYIM], [T_STRING], [T_VARIABLE]]) + ) { + $index = $tokens->getNextMeaningfulToken($index); + + continue; + } + + break; + } + + return $index; + } + + /** + * @return null|array{type: Tokens::BLOCK_TYPE_*, isStart: bool} + */ + private function getBlock(Tokens $tokens, int $index, bool $isStart): ?array + { + $block = Tokens::detectBlockType($tokens[$index]); + + return null !== $block && $isStart === $block['isStart'] && \in_array($block['type'], self::BLOCK_TYPES, true) ? $block : null; + } + + // cheap check on a tokens type before `(` of which we know the `(` will never be superfluous + private function isKnownNegativePre(Token $token): bool + { + static $knownNegativeTypes; + + if (null === $knownNegativeTypes) { + $knownNegativeTypes = [ + [CT::T_CLASS_CONSTANT], + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + [CT::T_RETURN_REF], + [CT::T_USE_LAMBDA], + [T_ARRAY], + [T_CATCH], + [T_CLASS], + [T_DECLARE], + [T_ELSEIF], + [T_EMPTY], + [T_EXIT], + [T_EVAL], + [T_FN], + [T_FOREACH], + [T_FOR], + [T_FUNCTION], + [T_HALT_COMPILER], + [T_IF], + [T_ISSET], + [T_LIST], + [T_STRING], + [T_SWITCH], + [T_STATIC], + [T_UNSET], + [T_VARIABLE], + [T_WHILE], + // handled by the `include` rule + [T_REQUIRE], + [T_REQUIRE_ONCE], + [T_INCLUDE], + [T_INCLUDE_ONCE], + ]; + + if (\defined('T_MATCH')) { // @TODO: drop condition and add directly in `$knownNegativeTypes` above when PHP 8.0+ is required + $knownNegativeTypes[] = T_MATCH; + } + } + + return $token->equalsAny($knownNegativeTypes); + } + + private function containsOperation(Tokens $tokens, int $startIndex, int $endIndex): bool + { + while (true) { + $startIndex = $tokens->getNextMeaningfulToken($startIndex); + + if ($startIndex === $endIndex) { + break; + } + + $block = Tokens::detectBlockType($tokens[$startIndex]); + + if (null !== $block && $block['isStart']) { + $startIndex = $tokens->findBlockEnd($block['type'], $startIndex); + + continue; + } + + if (!$tokens[$startIndex]->equalsAny($this->noopTypes)) { + return true; + } + } + + return false; + } + + private function getConfigType(Tokens $tokens, int $beforeOpenIndex): ?string + { + if ($tokens[$beforeOpenIndex]->isGivenKind(self::TOKEN_TYPE_NO_CONFIG)) { + return null; + } + + foreach (self::TOKEN_TYPE_CONFIG_MAP as $type => $configItem) { + if ($tokens[$beforeOpenIndex]->isGivenKind($type)) { + return $configItem; + } + } + + return 'others'; + } + + private function removeUselessParenthesisPair( + Tokens $tokens, + int $beforeOpenIndex, + int $afterCloseIndex, + int $openIndex, + int $closeIndex, + ?string $configType + ): void { + $statements = $this->configuration['statements']; + + if (null === $configType || !\in_array($configType, $statements, true)) { + return; + } + + $needsSpaceAfter = + !$this->isAccess($tokens, $afterCloseIndex) + && !$tokens[$afterCloseIndex]->equalsAny([';', ',', [T_CLOSE_TAG]]) + && null === $this->getBlock($tokens, $afterCloseIndex, false) + && !($tokens[$afterCloseIndex]->equalsAny([':', ';']) && $tokens[$beforeOpenIndex]->isGivenKind(T_CASE)); + + $needsSpaceBefore = + !$this->isPreUnaryOperation($tokens, $beforeOpenIndex) + && !$tokens[$beforeOpenIndex]->equalsAny(['}', [T_EXIT], [T_OPEN_TAG]]) + && null === $this->getBlock($tokens, $beforeOpenIndex, true); + + $this->removeBrace($tokens, $closeIndex, $needsSpaceAfter); + $this->removeBrace($tokens, $openIndex, $needsSpaceBefore); + } + + private function removeBrace(Tokens $tokens, int $index, bool $needsSpace): void + { + if ($needsSpace) { + foreach ([-1, 1] as $direction) { + $siblingIndex = $tokens->getNonEmptySibling($index, $direction); + + if ($tokens[$siblingIndex]->isWhitespace() || $tokens[$siblingIndex]->isComment()) { + $needsSpace = false; + + break; + } + } + } + + if ($needsSpace) { + $tokens[$index] = new Token([T_WHITESPACE, ' ']); + } else { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + + private function closeCurlyBelongsToDynamicElement(Tokens $tokens, int $beforeOpenIndex): bool + { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $beforeOpenIndex); + $index = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(T_DOUBLE_COLON)) { + return true; + } + + if ($tokens[$index]->equals(':')) { + $index = $tokens->getPrevTokenOfKind($index, [[T_CASE], '?']); + + return !$tokens[$index]->isGivenKind(T_CASE); + } + + return false; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.php new file mode 100644 index 00000000..b71c524b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.php @@ -0,0 +1,92 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @deprecated + */ +final class NoUnneededCurlyBracesFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface +{ + private NoUnneededBracesFixer $noUnneededBracesFixer; + + public function __construct() + { + $this->noUnneededBracesFixer = new NoUnneededBracesFixer(); + + parent::__construct(); + } + + public function getDefinition(): FixerDefinitionInterface + { + $fixerDefinition = $this->noUnneededBracesFixer->getDefinition(); + + return new FixerDefinition( + 'Removes unneeded curly braces that are superfluous and aren\'t part of a control structure\'s body.', + $fixerDefinition->getCodeSamples(), + $fixerDefinition->getDescription(), + $fixerDefinition->getRiskyDescription() + ); + } + + public function configure(array $configuration): void + { + $this->noUnneededBracesFixer->configure($configuration); + + parent::configure($configuration); + } + + /** + * {@inheritdoc} + * + * Must run before NoUselessElseFixer, NoUselessReturnFixer, ReturnAssignmentFixer, SimplifiedIfReturnFixer. + */ + public function getPriority(): int + { + return $this->noUnneededBracesFixer->getPriority(); + } + + public function getSuccessorsNames(): array + { + return [ + $this->noUnneededBracesFixer->getName(), + ]; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('namespaces', 'Remove unneeded curly braces from bracketed namespaces.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function createProxyFixers(): array + { + return [ + $this->noUnneededBracesFixer, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUselessElseFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUselessElseFixer.php new file mode 100644 index 00000000..9b2d1cce --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUselessElseFixer.php @@ -0,0 +1,120 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractNoUselessElseFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +final class NoUselessElseFixer extends AbstractNoUselessElseFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_ELSE); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be useless `else` cases.', + [ + new CodeSample(" $token) { + if (!$token->isGivenKind(T_ELSE)) { + continue; + } + + // `else if` vs. `else` and alternative syntax `else:` checks + if ($tokens[$tokens->getNextMeaningfulToken($index)]->equalsAny([':', [T_IF]])) { + continue; + } + + // clean up `else` if it is an empty statement + $this->fixEmptyElse($tokens, $index); + if ($tokens->isEmptyAt($index)) { + continue; + } + + // clean up `else` if possible + if ($this->isSuperfluousElse($tokens, $index)) { + $this->clearElse($tokens, $index); + } + } + } + + /** + * Remove tokens part of an `else` statement if not empty (i.e. no meaningful tokens inside). + * + * @param int $index T_ELSE index + */ + private function fixEmptyElse(Tokens $tokens, int $index): void + { + $next = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$next]->equals('{')) { + $close = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $next); + if (1 === $close - $next) { // '{}' + $this->clearElse($tokens, $index); + } elseif ($tokens->getNextMeaningfulToken($next) === $close) { // '{/**/}' + $this->clearElse($tokens, $index); + } + + return; + } + + // short `else` + $end = $tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]); + if ($next === $end) { + $this->clearElse($tokens, $index); + } + } + + /** + * @param int $index index of T_ELSE + */ + private function clearElse(Tokens $tokens, int $index): void + { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + // clear T_ELSE and the '{' '}' if there are any + $next = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$next]->equals('{')) { + return; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $next)); + $tokens->clearTokenAndMergeSurroundingWhitespace($next); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SimplifiedIfReturnFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SimplifiedIfReturnFixer.php new file mode 100644 index 00000000..9710a9fd --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SimplifiedIfReturnFixer.php @@ -0,0 +1,138 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + */ +final class SimplifiedIfReturnFixer extends AbstractFixer +{ + /** + * @var list|string>}> + */ + private array $sequences = [ + [ + 'isNegative' => false, + 'sequence' => [ + '{', [T_RETURN], [T_STRING, 'true'], ';', '}', + [T_RETURN], [T_STRING, 'false'], ';', + ], + ], + [ + 'isNegative' => true, + 'sequence' => [ + '{', [T_RETURN], [T_STRING, 'false'], ';', '}', + [T_RETURN], [T_STRING, 'true'], ';', + ], + ], + [ + 'isNegative' => false, + 'sequence' => [ + [T_RETURN], [T_STRING, 'true'], ';', + [T_RETURN], [T_STRING, 'false'], ';', + ], + ], + [ + 'isNegative' => true, + 'sequence' => [ + [T_RETURN], [T_STRING, 'false'], ';', + [T_RETURN], [T_STRING, 'true'], ';', + ], + ], + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Simplify `if` control structures that return the boolean result of their condition.', + [new CodeSample("isAllTokenKindsFound([T_IF, T_RETURN, T_STRING]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($ifIndex = $tokens->count() - 1; 0 <= $ifIndex; --$ifIndex) { + if (!$tokens[$ifIndex]->isGivenKind([T_IF, T_ELSEIF])) { + continue; + } + + if ($tokens[$tokens->getPrevMeaningfulToken($ifIndex)]->equals(')')) { + continue; // in a loop without braces + } + + $startParenthesisIndex = $tokens->getNextTokenOfKind($ifIndex, ['(']); + $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex); + $firstCandidateIndex = $tokens->getNextMeaningfulToken($endParenthesisIndex); + + foreach ($this->sequences as $sequenceSpec) { + $sequenceFound = $tokens->findSequence($sequenceSpec['sequence'], $firstCandidateIndex); + + if (null === $sequenceFound) { + continue; + } + + $firstSequenceIndex = key($sequenceFound); + + if ($firstSequenceIndex !== $firstCandidateIndex) { + continue; + } + + $indicesToClear = array_keys($sequenceFound); + array_pop($indicesToClear); // Preserve last semicolon + rsort($indicesToClear); + + foreach ($indicesToClear as $index) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + + $newTokens = [ + new Token([T_RETURN, 'return']), + new Token([T_WHITESPACE, ' ']), + ]; + + if ($sequenceSpec['isNegative']) { + $newTokens[] = new Token('!'); + } else { + $newTokens[] = new Token([T_BOOL_CAST, '(bool)']); + } + + $tokens->overrideRange($ifIndex, $ifIndex, $newTokens); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php new file mode 100644 index 00000000..f5e2210f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php @@ -0,0 +1,87 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\ControlCaseStructuresAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶5.2. + */ +final class SwitchCaseSemicolonToColonFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'A case should be followed by a colon and not a semicolon.', + [ + new CodeSample( + 'isTokenKindFound(T_SWITCH); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + /** @var SwitchAnalysis $analysis */ + foreach (ControlCaseStructuresAnalyzer::findControlStructures($tokens, [T_SWITCH]) as $analysis) { + $default = $analysis->getDefaultAnalysis(); + + if (null !== $default) { + $this->fixTokenIfNeeded($tokens, $default->getColonIndex()); + } + + foreach ($analysis->getCases() as $caseAnalysis) { + $this->fixTokenIfNeeded($tokens, $caseAnalysis->getColonIndex()); + } + } + } + + private function fixTokenIfNeeded(Tokens $tokens, int $index): void + { + if ($tokens[$index]->equals(';')) { + $tokens[$index] = new Token(':'); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php new file mode 100644 index 00000000..5616e1f3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php @@ -0,0 +1,85 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\ControlCaseStructuresAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶5.2. + * + * @author Sullivan Senechal + */ +final class SwitchCaseSpaceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes extra spaces between colon and case value.', + [ + new CodeSample( + 'isTokenKindFound(T_SWITCH); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + /** @var SwitchAnalysis $analysis */ + foreach (ControlCaseStructuresAnalyzer::findControlStructures($tokens, [T_SWITCH]) as $analysis) { + $default = $analysis->getDefaultAnalysis(); + + if (null !== $default) { + $index = $default->getIndex(); + + if (!$tokens[$index + 1]->isWhitespace() || !$tokens[$index + 2]->equalsAny([':', ';'])) { + continue; + } + + $tokens->clearAt($index + 1); + } + + foreach ($analysis->getCases() as $caseAnalysis) { + $colonIndex = $caseAnalysis->getColonIndex(); + $valueIndex = $tokens->getPrevNonWhitespace($colonIndex); + + // skip if there is no space between the colon and previous token or is space after comment + if ($valueIndex === $colonIndex - 1 || $tokens[$valueIndex]->isComment()) { + continue; + } + + $tokens->clearAt($valueIndex + 1); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchContinueToBreakFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchContinueToBreakFixer.php new file mode 100644 index 00000000..23b523a8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchContinueToBreakFixer.php @@ -0,0 +1,240 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class SwitchContinueToBreakFixer extends AbstractFixer +{ + /** + * @var int[] + */ + private array $switchLevels = []; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Switch case must not be ended with `continue` but with `break`.', + [ + new CodeSample( + ' 3) { + continue; + } + + continue 2; + } +} +' + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run after NoAlternativeSyntaxFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAllTokenKindsFound([T_SWITCH, T_CONTINUE]) && !$tokens->hasAlternativeSyntax(); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $count = \count($tokens); + + for ($index = 1; $index < $count - 1; ++$index) { + $index = $this->doFix($tokens, $index, 0, false); + } + } + + /** + * @param int $depth >= 0 + */ + private function doFix(Tokens $tokens, int $index, int $depth, bool $isInSwitch): int + { + $token = $tokens[$index]; + + if ($token->isGivenKind([T_FOREACH, T_FOR, T_WHILE])) { + // go to first `(`, go to its close ')', go to first of '{', ';', '? >' + $index = $tokens->getNextTokenOfKind($index, ['(']); + $index = $tokens->getNextTokenOfKind($index, [')']); + $index = $tokens->getNextTokenOfKind($index, ['{', ';', [T_CLOSE_TAG]]); + + if (!$tokens[$index]->equals('{')) { + return $index; + } + + return $this->fixInLoop($tokens, $index, $depth + 1); + } + + if ($token->isGivenKind(T_DO)) { + return $this->fixInLoop($tokens, $tokens->getNextTokenOfKind($index, ['{']), $depth + 1); + } + + if ($token->isGivenKind(T_SWITCH)) { + return $this->fixInSwitch($tokens, $index, $depth + 1); + } + + if ($token->isGivenKind(T_CONTINUE)) { + return $this->fixContinueWhenActsAsBreak($tokens, $index, $isInSwitch, $depth); + } + + return $index; + } + + private function fixInSwitch(Tokens $tokens, int $switchIndex, int $depth): int + { + $this->switchLevels[] = $depth; + + // figure out where the switch starts + $openIndex = $tokens->getNextTokenOfKind($switchIndex, ['{']); + + // figure out where the switch ends + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openIndex); + + for ($index = $openIndex + 1; $index < $closeIndex; ++$index) { + $index = $this->doFix($tokens, $index, $depth, true); + } + + array_pop($this->switchLevels); + + return $closeIndex; + } + + private function fixInLoop(Tokens $tokens, int $openIndex, int $depth): int + { + $openCount = 1; + + while (true) { + ++$openIndex; + $token = $tokens[$openIndex]; + + if ($token->equals('{')) { + ++$openCount; + + continue; + } + + if ($token->equals('}')) { + --$openCount; + + if (0 === $openCount) { + break; + } + + continue; + } + + $openIndex = $this->doFix($tokens, $openIndex, $depth, false); + } + + return $openIndex; + } + + private function fixContinueWhenActsAsBreak(Tokens $tokens, int $continueIndex, bool $isInSwitch, int $depth): int + { + $followingContinueIndex = $tokens->getNextMeaningfulToken($continueIndex); + $followingContinueToken = $tokens[$followingContinueIndex]; + + if ($isInSwitch && $followingContinueToken->equals(';')) { + $this->replaceContinueWithBreakToken($tokens, $continueIndex); // short continue 1 notation + + return $followingContinueIndex; + } + + if (!$followingContinueToken->isGivenKind(T_LNUMBER)) { + return $followingContinueIndex; + } + + $afterFollowingContinueIndex = $tokens->getNextMeaningfulToken($followingContinueIndex); + + if (!$tokens[$afterFollowingContinueIndex]->equals(';')) { + return $afterFollowingContinueIndex; // if next not is `;` return without fixing, for example `continue 1 ? >getContent(); + $jump = str_replace('_', '', $jump); // support for numeric_literal_separator + + if (\strlen($jump) > 2 && 'x' === $jump[1]) { + $jump = hexdec($jump); // hexadecimal - 0x1 + } elseif (\strlen($jump) > 2 && 'b' === $jump[1]) { + $jump = bindec($jump); // binary - 0b1 + } elseif (\strlen($jump) > 1 && '0' === $jump[0]) { + $jump = octdec($jump); // octal 01 + } elseif (Preg::match('#^\d+$#', $jump)) { // positive int + $jump = (float) $jump; // cast to float, might be a number bigger than PHP max. int value + } else { + return $afterFollowingContinueIndex; // cannot process value, ignore + } + + if ($jump > PHP_INT_MAX) { + return $afterFollowingContinueIndex; // cannot process value, ignore + } + + $jump = (int) $jump; + + if ($isInSwitch && (1 === $jump || 0 === $jump)) { + $this->replaceContinueWithBreakToken($tokens, $continueIndex); // long continue 0/1 notation + + return $afterFollowingContinueIndex; + } + + $jumpDestination = $depth - $jump + 1; + + if (\in_array($jumpDestination, $this->switchLevels, true)) { + $this->replaceContinueWithBreakToken($tokens, $continueIndex); + + return $afterFollowingContinueIndex; + } + + return $afterFollowingContinueIndex; + } + + private function replaceContinueWithBreakToken(Tokens $tokens, int $index): void + { + $tokens[$index] = new Token([T_BREAK, 'break']); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/TrailingCommaInMultilineFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/TrailingCommaInMultilineFixer.php new file mode 100644 index 00000000..19cfffe8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/TrailingCommaInMultilineFixer.php @@ -0,0 +1,233 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerConfiguration\InvalidOptionsForEnvException; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use Symfony\Component\OptionsResolver\Options; + +/** + * @author Sebastiaan Stok + * @author Dariusz Rumiński + * @author Kuba Werłos + */ +final class TrailingCommaInMultilineFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const ELEMENTS_ARRAYS = 'arrays'; + + /** + * @internal + */ + public const ELEMENTS_ARGUMENTS = 'arguments'; + + /** + * @internal + */ + public const ELEMENTS_PARAMETERS = 'parameters'; + + private const MATCH_EXPRESSIONS = 'match'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Multi-line arrays, arguments list, parameters list and `match` expressions must have a trailing comma.', + [ + new CodeSample(" true] + ), + new CodeSample(" [self::ELEMENTS_ARGUMENTS]]), + new VersionSpecificCodeSample(" [self::ELEMENTS_PARAMETERS]]), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN, '(']); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('after_heredoc', 'Whether a trailing comma should also be placed after heredoc end.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('elements', sprintf('Where to fix multiline trailing comma (PHP >= 8.0 for `%s` and `%s`).', self::ELEMENTS_PARAMETERS, self::MATCH_EXPRESSIONS))) // @TODO: remove text when PHP 8.0+ is required + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset([self::ELEMENTS_ARRAYS, self::ELEMENTS_ARGUMENTS, self::ELEMENTS_PARAMETERS, self::MATCH_EXPRESSIONS])]) + ->setDefault([self::ELEMENTS_ARRAYS]) + ->setNormalizer(static function (Options $options, $value) { + if (\PHP_VERSION_ID < 8_00_00) { // @TODO: drop condition when PHP 8.0+ is required + foreach ([self::ELEMENTS_PARAMETERS, self::MATCH_EXPRESSIONS] as $option) { + if (\in_array($option, $value, true)) { + throw new InvalidOptionsForEnvException(sprintf('"%s" option can only be enabled with PHP 8.0+.', $option)); + } + } + } + + return $value; + }) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $fixArrays = \in_array(self::ELEMENTS_ARRAYS, $this->configuration['elements'], true); + $fixArguments = \in_array(self::ELEMENTS_ARGUMENTS, $this->configuration['elements'], true); + $fixParameters = \PHP_VERSION_ID >= 8_00_00 && \in_array(self::ELEMENTS_PARAMETERS, $this->configuration['elements'], true); // @TODO: drop condition when PHP 8.0+ is required + $fixMatch = \PHP_VERSION_ID >= 8_00_00 && \in_array(self::MATCH_EXPRESSIONS, $this->configuration['elements'], true); // @TODO: drop condition when PHP 8.0+ is required + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if ( + $fixArrays + && ( + $tokens[$index]->equals('(') && $tokens[$prevIndex]->isGivenKind(T_ARRAY) // long syntax + || $tokens[$index]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN) // short syntax + ) + ) { + $this->fixBlock($tokens, $index); + + continue; + } + + if (!$tokens[$index]->equals('(')) { + continue; + } + + $prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + + if ($fixArguments + && $tokens[$prevIndex]->equalsAny([']', [T_CLASS], [T_STRING], [T_VARIABLE], [T_STATIC]]) + && !$tokens[$prevPrevIndex]->isGivenKind(T_FUNCTION) + ) { + $this->fixBlock($tokens, $index); + + continue; + } + + if ( + $fixParameters + && ( + $tokens[$prevIndex]->isGivenKind(T_STRING) && $tokens[$prevPrevIndex]->isGivenKind(T_FUNCTION) + || $tokens[$prevIndex]->isGivenKind([T_FN, T_FUNCTION]) + ) + ) { + $this->fixBlock($tokens, $index); + } + + if ($fixMatch && $tokens[$prevIndex]->isGivenKind(T_MATCH)) { + $this->fixMatch($tokens, $index); + } + } + } + + private function fixBlock(Tokens $tokens, int $startIndex): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + if (!$tokensAnalyzer->isBlockMultiline($tokens, $startIndex)) { + return; + } + + $blockType = Tokens::detectBlockType($tokens[$startIndex]); + $endIndex = $tokens->findBlockEnd($blockType['type'], $startIndex); + + $beforeEndIndex = $tokens->getPrevMeaningfulToken($endIndex); + if (!$tokens->isPartialCodeMultiline($beforeEndIndex, $endIndex)) { + return; + } + $beforeEndToken = $tokens[$beforeEndIndex]; + + // if there is some item between braces then add `,` after it + if ( + $startIndex !== $beforeEndIndex && !$beforeEndToken->equals(',') + && (true === $this->configuration['after_heredoc'] || !$beforeEndToken->isGivenKind(T_END_HEREDOC)) + ) { + $tokens->insertAt($beforeEndIndex + 1, new Token(',')); + + $endToken = $tokens[$endIndex]; + + if (!$endToken->isComment() && !$endToken->isWhitespace()) { + $tokens->ensureWhitespaceAtIndex($endIndex, 1, ' '); + } + } + } + + private function fixMatch(Tokens $tokens, int $index): void + { + $index = $tokens->getNextTokenOfKind($index, ['{']); + $closeIndex = $index; + $isMultiline = false; + $depth = 1; + + do { + ++$closeIndex; + + if ($tokens[$closeIndex]->equals('{')) { + ++$depth; + } elseif ($tokens[$closeIndex]->equals('}')) { + --$depth; + } elseif (!$isMultiline && str_contains($tokens[$closeIndex]->getContent(), "\n")) { + $isMultiline = true; + } + } while ($depth > 0); + + if (!$isMultiline) { + return; + } + + $previousIndex = $tokens->getPrevMeaningfulToken($closeIndex); + if (!$tokens->isPartialCodeMultiline($previousIndex, $closeIndex)) { + return; + } + + if (!$tokens[$previousIndex]->equals(',')) { + $tokens->insertAt($previousIndex + 1, new Token(',')); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/YodaStyleFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/YodaStyleFixer.php new file mode 100644 index 00000000..0a267465 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/YodaStyleFixer.php @@ -0,0 +1,738 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Bram Gotink + * @author Dariusz Rumiński + */ +final class YodaStyleFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private $candidatesMap; + + /** + * @var array + */ + private $candidateTypesConfiguration; + + /** + * @var array + */ + private $candidateTypes; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->resolveConfiguration(); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Write conditions in Yoda style (`true`), non-Yoda style (`[\'equal\' => false, \'identical\' => false, \'less_and_greater\' => false]`) or ignore those conditions (`null`) based on configuration.', + [ + new CodeSample( + ' 3; // less than +', + [ + 'equal' => true, + 'identical' => false, + 'less_and_greater' => null, + ] + ), + new CodeSample( + ' true, + ] + ), + new CodeSample( + ' false, + 'identical' => false, + 'less_and_greater' => false, + ] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run after IsNullFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound($this->candidateTypes); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->fixTokens($tokens); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('equal', 'Style for equal (`==`, `!=`) statements.')) + ->setAllowedTypes(['bool', 'null']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('identical', 'Style for identical (`===`, `!==`) statements.')) + ->setAllowedTypes(['bool', 'null']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('less_and_greater', 'Style for less and greater than (`<`, `<=`, `>`, `>=`) statements.')) + ->setAllowedTypes(['bool', 'null']) + ->setDefault(null) + ->getOption(), + (new FixerOptionBuilder('always_move_variable', 'Whether variables should always be on non assignable side when applying Yoda style.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * Finds the end of the right-hand side of the comparison at the given + * index. + * + * The right-hand side ends when an operator with a lower precedence is + * encountered or when the block level for `()`, `{}` or `[]` goes below + * zero. + * + * @param Tokens $tokens The token list + * @param int $index The index of the comparison + * + * @return int The last index of the right-hand side of the comparison + */ + private function findComparisonEnd(Tokens $tokens, int $index): int + { + ++$index; + $count = \count($tokens); + + while ($index < $count) { + $token = $tokens[$index]; + + if ($token->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) { + ++$index; + + continue; + } + + if ($this->isOfLowerPrecedence($token)) { + break; + } + + $block = Tokens::detectBlockType($token); + + if (null === $block) { + ++$index; + + continue; + } + + if (!$block['isStart']) { + break; + } + + $index = $tokens->findBlockEnd($block['type'], $index) + 1; + } + + $prev = $tokens->getPrevMeaningfulToken($index); + + return $tokens[$prev]->isGivenKind(T_CLOSE_TAG) ? $tokens->getPrevMeaningfulToken($prev) : $prev; + } + + /** + * Finds the start of the left-hand side of the comparison at the given + * index. + * + * The left-hand side ends when an operator with a lower precedence is + * encountered or when the block level for `()`, `{}` or `[]` goes below + * zero. + * + * @param Tokens $tokens The token list + * @param int $index The index of the comparison + * + * @return int The first index of the left-hand side of the comparison + */ + private function findComparisonStart(Tokens $tokens, int $index): int + { + --$index; + $nonBlockFound = false; + + while (0 <= $index) { + $token = $tokens[$index]; + + if ($token->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) { + --$index; + + continue; + } + + if ($token->isGivenKind([CT::T_NAMED_ARGUMENT_COLON])) { + break; + } + + if ($this->isOfLowerPrecedence($token)) { + break; + } + + $block = Tokens::detectBlockType($token); + + if (null === $block) { + --$index; + $nonBlockFound = true; + + continue; + } + + if ( + $block['isStart'] + || ($nonBlockFound && Tokens::BLOCK_TYPE_CURLY_BRACE === $block['type']) // closing of structure not related to the comparison + ) { + break; + } + + $index = $tokens->findBlockStart($block['type'], $index) - 1; + } + + return $tokens->getNextMeaningfulToken($index); + } + + private function fixTokens(Tokens $tokens): Tokens + { + for ($i = \count($tokens) - 1; $i > 1; --$i) { + if ($tokens[$i]->isGivenKind($this->candidateTypes)) { + $yoda = $this->candidateTypesConfiguration[$tokens[$i]->getId()]; + } elseif ( + ($tokens[$i]->equals('<') && \in_array('<', $this->candidateTypes, true)) + || ($tokens[$i]->equals('>') && \in_array('>', $this->candidateTypes, true)) + ) { + $yoda = $this->candidateTypesConfiguration[$tokens[$i]->getContent()]; + } else { + continue; + } + + $fixableCompareInfo = $this->getCompareFixableInfo($tokens, $i, $yoda); + + if (null === $fixableCompareInfo) { + continue; + } + + $i = $this->fixTokensCompare( + $tokens, + $fixableCompareInfo['left']['start'], + $fixableCompareInfo['left']['end'], + $i, + $fixableCompareInfo['right']['start'], + $fixableCompareInfo['right']['end'] + ); + } + + return $tokens; + } + + /** + * Fixes the comparison at the given index. + * + * A comparison is considered fixed when + * - both sides are a variable (e.g. $a === $b) + * - neither side is a variable (e.g. self::CONST === 3) + * - only the right-hand side is a variable (e.g. 3 === self::$var) + * + * If the left-hand side and right-hand side of the given comparison are + * swapped, this function runs recursively on the previous left-hand-side. + * + * @return int an upper bound for all non-fixed comparisons + */ + private function fixTokensCompare( + Tokens $tokens, + int $startLeft, + int $endLeft, + int $compareOperatorIndex, + int $startRight, + int $endRight + ): int { + $type = $tokens[$compareOperatorIndex]->getId(); + $content = $tokens[$compareOperatorIndex]->getContent(); + + if (\array_key_exists($type, $this->candidatesMap)) { + $tokens[$compareOperatorIndex] = clone $this->candidatesMap[$type]; + } elseif (\array_key_exists($content, $this->candidatesMap)) { + $tokens[$compareOperatorIndex] = clone $this->candidatesMap[$content]; + } + + $right = $this->fixTokensComparePart($tokens, $startRight, $endRight); + $left = $this->fixTokensComparePart($tokens, $startLeft, $endLeft); + + for ($i = $startRight; $i <= $endRight; ++$i) { + $tokens->clearAt($i); + } + + for ($i = $startLeft; $i <= $endLeft; ++$i) { + $tokens->clearAt($i); + } + + $tokens->insertAt($startRight, $left); + $tokens->insertAt($startLeft, $right); + + return $startLeft; + } + + private function fixTokensComparePart(Tokens $tokens, int $start, int $end): Tokens + { + $newTokens = $tokens->generatePartialCode($start, $end); + $newTokens = $this->fixTokens(Tokens::fromCode(sprintf('clearAt(\count($newTokens) - 1); + $newTokens->clearAt(0); + $newTokens->clearEmptyTokens(); + + return $newTokens; + } + + private function getCompareFixableInfo(Tokens $tokens, int $index, bool $yoda): ?array + { + $right = $this->getRightSideCompareFixableInfo($tokens, $index); + + if (!$yoda && $this->isOfLowerPrecedenceAssignment($tokens[$tokens->getNextMeaningfulToken($right['end'])])) { + return null; + } + + $left = $this->getLeftSideCompareFixableInfo($tokens, $index); + + if ($this->isListStatement($tokens, $left['start'], $left['end']) || $this->isListStatement($tokens, $right['start'], $right['end'])) { + return null; // do not fix lists assignment inside statements + } + + /** @var bool $strict */ + $strict = $this->configuration['always_move_variable']; + $leftSideIsVariable = $this->isVariable($tokens, $left['start'], $left['end'], $strict); + $rightSideIsVariable = $this->isVariable($tokens, $right['start'], $right['end'], $strict); + + if (!($leftSideIsVariable xor $rightSideIsVariable)) { + return null; // both are (not) variables, do not touch + } + + if (!$strict) { // special handling for braces with not "always_move_variable" + $leftSideIsVariable = $leftSideIsVariable && !$tokens[$left['start']]->equals('('); + $rightSideIsVariable = $rightSideIsVariable && !$tokens[$right['start']]->equals('('); + } + + return ($yoda && !$leftSideIsVariable) || (!$yoda && !$rightSideIsVariable) + ? null + : ['left' => $left, 'right' => $right]; + } + + /** + * @return array{start: int, end: int} + */ + private function getLeftSideCompareFixableInfo(Tokens $tokens, int $index): array + { + return [ + 'start' => $this->findComparisonStart($tokens, $index), + 'end' => $tokens->getPrevMeaningfulToken($index), + ]; + } + + /** + * @return array{start: int, end: int} + */ + private function getRightSideCompareFixableInfo(Tokens $tokens, int $index): array + { + return [ + 'start' => $tokens->getNextMeaningfulToken($index), + 'end' => $this->findComparisonEnd($tokens, $index), + ]; + } + + private function isListStatement(Tokens $tokens, int $index, int $end): bool + { + for ($i = $index; $i <= $end; ++$i) { + if ($tokens[$i]->isGivenKind([T_LIST, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE])) { + return true; + } + } + + return false; + } + + /** + * Checks whether the given token has a lower precedence than `T_IS_EQUAL` + * or `T_IS_IDENTICAL`. + * + * @param Token $token The token to check + * + * @return bool Whether the token has a lower precedence + */ + private function isOfLowerPrecedence(Token $token): bool + { + static $tokens; + + if (null === $tokens) { + $tokens = [ + T_BOOLEAN_AND, // && + T_BOOLEAN_OR, // || + T_CASE, // case + T_DOUBLE_ARROW, // => + T_ECHO, // echo + T_GOTO, // goto + T_LOGICAL_AND, // and + T_LOGICAL_OR, // or + T_LOGICAL_XOR, // xor + T_OPEN_TAG, // isOfLowerPrecedenceAssignment($token) || $token->isGivenKind($tokens) || $token->equalsAny($otherTokens); + } + + /** + * Checks whether the given assignment token has a lower precedence than `T_IS_EQUAL` + * or `T_IS_IDENTICAL`. + */ + private function isOfLowerPrecedenceAssignment(Token $token): bool + { + static $tokens; + + if (null === $tokens) { + $tokens = [ + T_AND_EQUAL, // &= + T_CONCAT_EQUAL, // .= + T_DIV_EQUAL, // /= + T_MINUS_EQUAL, // -= + T_MOD_EQUAL, // %= + T_MUL_EQUAL, // *= + T_OR_EQUAL, // |= + T_PLUS_EQUAL, // += + T_POW_EQUAL, // **= + T_SL_EQUAL, // <<= + T_SR_EQUAL, // >>= + T_XOR_EQUAL, // ^= + T_COALESCE_EQUAL, // ??= + ]; + } + + return $token->equals('=') || $token->isGivenKind($tokens); + } + + /** + * Checks whether the tokens between the given start and end describe a + * variable. + * + * @param Tokens $tokens The token list + * @param int $start The first index of the possible variable + * @param int $end The last index of the possible variable + * @param bool $strict Enable strict variable detection + * + * @return bool Whether the tokens describe a variable + */ + private function isVariable(Tokens $tokens, int $start, int $end, bool $strict): bool + { + $tokenAnalyzer = new TokensAnalyzer($tokens); + + if ($start === $end) { + return $tokens[$start]->isGivenKind(T_VARIABLE); + } + + if ($tokens[$start]->equals('(')) { + return true; + } + + if ($strict) { + for ($index = $start; $index <= $end; ++$index) { + if ( + $tokens[$index]->isCast() + || $tokens[$index]->isGivenKind(T_INSTANCEOF) + || $tokens[$index]->equals('!') + || $tokenAnalyzer->isBinaryOperator($index) + ) { + return false; + } + } + } + + $index = $start; + + // handle multiple braces around statement ((($a === 1))) + while ( + $tokens[$index]->equals('(') + && $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index) === $end + ) { + $index = $tokens->getNextMeaningfulToken($index); + $end = $tokens->getPrevMeaningfulToken($end); + } + + $expectString = false; + + while ($index <= $end) { + $current = $tokens[$index]; + if ($current->isComment() || $current->isWhitespace() || $tokens->isEmptyAt($index)) { + ++$index; + + continue; + } + + // check if this is the last token + if ($index === $end) { + return $current->isGivenKind($expectString ? T_STRING : T_VARIABLE); + } + + if ($current->isGivenKind([T_LIST, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE])) { + return false; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + $next = $tokens[$nextIndex]; + + // self:: or ClassName:: + if ($current->isGivenKind(T_STRING) && $next->isGivenKind(T_DOUBLE_COLON)) { + $index = $tokens->getNextMeaningfulToken($nextIndex); + + continue; + } + + // \ClassName + if ($current->isGivenKind(T_NS_SEPARATOR) && $next->isGivenKind(T_STRING)) { + $index = $nextIndex; + + continue; + } + + // ClassName\ + if ($current->isGivenKind(T_STRING) && $next->isGivenKind(T_NS_SEPARATOR)) { + $index = $nextIndex; + + continue; + } + + // $a-> or a-> (as in $b->a->c) + if ($current->isGivenKind([T_STRING, T_VARIABLE]) && $next->isObjectOperator()) { + $index = $tokens->getNextMeaningfulToken($nextIndex); + $expectString = true; + + continue; + } + + // $a[...], a[...] (as in $c->a[$b]), $a{...} or a{...} (as in $c->a{$b}) + if ( + $current->isGivenKind($expectString ? T_STRING : T_VARIABLE) + && $next->equalsAny(['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{']]) + ) { + $index = $tokens->findBlockEnd( + $next->equals('[') ? Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE : Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE, + $nextIndex + ); + + if ($index === $end) { + return true; + } + + $index = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$index]->equalsAny(['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{']]) && !$tokens[$index]->isObjectOperator()) { + return false; + } + + $index = $tokens->getNextMeaningfulToken($index); + $expectString = true; + + continue; + } + + // $a(...) or $a->b(...) + if ($strict && $current->isGivenKind([T_STRING, T_VARIABLE]) && $next->equals('(')) { + return false; + } + + // {...} (as in $a->{$b}) + if ($expectString && $current->isGivenKind(CT::T_DYNAMIC_PROP_BRACE_OPEN)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_DYNAMIC_PROP_BRACE, $index); + if ($index === $end) { + return true; + } + + $index = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$index]->isObjectOperator()) { + return false; + } + + $index = $tokens->getNextMeaningfulToken($index); + $expectString = true; + + continue; + } + + break; + } + + return !$this->isConstant($tokens, $start, $end); + } + + private function isConstant(Tokens $tokens, int $index, int $end): bool + { + $expectArrayOnly = false; + $expectNumberOnly = false; + $expectNothing = false; + + for (; $index <= $end; ++$index) { + $token = $tokens[$index]; + + if ($token->isComment() || $token->isWhitespace()) { + continue; + } + + if ($expectNothing) { + return false; + } + + if ($expectArrayOnly) { + if ($token->equalsAny(['(', ')', [CT::T_ARRAY_SQUARE_BRACE_CLOSE]])) { + continue; + } + + return false; + } + + if ($token->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { + $expectArrayOnly = true; + + continue; + } + + if ($expectNumberOnly && !$token->isGivenKind([T_LNUMBER, T_DNUMBER])) { + return false; + } + + if ($token->equals('-')) { + $expectNumberOnly = true; + + continue; + } + + if ( + $token->isGivenKind([T_LNUMBER, T_DNUMBER, T_CONSTANT_ENCAPSED_STRING]) + || $token->equalsAny([[T_STRING, 'true'], [T_STRING, 'false'], [T_STRING, 'null']]) + ) { + $expectNothing = true; + + continue; + } + + return false; + } + + return true; + } + + private function resolveConfiguration(): void + { + $candidateTypes = []; + $this->candidatesMap = []; + + if (null !== $this->configuration['equal']) { + // `==`, `!=` and `<>` + $candidateTypes[T_IS_EQUAL] = $this->configuration['equal']; + $candidateTypes[T_IS_NOT_EQUAL] = $this->configuration['equal']; + } + + if (null !== $this->configuration['identical']) { + // `===` and `!==` + $candidateTypes[T_IS_IDENTICAL] = $this->configuration['identical']; + $candidateTypes[T_IS_NOT_IDENTICAL] = $this->configuration['identical']; + } + + if (null !== $this->configuration['less_and_greater']) { + // `<`, `<=`, `>` and `>=` + $candidateTypes[T_IS_SMALLER_OR_EQUAL] = $this->configuration['less_and_greater']; + $this->candidatesMap[T_IS_SMALLER_OR_EQUAL] = new Token([T_IS_GREATER_OR_EQUAL, '>=']); + + $candidateTypes[T_IS_GREATER_OR_EQUAL] = $this->configuration['less_and_greater']; + $this->candidatesMap[T_IS_GREATER_OR_EQUAL] = new Token([T_IS_SMALLER_OR_EQUAL, '<=']); + + $candidateTypes['<'] = $this->configuration['less_and_greater']; + $this->candidatesMap['<'] = new Token('>'); + + $candidateTypes['>'] = $this->configuration['less_and_greater']; + $this->candidatesMap['>'] = new Token('<'); + } + + $this->candidateTypesConfiguration = $candidateTypes; + $this->candidateTypes = array_keys($candidateTypes); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/DeprecatedFixerInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/DeprecatedFixerInterface.php new file mode 100644 index 00000000..6d7d7e84 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/DeprecatedFixerInterface.php @@ -0,0 +1,28 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +/** + * @author Kuba Werłos + */ +interface DeprecatedFixerInterface extends FixerInterface +{ + /** + * Returns names of fixers to use instead, if any. + * + * @return string[] + */ + public function getSuccessorsNames(): array; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php new file mode 100644 index 00000000..d4801c45 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php @@ -0,0 +1,99 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\DoctrineAnnotation; + +use PhpCsFixer\AbstractDoctrineAnnotationFixer; +use PhpCsFixer\Doctrine\Annotation\DocLexer; +use PhpCsFixer\Doctrine\Annotation\Tokens; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * Forces the configured operator for assignment in arrays in Doctrine Annotations. + */ +final class DoctrineAnnotationArrayAssignmentFixer extends AbstractDoctrineAnnotationFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Doctrine annotations must use configured operator for assignment in arrays.', + [ + new CodeSample( + " ':'] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before DoctrineAnnotationSpacesFixer. + */ + public function getPriority(): int + { + return 1; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $options = parent::createConfigurationDefinition()->getOptions(); + + $operator = new FixerOptionBuilder('operator', 'The operator to use.'); + $options[] = $operator + ->setAllowedValues(['=', ':']) + ->setDefault('=') + ->getOption() + ; + + return new FixerConfigurationResolver($options); + } + + protected function fixAnnotations(Tokens $doctrineAnnotationTokens): void + { + $scopes = []; + foreach ($doctrineAnnotationTokens as $token) { + if ($token->isType(DocLexer::T_OPEN_PARENTHESIS)) { + $scopes[] = 'annotation'; + + continue; + } + + if ($token->isType(DocLexer::T_OPEN_CURLY_BRACES)) { + $scopes[] = 'array'; + + continue; + } + + if ($token->isType([DocLexer::T_CLOSE_PARENTHESIS, DocLexer::T_CLOSE_CURLY_BRACES])) { + array_pop($scopes); + + continue; + } + + if ('array' === end($scopes) && $token->isType([DocLexer::T_EQUALS, DocLexer::T_COLON])) { + $token->setContent($this->configuration['operator']); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php new file mode 100644 index 00000000..ead0fb69 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php @@ -0,0 +1,116 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\DoctrineAnnotation; + +use PhpCsFixer\AbstractDoctrineAnnotationFixer; +use PhpCsFixer\Doctrine\Annotation\DocLexer; +use PhpCsFixer\Doctrine\Annotation\Token; +use PhpCsFixer\Doctrine\Annotation\Tokens; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * Adds braces to Doctrine annotations when missing. + */ +final class DoctrineAnnotationBracesFixer extends AbstractDoctrineAnnotationFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Doctrine annotations without arguments must use the configured syntax.', + [ + new CodeSample( + " 'with_braces'] + ), + ] + ); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + ...parent::createConfigurationDefinition()->getOptions(), + (new FixerOptionBuilder('syntax', 'Whether to add or remove braces.')) + ->setAllowedValues(['with_braces', 'without_braces']) + ->setDefault('without_braces') + ->getOption(), + ]); + } + + protected function fixAnnotations(Tokens $doctrineAnnotationTokens): void + { + if ('without_braces' === $this->configuration['syntax']) { + $this->removesBracesFromAnnotations($doctrineAnnotationTokens); + } else { + $this->addBracesToAnnotations($doctrineAnnotationTokens); + } + } + + private function addBracesToAnnotations(Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$tokens[$index]->isType(DocLexer::T_AT)) { + continue; + } + + $braceIndex = $tokens->getNextMeaningfulToken($index + 1); + if (null !== $braceIndex && $tokens[$braceIndex]->isType(DocLexer::T_OPEN_PARENTHESIS)) { + continue; + } + + $tokens->insertAt($index + 2, new Token(DocLexer::T_OPEN_PARENTHESIS, '(')); + $tokens->insertAt($index + 3, new Token(DocLexer::T_CLOSE_PARENTHESIS, ')')); + } + } + + private function removesBracesFromAnnotations(Tokens $tokens): void + { + for ($index = 0, $max = \count($tokens); $index < $max; ++$index) { + if (!$tokens[$index]->isType(DocLexer::T_AT)) { + continue; + } + + $openBraceIndex = $tokens->getNextMeaningfulToken($index + 1); + if (null === $openBraceIndex) { + continue; + } + + if (!$tokens[$openBraceIndex]->isType(DocLexer::T_OPEN_PARENTHESIS)) { + continue; + } + + $closeBraceIndex = $tokens->getNextMeaningfulToken($openBraceIndex); + if (null === $closeBraceIndex) { + continue; + } + + if (!$tokens[$closeBraceIndex]->isType(DocLexer::T_CLOSE_PARENTHESIS)) { + continue; + } + + for ($currentIndex = $index + 2; $currentIndex <= $closeBraceIndex; ++$currentIndex) { + $tokens[$currentIndex]->clear(); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php new file mode 100644 index 00000000..1359aef0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php @@ -0,0 +1,182 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\DoctrineAnnotation; + +use PhpCsFixer\AbstractDoctrineAnnotationFixer; +use PhpCsFixer\Doctrine\Annotation\DocLexer; +use PhpCsFixer\Doctrine\Annotation\Tokens; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; + +final class DoctrineAnnotationIndentationFixer extends AbstractDoctrineAnnotationFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Doctrine annotations must be indented with four spaces.', + [ + new CodeSample(" true] + ), + ] + ); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + ...parent::createConfigurationDefinition()->getOptions(), + (new FixerOptionBuilder('indent_mixed_lines', 'Whether to indent lines that have content before closing parenthesis.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function fixAnnotations(Tokens $doctrineAnnotationTokens): void + { + $annotationPositions = []; + for ($index = 0, $max = \count($doctrineAnnotationTokens); $index < $max; ++$index) { + if (!$doctrineAnnotationTokens[$index]->isType(DocLexer::T_AT)) { + continue; + } + + $annotationEndIndex = $doctrineAnnotationTokens->getAnnotationEnd($index); + if (null === $annotationEndIndex) { + return; + } + + $annotationPositions[] = [$index, $annotationEndIndex]; + $index = $annotationEndIndex; + } + + $indentLevel = 0; + foreach ($doctrineAnnotationTokens as $index => $token) { + if (!$token->isType(DocLexer::T_NONE) || !str_contains($token->getContent(), "\n")) { + continue; + } + + if (!$this->indentationCanBeFixed($doctrineAnnotationTokens, $index, $annotationPositions)) { + continue; + } + + $braces = $this->getLineBracesCount($doctrineAnnotationTokens, $index); + $delta = $braces[0] - $braces[1]; + $mixedBraces = 0 === $delta && $braces[0] > 0; + $extraIndentLevel = 0; + + if ($indentLevel > 0 && ($delta < 0 || $mixedBraces)) { + --$indentLevel; + + if (true === $this->configuration['indent_mixed_lines'] && $this->isClosingLineWithMeaningfulContent($doctrineAnnotationTokens, $index)) { + $extraIndentLevel = 1; + } + } + + $token->setContent(Preg::replace( + '/(\n( +\*)?) *$/', + '$1'.str_repeat(' ', 4 * ($indentLevel + $extraIndentLevel) + 1), + $token->getContent() + )); + + if ($delta > 0 || $mixedBraces) { + ++$indentLevel; + } + } + } + + /** + * @return int[] + */ + private function getLineBracesCount(Tokens $tokens, int $index): array + { + $opening = 0; + $closing = 0; + + while (isset($tokens[++$index])) { + $token = $tokens[$index]; + if ($token->isType(DocLexer::T_NONE) && str_contains($token->getContent(), "\n")) { + break; + } + + if ($token->isType([DocLexer::T_OPEN_PARENTHESIS, DocLexer::T_OPEN_CURLY_BRACES])) { + ++$opening; + + continue; + } + + if (!$token->isType([DocLexer::T_CLOSE_PARENTHESIS, DocLexer::T_CLOSE_CURLY_BRACES])) { + continue; + } + + if ($opening > 0) { + --$opening; + } else { + ++$closing; + } + } + + return [$opening, $closing]; + } + + private function isClosingLineWithMeaningfulContent(Tokens $tokens, int $index): bool + { + while (isset($tokens[++$index])) { + $token = $tokens[$index]; + if ($token->isType(DocLexer::T_NONE)) { + if (str_contains($token->getContent(), "\n")) { + return false; + } + + continue; + } + + return !$token->isType([DocLexer::T_CLOSE_PARENTHESIS, DocLexer::T_CLOSE_CURLY_BRACES]); + } + + return false; + } + + /** + * @param array> $annotationPositions Pairs of begin and end indices of main annotations + */ + private function indentationCanBeFixed(Tokens $tokens, int $newLineTokenIndex, array $annotationPositions): bool + { + foreach ($annotationPositions as $position) { + if ($newLineTokenIndex >= $position[0] && $newLineTokenIndex <= $position[1]) { + return true; + } + } + + for ($index = $newLineTokenIndex + 1, $max = \count($tokens); $index < $max; ++$index) { + $token = $tokens[$index]; + + if (str_contains($token->getContent(), "\n")) { + return false; + } + + return $tokens[$index]->isType(DocLexer::T_AT); + } + + return false; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.php new file mode 100644 index 00000000..0ee08482 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.php @@ -0,0 +1,290 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\DoctrineAnnotation; + +use PhpCsFixer\AbstractDoctrineAnnotationFixer; +use PhpCsFixer\Doctrine\Annotation\DocLexer; +use PhpCsFixer\Doctrine\Annotation\Token; +use PhpCsFixer\Doctrine\Annotation\Tokens; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; + +/** + * Fixes spaces around commas and assignment operators in Doctrine annotations. + */ +final class DoctrineAnnotationSpacesFixer extends AbstractDoctrineAnnotationFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Fixes spaces in Doctrine annotations.', + [ + new CodeSample( + " false, 'before_array_assignments_equals' => false] + ), + ], + 'There must not be any space around parentheses; commas must be preceded by no space and followed by one space; there must be no space around named arguments assignment operator; there must be one space around array assignment operator.' + ); + } + + /** + * {@inheritdoc} + * + * Must run after DoctrineAnnotationArrayAssignmentFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + ...parent::createConfigurationDefinition()->getOptions(), + (new FixerOptionBuilder('around_parentheses', 'Whether to fix spaces around parentheses.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('around_commas', 'Whether to fix spaces around commas.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('before_argument_assignments', 'Whether to add, remove or ignore spaces before argument assignment operator.')) + ->setAllowedTypes(['null', 'bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('after_argument_assignments', 'Whether to add, remove or ignore spaces after argument assignment operator.')) + ->setAllowedTypes(['null', 'bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('before_array_assignments_equals', 'Whether to add, remove or ignore spaces before array `=` assignment operator.')) + ->setAllowedTypes(['null', 'bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('after_array_assignments_equals', 'Whether to add, remove or ignore spaces after array assignment `=` operator.')) + ->setAllowedTypes(['null', 'bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('before_array_assignments_colon', 'Whether to add, remove or ignore spaces before array `:` assignment operator.')) + ->setAllowedTypes(['null', 'bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('after_array_assignments_colon', 'Whether to add, remove or ignore spaces after array assignment `:` operator.')) + ->setAllowedTypes(['null', 'bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + protected function fixAnnotations(Tokens $doctrineAnnotationTokens): void + { + if (true === $this->configuration['around_parentheses']) { + $this->fixSpacesAroundParentheses($doctrineAnnotationTokens); + } + + if (true === $this->configuration['around_commas']) { + $this->fixSpacesAroundCommas($doctrineAnnotationTokens); + } + + if ( + null !== $this->configuration['before_argument_assignments'] + || null !== $this->configuration['after_argument_assignments'] + || null !== $this->configuration['before_array_assignments_equals'] + || null !== $this->configuration['after_array_assignments_equals'] + || null !== $this->configuration['before_array_assignments_colon'] + || null !== $this->configuration['after_array_assignments_colon'] + ) { + $this->fixAroundAssignments($doctrineAnnotationTokens); + } + } + + private function fixSpacesAroundParentheses(Tokens $tokens): void + { + $inAnnotationUntilIndex = null; + + foreach ($tokens as $index => $token) { + if (null !== $inAnnotationUntilIndex) { + if ($index === $inAnnotationUntilIndex) { + $inAnnotationUntilIndex = null; + + continue; + } + } elseif ($tokens[$index]->isType(DocLexer::T_AT)) { + $endIndex = $tokens->getAnnotationEnd($index); + if (null !== $endIndex) { + $inAnnotationUntilIndex = $endIndex + 1; + } + + continue; + } + + if (null === $inAnnotationUntilIndex) { + continue; + } + + if (!$token->isType([DocLexer::T_OPEN_PARENTHESIS, DocLexer::T_CLOSE_PARENTHESIS])) { + continue; + } + + if ($token->isType(DocLexer::T_OPEN_PARENTHESIS)) { + $token = $tokens[$index - 1]; + if ($token->isType(DocLexer::T_NONE)) { + $token->clear(); + } + + $token = $tokens[$index + 1]; + } else { + $token = $tokens[$index - 1]; + } + + if ($token->isType(DocLexer::T_NONE)) { + if (str_contains($token->getContent(), "\n")) { + continue; + } + + $token->clear(); + } + } + } + + private function fixSpacesAroundCommas(Tokens $tokens): void + { + $inAnnotationUntilIndex = null; + + foreach ($tokens as $index => $token) { + if (null !== $inAnnotationUntilIndex) { + if ($index === $inAnnotationUntilIndex) { + $inAnnotationUntilIndex = null; + + continue; + } + } elseif ($tokens[$index]->isType(DocLexer::T_AT)) { + $endIndex = $tokens->getAnnotationEnd($index); + if (null !== $endIndex) { + $inAnnotationUntilIndex = $endIndex; + } + + continue; + } + + if (null === $inAnnotationUntilIndex) { + continue; + } + + if (!$token->isType(DocLexer::T_COMMA)) { + continue; + } + + $token = $tokens[$index - 1]; + if ($token->isType(DocLexer::T_NONE)) { + $token->clear(); + } + + if ($index < \count($tokens) - 1 && !Preg::match('/^\s/', $tokens[$index + 1]->getContent())) { + $tokens->insertAt($index + 1, new Token(DocLexer::T_NONE, ' ')); + } + } + } + + private function fixAroundAssignments(Tokens $tokens): void + { + $beforeArguments = $this->configuration['before_argument_assignments']; + $afterArguments = $this->configuration['after_argument_assignments']; + $beforeArraysEquals = $this->configuration['before_array_assignments_equals']; + $afterArraysEquals = $this->configuration['after_array_assignments_equals']; + $beforeArraysColon = $this->configuration['before_array_assignments_colon']; + $afterArraysColon = $this->configuration['after_array_assignments_colon']; + + $scopes = []; + foreach ($tokens as $index => $token) { + $endScopeType = end($scopes); + if (false !== $endScopeType && $token->isType($endScopeType)) { + array_pop($scopes); + + continue; + } + + if ($tokens[$index]->isType(DocLexer::T_AT)) { + $scopes[] = DocLexer::T_CLOSE_PARENTHESIS; + + continue; + } + + if ($tokens[$index]->isType(DocLexer::T_OPEN_CURLY_BRACES)) { + $scopes[] = DocLexer::T_CLOSE_CURLY_BRACES; + + continue; + } + + if (DocLexer::T_CLOSE_PARENTHESIS === $endScopeType && $token->isType(DocLexer::T_EQUALS)) { + $this->updateSpacesAfter($tokens, $index, $afterArguments); + $this->updateSpacesBefore($tokens, $index, $beforeArguments); + + continue; + } + + if (DocLexer::T_CLOSE_CURLY_BRACES === $endScopeType) { + if ($token->isType(DocLexer::T_EQUALS)) { + $this->updateSpacesAfter($tokens, $index, $afterArraysEquals); + $this->updateSpacesBefore($tokens, $index, $beforeArraysEquals); + + continue; + } + + if ($token->isType(DocLexer::T_COLON)) { + $this->updateSpacesAfter($tokens, $index, $afterArraysColon); + $this->updateSpacesBefore($tokens, $index, $beforeArraysColon); + } + } + } + } + + private function updateSpacesAfter(Tokens $tokens, int $index, ?bool $insert): void + { + $this->updateSpacesAt($tokens, $index + 1, $index + 1, $insert); + } + + private function updateSpacesBefore(Tokens $tokens, int $index, ?bool $insert): void + { + $this->updateSpacesAt($tokens, $index - 1, $index, $insert); + } + + private function updateSpacesAt(Tokens $tokens, int $index, int $insertIndex, ?bool $insert): void + { + if (null === $insert) { + return; + } + + $token = $tokens[$index]; + if ($insert) { + if (!$token->isType(DocLexer::T_NONE)) { + $tokens->insertAt($insertIndex, $token = new Token()); + } + + $token->setContent(' '); + } elseif ($token->isType(DocLexer::T_NONE)) { + $token->clear(); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FixerInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FixerInterface.php new file mode 100644 index 00000000..6e79741b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FixerInterface.php @@ -0,0 +1,79 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * @author Fabien Potencier + */ +interface FixerInterface +{ + /** + * Check if the fixer is a candidate for given Tokens collection. + * + * Fixer is a candidate when the collection contains tokens that may be fixed + * during fixer work. This could be considered as some kind of bloom filter. + * When this method returns true then to the Tokens collection may or may not + * need a fixing, but when this method returns false then the Tokens collection + * need no fixing for sure. + */ + public function isCandidate(Tokens $tokens): bool; + + /** + * Check if fixer is risky or not. + * + * Risky fixer could change code behavior! + */ + public function isRisky(): bool; + + /** + * Fixes a file. + * + * @param \SplFileInfo $file A \SplFileInfo instance + * @param Tokens $tokens Tokens collection + */ + public function fix(\SplFileInfo $file, Tokens $tokens): void; + + /** + * Returns the definition of the fixer. + */ + public function getDefinition(): FixerDefinitionInterface; + + /** + * Returns the name of the fixer. + * + * The name must be all lowercase and without any spaces. + * + * @return string The name of the fixer + */ + public function getName(): string; + + /** + * Returns the priority of the fixer. + * + * The default priority is 0 and higher priorities are executed first. + */ + public function getPriority(): int; + + /** + * Returns true if the file is supported by this fixer. + * + * @return bool true if the file is supported by this fixer, false otherwise + */ + public function supports(\SplFileInfo $file): bool; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/CombineNestedDirnameFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/CombineNestedDirnameFixer.php new file mode 100644 index 00000000..7a180998 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/CombineNestedDirnameFixer.php @@ -0,0 +1,224 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Gregor Harlan + */ +final class CombineNestedDirnameFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace multiple nested calls of `dirname` by only one call with second `$level` parameter. Requires PHP >= 7.0.', + [ + new CodeSample( + "isTokenKindFound(T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run before MethodArgumentSpaceFixer, NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer. + * Must run after DirConstantFixer. + */ + public function getPriority(): int + { + return 35; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + $dirnameInfo = $this->getDirnameInfo($tokens, $index); + + if (!$dirnameInfo) { + continue; + } + + $prev = $tokens->getPrevMeaningfulToken($dirnameInfo['indices'][0]); + + if (!$tokens[$prev]->equals('(')) { + continue; + } + + $prev = $tokens->getPrevMeaningfulToken($prev); + $firstArgumentEnd = $dirnameInfo['end']; + $dirnameInfoArray = [$dirnameInfo]; + + while ($dirnameInfo = $this->getDirnameInfo($tokens, $prev, $firstArgumentEnd)) { + $dirnameInfoArray[] = $dirnameInfo; + $prev = $tokens->getPrevMeaningfulToken($dirnameInfo['indices'][0]); + + if (!$tokens[$prev]->equals('(')) { + break; + } + + $prev = $tokens->getPrevMeaningfulToken($prev); + $firstArgumentEnd = $dirnameInfo['end']; + } + + if (\count($dirnameInfoArray) > 1) { + $this->combineDirnames($tokens, $dirnameInfoArray); + } + + $index = $prev; + } + } + + /** + * @param int $index Index of `dirname` + * @param null|int $firstArgumentEndIndex Index of last token of first argument of `dirname` call + * + * @return array{indices: list, secondArgument?: int, levels: int, end: int}|bool `false` when it is not a (supported) `dirname` call, an array with info about the dirname call otherwise + */ + private function getDirnameInfo(Tokens $tokens, int $index, ?int $firstArgumentEndIndex = null) + { + if (!$tokens[$index]->equals([T_STRING, 'dirname'], false)) { + return false; + } + + if (!(new FunctionsAnalyzer())->isGlobalFunctionCall($tokens, $index)) { + return false; + } + + $info = ['indices' => []]; + $prev = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prev]->isGivenKind(T_NS_SEPARATOR)) { + $info['indices'][] = $prev; + } + + $info['indices'][] = $index; + + // opening parenthesis "(" + $next = $tokens->getNextMeaningfulToken($index); + $info['indices'][] = $next; + + if (null !== $firstArgumentEndIndex) { + $next = $tokens->getNextMeaningfulToken($firstArgumentEndIndex); + } else { + $next = $tokens->getNextMeaningfulToken($next); + + if ($tokens[$next]->equals(')')) { + return false; + } + + while (!$tokens[$next]->equalsAny([',', ')'])) { + $blockType = Tokens::detectBlockType($tokens[$next]); + + if (null !== $blockType) { + $next = $tokens->findBlockEnd($blockType['type'], $next); + } + + $next = $tokens->getNextMeaningfulToken($next); + } + } + + $info['indices'][] = $next; + + if ($tokens[$next]->equals(',')) { + $next = $tokens->getNextMeaningfulToken($next); + $info['indices'][] = $next; + } + + if ($tokens[$next]->equals(')')) { + $info['levels'] = 1; + $info['end'] = $next; + + return $info; + } + + if (!$tokens[$next]->isGivenKind(T_LNUMBER)) { + return false; + } + + $info['secondArgument'] = $next; + $info['levels'] = (int) $tokens[$next]->getContent(); + + $next = $tokens->getNextMeaningfulToken($next); + + if ($tokens[$next]->equals(',')) { + $info['indices'][] = $next; + $next = $tokens->getNextMeaningfulToken($next); + } + + if (!$tokens[$next]->equals(')')) { + return false; + } + + $info['indices'][] = $next; + $info['end'] = $next; + + return $info; + } + + /** + * @param array, secondArgument?: int, levels: int, end: int}> $dirnameInfoArray + */ + private function combineDirnames(Tokens $tokens, array $dirnameInfoArray): void + { + $outerDirnameInfo = array_pop($dirnameInfoArray); + $levels = $outerDirnameInfo['levels']; + + foreach ($dirnameInfoArray as $dirnameInfo) { + $levels += $dirnameInfo['levels']; + + foreach ($dirnameInfo['indices'] as $index) { + $tokens->removeLeadingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + + $levelsToken = new Token([T_LNUMBER, (string) $levels]); + + if (isset($outerDirnameInfo['secondArgument'])) { + $tokens[$outerDirnameInfo['secondArgument']] = $levelsToken; + } else { + $prev = $tokens->getPrevMeaningfulToken($outerDirnameInfo['end']); + $items = []; + + if (!$tokens[$prev]->equals(',')) { + $items = [new Token(','), new Token([T_WHITESPACE, ' '])]; + } + + $items[] = $levelsToken; + $tokens->insertAt($outerDirnameInfo['end'], $items); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/DateTimeCreateFromFormatCallFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/DateTimeCreateFromFormatCallFixer.php new file mode 100644 index 00000000..5c72fcf2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/DateTimeCreateFromFormatCallFixer.php @@ -0,0 +1,163 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class DateTimeCreateFromFormatCallFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The first argument of `DateTime::createFromFormat` method must start with `!`.', + [ + new CodeSample("isTokenKindFound(T_DOUBLE_COLON); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); + + foreach ($tokens->getNamespaceDeclarations() as $namespace) { + $scopeStartIndex = $namespace->getScopeStartIndex(); + $useDeclarations = $namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace); + + for ($index = $namespace->getScopeEndIndex(); $index > $scopeStartIndex; --$index) { + if (!$tokens[$index]->isGivenKind(T_DOUBLE_COLON)) { + continue; + } + + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$functionNameIndex]->equals([T_STRING, 'createFromFormat'], false)) { + continue; + } + + if (!$tokens[$tokens->getNextMeaningfulToken($functionNameIndex)]->equals('(')) { + continue; + } + + $classNameIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$classNameIndex]->equalsAny([[T_STRING, 'DateTime'], [T_STRING, 'DateTimeImmutable']], false)) { + continue; + } + + $preClassNameIndex = $tokens->getPrevMeaningfulToken($classNameIndex); + + if ($tokens[$preClassNameIndex]->isGivenKind(T_NS_SEPARATOR)) { + if ($tokens[$tokens->getPrevMeaningfulToken($preClassNameIndex)]->isGivenKind(T_STRING)) { + continue; + } + } elseif (!$namespace->isGlobalNamespace()) { + continue; + } else { + foreach ($useDeclarations as $useDeclaration) { + foreach (['datetime', 'datetimeimmutable'] as $name) { + if ($name === strtolower($useDeclaration->getShortName()) && $name !== strtolower($useDeclaration->getFullName())) { + continue 3; + } + } + } + } + + $openIndex = $tokens->getNextTokenOfKind($functionNameIndex, ['(']); + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); + + $argumentIndex = $this->getFirstArgumentTokenIndex($tokens, $argumentsAnalyzer->getArguments($tokens, $openIndex, $closeIndex)); + + if (null === $argumentIndex) { + continue; + } + + $format = $tokens[$argumentIndex]->getContent(); + + if (\strlen($format) < 3) { + continue; + } + + $offset = 'b' === $format[0] || 'B' === $format[0] ? 2 : 1; + + if ('!' === $format[$offset]) { + continue; + } + + $tokens->clearAt($argumentIndex); + $tokens->insertAt($argumentIndex, new Token([T_CONSTANT_ENCAPSED_STRING, substr_replace($format, '!', $offset, 0)])); + } + } + } + + /** + * @param array $arguments + */ + private function getFirstArgumentTokenIndex(Tokens $tokens, array $arguments): ?int + { + if (2 !== \count($arguments)) { + return null; + } + + $argumentStartIndex = array_key_first($arguments); + $argumentEndIndex = $arguments[$argumentStartIndex]; + $argumentStartIndex = $tokens->getNextMeaningfulToken($argumentStartIndex - 1); + + if ( + $argumentStartIndex !== $argumentEndIndex + && $tokens->getNextMeaningfulToken($argumentStartIndex) <= $argumentEndIndex + ) { + return null; // argument is not a simple single string + } + + return !$tokens[$argumentStartIndex]->isGivenKind(T_CONSTANT_ENCAPSED_STRING) + ? null // first argument is not a string + : $argumentStartIndex; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagOrderFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagOrderFixer.php new file mode 100644 index 00000000..edf0bf6c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagOrderFixer.php @@ -0,0 +1,123 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFopenFlagFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class FopenFlagOrderFixer extends AbstractFopenFlagFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Order the flags in `fopen` calls, `b` and `t` must be last.', + [new CodeSample("isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) { + continue; + } + + if (null !== $argumentFlagIndex) { + return; // multiple meaningful tokens found, no candidate for fixing + } + + $argumentFlagIndex = $i; + } + + // check if second argument is candidate + if (null === $argumentFlagIndex || !$tokens[$argumentFlagIndex]->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) { + return; + } + + $content = $tokens[$argumentFlagIndex]->getContent(); + $contentQuote = $content[0]; // `'`, `"`, `b` or `B` + + if ('b' === $contentQuote || 'B' === $contentQuote) { + $binPrefix = $contentQuote; + $contentQuote = $content[1]; // `'` or `"` + $mode = substr($content, 2, -1); + } else { + $binPrefix = ''; + $mode = substr($content, 1, -1); + } + + $modeLength = \strlen($mode); + if ($modeLength < 2) { + return; // nothing to sort + } + + if (false === $this->isValidModeString($mode)) { + return; + } + + $split = $this->sortFlags(Preg::split('#([^\+]\+?)#', $mode, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)); + $newContent = $binPrefix.$contentQuote.implode('', $split).$contentQuote; + + if ($content !== $newContent) { + $tokens[$argumentFlagIndex] = new Token([T_CONSTANT_ENCAPSED_STRING, $newContent]); + } + } + + /** + * @param string[] $flags + * + * @return string[] + */ + private function sortFlags(array $flags): array + { + usort( + $flags, + static function (string $flag1, string $flag2): int { + if ($flag1 === $flag2) { + return 0; + } + + if ('b' === $flag1) { + return 1; + } + + if ('b' === $flag2) { + return -1; + } + + if ('t' === $flag1) { + return 1; + } + + if ('t' === $flag2) { + return -1; + } + + return $flag1 < $flag2 ? -1 : 1; + } + ); + + return $flags; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagsFixer.php new file mode 100644 index 00000000..a136c7b3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagsFixer.php @@ -0,0 +1,106 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFopenFlagFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class FopenFlagsFixer extends AbstractFopenFlagFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The flags in `fopen` calls must omit `t`, and `b` must be omitted or included consistently.', + [ + new CodeSample(" false]), + ], + null, + 'Risky when the function `fopen` is overridden.' + ); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('b_mode', 'The `b` flag must be used (`true`) or omitted (`false`).')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + protected function fixFopenFlagToken(Tokens $tokens, int $argumentStartIndex, int $argumentEndIndex): void + { + $argumentFlagIndex = null; + + for ($i = $argumentStartIndex; $i <= $argumentEndIndex; ++$i) { + if ($tokens[$i]->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) { + continue; + } + + if (null !== $argumentFlagIndex) { + return; // multiple meaningful tokens found, no candidate for fixing + } + + $argumentFlagIndex = $i; + } + + // check if second argument is candidate + if (null === $argumentFlagIndex || !$tokens[$argumentFlagIndex]->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) { + return; + } + + $content = $tokens[$argumentFlagIndex]->getContent(); + $contentQuote = $content[0]; // `'`, `"`, `b` or `B` + + if ('b' === $contentQuote || 'B' === $contentQuote) { + $binPrefix = $contentQuote; + $contentQuote = $content[1]; // `'` or `"` + $mode = substr($content, 2, -1); + } else { + $binPrefix = ''; + $mode = substr($content, 1, -1); + } + + if (false === $this->isValidModeString($mode)) { + return; + } + + $mode = str_replace('t', '', $mode); + + if (true === $this->configuration['b_mode']) { + if (!str_contains($mode, 'b')) { + $mode .= 'b'; + } + } else { + $mode = str_replace('b', '', $mode); + } + + $newContent = $binPrefix.$contentQuote.$mode.$contentQuote; + + if ($content !== $newContent) { + $tokens[$argumentFlagIndex] = new Token([T_CONSTANT_ENCAPSED_STRING, $newContent]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionDeclarationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionDeclarationFixer.php new file mode 100644 index 00000000..8e63c816 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionDeclarationFixer.php @@ -0,0 +1,246 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * Fixer for rules defined in PSR2 generally (¶1 and ¶6). + * + * @author Dariusz Rumiński + */ +final class FunctionDeclarationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const SPACING_NONE = 'none'; + + /** + * @internal + */ + public const SPACING_ONE = 'one'; + + private const SUPPORTED_SPACINGS = [self::SPACING_NONE, self::SPACING_ONE]; + + private string $singleLineWhitespaceOptions = " \t"; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([T_FUNCTION, T_FN]); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Spaces should be properly placed in a function declaration.', + [ + new CodeSample( + ' self::SPACING_NONE] + ), + new CodeSample( + ' null; +', + ['closure_fn_spacing' => self::SPACING_NONE] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before MethodArgumentSpaceFixer. + * Must run after SingleSpaceAfterConstructFixer, SingleSpaceAroundConstructFixer, UseArrowFunctionsFixer. + */ + public function getPriority(): int + { + return 31; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind([T_FUNCTION, T_FN])) { + continue; + } + + $startParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(', ';', [T_CLOSE_TAG]]); + + if (!$tokens[$startParenthesisIndex]->equals('(')) { + continue; + } + + $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex); + + if (false === $this->configuration['trailing_comma_single_line'] + && !$tokens->isPartialCodeMultiline($index, $endParenthesisIndex) + ) { + $commaIndex = $tokens->getPrevMeaningfulToken($endParenthesisIndex); + + if ($tokens[$commaIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex); + } + } + + $startBraceIndex = $tokens->getNextTokenOfKind($endParenthesisIndex, [';', '{', [T_DOUBLE_ARROW]]); + + // fix single-line whitespace before { or => + // eg: `function foo(){}` => `function foo() {}` + // eg: `function foo() {}` => `function foo() {}` + // eg: `fn() =>` => `fn() =>` + if ( + $tokens[$startBraceIndex]->equalsAny(['{', [T_DOUBLE_ARROW]]) + && ( + !$tokens[$startBraceIndex - 1]->isWhitespace() + || $tokens[$startBraceIndex - 1]->isWhitespace($this->singleLineWhitespaceOptions) + ) + ) { + $tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' '); + } + + $afterParenthesisIndex = $tokens->getNextNonWhitespace($endParenthesisIndex); + $afterParenthesisToken = $tokens[$afterParenthesisIndex]; + + if ($afterParenthesisToken->isGivenKind(CT::T_USE_LAMBDA)) { + // fix whitespace after CT:T_USE_LAMBDA (we might add a token, so do this before determining start and end parenthesis) + $tokens->ensureWhitespaceAtIndex($afterParenthesisIndex + 1, 0, ' '); + + $useStartParenthesisIndex = $tokens->getNextTokenOfKind($afterParenthesisIndex, ['(']); + $useEndParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $useStartParenthesisIndex); + + if (false === $this->configuration['trailing_comma_single_line'] + && !$tokens->isPartialCodeMultiline($index, $useEndParenthesisIndex) + ) { + $commaIndex = $tokens->getPrevMeaningfulToken($useEndParenthesisIndex); + + if ($tokens[$commaIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex); + } + } + + // remove single-line edge whitespaces inside use parentheses + $this->fixParenthesisInnerEdge($tokens, $useStartParenthesisIndex, $useEndParenthesisIndex); + + // fix whitespace before CT::T_USE_LAMBDA + $tokens->ensureWhitespaceAtIndex($afterParenthesisIndex - 1, 1, ' '); + } + + // remove single-line edge whitespaces inside parameters list parentheses + $this->fixParenthesisInnerEdge($tokens, $startParenthesisIndex, $endParenthesisIndex); + $isLambda = $tokensAnalyzer->isLambda($index); + + // remove whitespace before ( + // eg: `function foo () {}` => `function foo() {}` + if (!$isLambda && $tokens[$startParenthesisIndex - 1]->isWhitespace() && !$tokens[$tokens->getPrevNonWhitespace($startParenthesisIndex - 1)]->isComment()) { + $tokens->clearAt($startParenthesisIndex - 1); + } + + $option = $token->isGivenKind(T_FN) ? 'closure_fn_spacing' : 'closure_function_spacing'; + + if ($isLambda && self::SPACING_NONE === $this->configuration[$option]) { + // optionally remove whitespace after T_FUNCTION of a closure + // eg: `function () {}` => `function() {}` + if ($tokens[$index + 1]->isWhitespace()) { + $tokens->clearAt($index + 1); + } + } else { + // otherwise, enforce whitespace after T_FUNCTION + // eg: `function foo() {}` => `function foo() {}` + $tokens->ensureWhitespaceAtIndex($index + 1, 0, ' '); + } + + if ($isLambda) { + $prev = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prev]->isGivenKind(T_STATIC)) { + // fix whitespace after T_STATIC + // eg: `$a = static function(){};` => `$a = static function(){};` + $tokens->ensureWhitespaceAtIndex($prev + 1, 0, ' '); + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('closure_function_spacing', 'Spacing to use before open parenthesis for closures.')) + ->setDefault(self::SPACING_ONE) + ->setAllowedValues(self::SUPPORTED_SPACINGS) + ->getOption(), + (new FixerOptionBuilder('closure_fn_spacing', 'Spacing to use before open parenthesis for short arrow functions.')) + ->setDefault(self::SPACING_ONE) // @TODO change to SPACING_NONE on next major 4.0 + ->setAllowedValues(self::SUPPORTED_SPACINGS) + ->getOption(), + (new FixerOptionBuilder('trailing_comma_single_line', 'Whether trailing commas are allowed in single line signatures.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + private function fixParenthesisInnerEdge(Tokens $tokens, int $start, int $end): void + { + do { + --$end; + } while ($tokens->isEmptyAt($end)); + + // remove single-line whitespace before `)` + if ($tokens[$end]->isWhitespace($this->singleLineWhitespaceOptions)) { + $tokens->clearAt($end); + } + + // remove single-line whitespace after `(` + if ($tokens[$start + 1]->isWhitespace($this->singleLineWhitespaceOptions)) { + $tokens->clearAt($start + 1); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php new file mode 100644 index 00000000..132f7c13 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php @@ -0,0 +1,60 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\Whitespace\TypeDeclarationSpacesFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * + * @deprecated + */ +final class FunctionTypehintSpaceFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Ensure single space between function\'s argument and its typehint.', + [ + new CodeSample("isAnyTokenKindsFound([T_FUNCTION, T_FN]); + } + + public function getSuccessorsNames(): array + { + return array_keys($this->proxyFixers); + } + + protected function createProxyFixers(): array + { + $fixer = new TypeDeclarationSpacesFixer(); + $fixer->configure(['elements' => ['function']]); + + return [$fixer]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ImplodeCallFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ImplodeCallFixer.php new file mode 100644 index 00000000..49d728ef --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ImplodeCallFixer.php @@ -0,0 +1,139 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + */ +final class ImplodeCallFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Function `implode` must be called with 2 arguments in the documented order.', + [ + new CodeSample("isTokenKindFound(T_STRING); + } + + /** + * {@inheritdoc} + * + * Must run before MethodArgumentSpaceFixer. + * Must run after NoAliasFunctionsFixer. + */ + public function getPriority(): int + { + return 37; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + for ($index = \count($tokens) - 1; $index > 0; --$index) { + if (!$tokens[$index]->equals([T_STRING, 'implode'], false)) { + continue; + } + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + $argumentsIndices = $this->getArgumentIndices($tokens, $index); + + if (1 === \count($argumentsIndices)) { + $firstArgumentIndex = key($argumentsIndices); + $tokens->insertAt($firstArgumentIndex, [ + new Token([T_CONSTANT_ENCAPSED_STRING, "''"]), + new Token(','), + new Token([T_WHITESPACE, ' ']), + ]); + + continue; + } + + if (2 === \count($argumentsIndices)) { + [$firstArgumentIndex, $secondArgumentIndex] = array_keys($argumentsIndices); + + // If the first argument is string we have nothing to do + if ($tokens[$firstArgumentIndex]->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) { + continue; + } + // If the second argument is not string we cannot make a swap + if (!$tokens[$secondArgumentIndex]->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) { + continue; + } + + // collect tokens from first argument + $firstArgumentEndIndex = $argumentsIndices[key($argumentsIndices)]; + $newSecondArgumentTokens = []; + for ($i = key($argumentsIndices); $i <= $firstArgumentEndIndex; ++$i) { + $newSecondArgumentTokens[] = clone $tokens[$i]; + $tokens->clearAt($i); + } + + $tokens->insertAt($firstArgumentIndex, clone $tokens[$secondArgumentIndex]); + + // insert above increased the second argument index + ++$secondArgumentIndex; + $tokens->clearAt($secondArgumentIndex); + $tokens->insertAt($secondArgumentIndex, $newSecondArgumentTokens); + } + } + } + + /** + * @return array In the format: startIndex => endIndex + */ + private function getArgumentIndices(Tokens $tokens, int $functionNameIndex): array + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + $openParenthesis = $tokens->getNextTokenOfKind($functionNameIndex, ['(']); + $closeParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis); + + $indices = []; + + foreach ($argumentsAnalyzer->getArguments($tokens, $openParenthesis, $closeParenthesis) as $startIndexCandidate => $endIndex) { + $indices[$tokens->getNextMeaningfulToken($startIndexCandidate - 1)] = $tokens->getPrevMeaningfulToken($endIndex + 1); + } + + return $indices; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.php new file mode 100644 index 00000000..48155cec --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.php @@ -0,0 +1,346 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +final class LambdaNotUsedImportFixer extends AbstractFixer +{ + /** + * @var ArgumentsAnalyzer + */ + private $argumentsAnalyzer; + + /** + * @var FunctionsAnalyzer + */ + private $functionAnalyzer; + + /** + * @var TokensAnalyzer + */ + private $tokensAnalyzer; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Lambda must not import variables it doesn\'t use.', + [new CodeSample("isAllTokenKindsFound([T_FUNCTION, CT::T_USE_LAMBDA]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->argumentsAnalyzer = new ArgumentsAnalyzer(); + $this->functionAnalyzer = new FunctionsAnalyzer(); + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 4; $index > 0; --$index) { + $lambdaUseIndex = $this->getLambdaUseIndex($tokens, $index); + + if (false !== $lambdaUseIndex) { + $this->fixLambda($tokens, $lambdaUseIndex); + } + } + } + + private function fixLambda(Tokens $tokens, int $lambdaUseIndex): void + { + $lambdaUseOpenBraceIndex = $tokens->getNextTokenOfKind($lambdaUseIndex, ['(']); + $lambdaUseCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseOpenBraceIndex); + $arguments = $this->argumentsAnalyzer->getArguments($tokens, $lambdaUseOpenBraceIndex, $lambdaUseCloseBraceIndex); + + $imports = $this->filterArguments($tokens, $arguments); + + if (0 === \count($imports)) { + return; // no imports to remove + } + + $notUsedImports = $this->findNotUsedLambdaImports($tokens, $imports, $lambdaUseCloseBraceIndex); + $notUsedImportsCount = \count($notUsedImports); + + if (0 === $notUsedImportsCount) { + return; // no not used imports found + } + + if ($notUsedImportsCount === \count($arguments)) { + $this->clearImportsAndUse($tokens, $lambdaUseIndex, $lambdaUseCloseBraceIndex); // all imports are not used + + return; + } + + $this->clearImports($tokens, array_reverse($notUsedImports)); + } + + /** + * @return array + */ + private function findNotUsedLambdaImports(Tokens $tokens, array $imports, int $lambdaUseCloseBraceIndex): array + { + static $riskyKinds = [ + CT::T_DYNAMIC_VAR_BRACE_OPEN, + T_EVAL, + T_INCLUDE, + T_INCLUDE_ONCE, + T_REQUIRE, + T_REQUIRE_ONCE, + ]; + + // figure out where the lambda starts ... + $lambdaOpenIndex = $tokens->getNextTokenOfKind($lambdaUseCloseBraceIndex, ['{']); + $curlyBracesLevel = 0; + + for ($index = $lambdaOpenIndex;; ++$index) { // go through the body of the lambda and keep count of the (possible) usages of the imported variables + $token = $tokens[$index]; + + if ($token->equals('{')) { + ++$curlyBracesLevel; + + continue; + } + + if ($token->equals('}')) { + --$curlyBracesLevel; + + if (0 === $curlyBracesLevel) { + break; + } + + continue; + } + + if ($token->isGivenKind(T_STRING) && 'compact' === strtolower($token->getContent()) && $this->functionAnalyzer->isGlobalFunctionCall($tokens, $index)) { + return []; // wouldn't touch it with a ten-foot pole + } + + if ($token->isGivenKind($riskyKinds)) { + return []; + } + + if ($token->equals('$')) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$nextIndex]->isGivenKind(T_VARIABLE)) { + return []; // "$$a" case + } + } + + if ($token->isGivenKind(T_VARIABLE)) { + $content = $token->getContent(); + + if (isset($imports[$content])) { + unset($imports[$content]); + + if (0 === \count($imports)) { + return $imports; + } + } + } + + if ($token->isGivenKind(T_STRING_VARNAME)) { + $content = '$'.$token->getContent(); + + if (isset($imports[$content])) { + unset($imports[$content]); + + if (0 === \count($imports)) { + return $imports; + } + } + } + + if ($token->isClassy()) { // is anonymous class + // check if used as argument in the constructor of the anonymous class + $index = $tokens->getNextTokenOfKind($index, ['(', '{']); + + if ($tokens[$index]->equals('(')) { + $closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $arguments = $this->argumentsAnalyzer->getArguments($tokens, $index, $closeBraceIndex); + + $imports = $this->countImportsUsedAsArgument($tokens, $imports, $arguments); + + $index = $tokens->getNextTokenOfKind($closeBraceIndex, ['{']); + } + + // skip body + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + + continue; + } + + if ($token->isGivenKind(T_FUNCTION)) { + // check if used as argument + $lambdaUseOpenBraceIndex = $tokens->getNextTokenOfKind($index, ['(']); + $lambdaUseCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseOpenBraceIndex); + $arguments = $this->argumentsAnalyzer->getArguments($tokens, $lambdaUseOpenBraceIndex, $lambdaUseCloseBraceIndex); + + $imports = $this->countImportsUsedAsArgument($tokens, $imports, $arguments); + + // check if used as import + $index = $tokens->getNextTokenOfKind($index, [[CT::T_USE_LAMBDA], '{']); + + if ($tokens[$index]->isGivenKind(CT::T_USE_LAMBDA)) { + $lambdaUseOpenBraceIndex = $tokens->getNextTokenOfKind($index, ['(']); + $lambdaUseCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseOpenBraceIndex); + $arguments = $this->argumentsAnalyzer->getArguments($tokens, $lambdaUseOpenBraceIndex, $lambdaUseCloseBraceIndex); + + $imports = $this->countImportsUsedAsArgument($tokens, $imports, $arguments); + + $index = $tokens->getNextTokenOfKind($lambdaUseCloseBraceIndex, ['{']); + } + + // skip body + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + + continue; + } + } + + return $imports; + } + + private function countImportsUsedAsArgument(Tokens $tokens, array $imports, array $arguments): array + { + foreach ($arguments as $start => $end) { + $info = $this->argumentsAnalyzer->getArgumentInfo($tokens, $start, $end); + $content = $info->getName(); + + if (isset($imports[$content])) { + unset($imports[$content]); + + if (0 === \count($imports)) { + return $imports; + } + } + } + + return $imports; + } + + /** + * @return false|int + */ + private function getLambdaUseIndex(Tokens $tokens, int $index) + { + if (!$tokens[$index]->isGivenKind(T_FUNCTION) || !$this->tokensAnalyzer->isLambda($index)) { + return false; + } + + $lambdaUseIndex = $tokens->getNextMeaningfulToken($index); // we are @ '(' or '&' after this + + if ($tokens[$lambdaUseIndex]->isGivenKind(CT::T_RETURN_REF)) { + $lambdaUseIndex = $tokens->getNextMeaningfulToken($lambdaUseIndex); + } + + $lambdaUseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseIndex); // we are @ ')' after this + $lambdaUseIndex = $tokens->getNextMeaningfulToken($lambdaUseIndex); + + if (!$tokens[$lambdaUseIndex]->isGivenKind(CT::T_USE_LAMBDA)) { + return false; + } + + return $lambdaUseIndex; + } + + private function filterArguments(Tokens $tokens, array $arguments): array + { + $imports = []; + + foreach ($arguments as $start => $end) { + $info = $this->argumentsAnalyzer->getArgumentInfo($tokens, $start, $end); + $argument = $info->getNameIndex(); + + if ($tokens[$tokens->getPrevMeaningfulToken($argument)]->equals('&')) { + continue; + } + + $argumentCandidate = $tokens[$argument]; + + if ('$this' === $argumentCandidate->getContent()) { + continue; + } + + if ($this->tokensAnalyzer->isSuperGlobal($argument)) { + continue; + } + + $imports[$argumentCandidate->getContent()] = $argument; + } + + return $imports; + } + + /** + * @param array $imports + */ + private function clearImports(Tokens $tokens, array $imports): void + { + foreach ($imports as $removeIndex) { + $tokens->clearTokenAndMergeSurroundingWhitespace($removeIndex); + $previousRemoveIndex = $tokens->getPrevMeaningfulToken($removeIndex); + + if ($tokens[$previousRemoveIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($previousRemoveIndex); + } elseif ($tokens[$previousRemoveIndex]->equals('(')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($tokens->getNextMeaningfulToken($removeIndex)); // next is always ',' here + } + } + } + + /** + * Remove `use` and all imported variables. + */ + private function clearImportsAndUse(Tokens $tokens, int $lambdaUseIndex, int $lambdaUseCloseBraceIndex): void + { + for ($i = $lambdaUseCloseBraceIndex; $i >= $lambdaUseIndex; --$i) { + if ($tokens[$i]->isComment()) { + continue; + } + + if ($tokens[$i]->isWhitespace()) { + $previousIndex = $tokens->getPrevNonWhitespace($i); + + if ($tokens[$previousIndex]->isComment()) { + continue; + } + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php new file mode 100644 index 00000000..5f47784e --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php @@ -0,0 +1,488 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuanhung Chen + */ +final class MethodArgumentSpaceFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'In method arguments and method call, there MUST NOT be a space before each comma and there MUST be one space after each comma. Argument lists MAY be split across multiple lines, where each subsequent line is indented once. When doing so, the first item in the list MUST be on the next line, and there MUST be only one argument per line.', + [ + new CodeSample( + " false] + ), + new CodeSample( + " true] + ), + new CodeSample( + " 'ensure_fully_multiline'] + ), + new CodeSample( + " 'ensure_single_line'] + ), + new CodeSample( + " 'ensure_fully_multiline', + 'keep_multiple_spaces_after_comma' => true, + ] + ), + new CodeSample( + " 'ensure_fully_multiline', + 'keep_multiple_spaces_after_comma' => false, + ] + ), + new CodeSample( + " 'ensure_fully_multiline', + 'attribute_placement' => 'ignore', + ] + ), + new CodeSample( + " 'ensure_fully_multiline', + 'attribute_placement' => 'same_line', + ] + ), + new CodeSample( + " 'ensure_fully_multiline', + 'attribute_placement' => 'standalone', + ] + ), + new CodeSample( + <<<'SAMPLE' + true] + ), + ], + 'This fixer covers rules defined in PSR2 ¶4.4, ¶4.6.' + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound('('); + } + + /** + * {@inheritdoc} + * + * Must run before ArrayIndentationFixer, StatementIndentationFixer. + * Must run after CombineNestedDirnameFixer, FunctionDeclarationFixer, ImplodeCallFixer, LambdaNotUsedImportFixer, NoMultilineWhitespaceAroundDoubleArrowFixer, NoUselessSprintfFixer, PowToExponentiationFixer, StrictParamFixer. + */ + public function getPriority(): int + { + return 30; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $expectedTokens = [T_LIST, T_FUNCTION, CT::T_USE_LAMBDA, T_FN, T_CLASS]; + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + $token = $tokens[$index]; + + if (!$token->equals('(')) { + continue; + } + + $meaningfulTokenBeforeParenthesis = $tokens[$tokens->getPrevMeaningfulToken($index)]; + + if ( + $meaningfulTokenBeforeParenthesis->isKeyword() + && !$meaningfulTokenBeforeParenthesis->isGivenKind($expectedTokens) + ) { + continue; + } + + $isMultiline = $this->fixFunction($tokens, $index); + + if ( + $isMultiline + && 'ensure_fully_multiline' === $this->configuration['on_multiline'] + && !$meaningfulTokenBeforeParenthesis->isGivenKind(T_LIST) + ) { + $this->ensureFunctionFullyMultiline($tokens, $index); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('keep_multiple_spaces_after_comma', 'Whether keep multiple spaces after comma.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder( + 'on_multiline', + 'Defines how to handle function arguments lists that contain newlines.' + )) + ->setAllowedValues(['ignore', 'ensure_single_line', 'ensure_fully_multiline']) + ->setDefault('ensure_fully_multiline') + ->getOption(), + (new FixerOptionBuilder('after_heredoc', 'Whether the whitespace between heredoc end and comma should be removed.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder( + 'attribute_placement', + 'Defines how to handle argument attributes when function definition is multiline.' + )) + ->setAllowedValues(['ignore', 'same_line', 'standalone']) + ->setDefault('standalone') + ->getOption(), + ]); + } + + /** + * Fix arguments spacing for given function. + * + * @param Tokens $tokens Tokens to handle + * @param int $startFunctionIndex Start parenthesis position + * + * @return bool whether the function is multiline + */ + private function fixFunction(Tokens $tokens, int $startFunctionIndex): bool + { + $isMultiline = false; + + $endFunctionIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startFunctionIndex); + $firstWhitespaceIndex = $this->findWhitespaceIndexAfterParenthesis($tokens, $startFunctionIndex, $endFunctionIndex); + $lastWhitespaceIndex = $this->findWhitespaceIndexAfterParenthesis($tokens, $endFunctionIndex, $startFunctionIndex); + + foreach ([$firstWhitespaceIndex, $lastWhitespaceIndex] as $index) { + if (null === $index || !Preg::match('/\R/', $tokens[$index]->getContent())) { + continue; + } + + if ('ensure_single_line' !== $this->configuration['on_multiline']) { + $isMultiline = true; + + continue; + } + + $newLinesRemoved = $this->ensureSingleLine($tokens, $index); + + if (!$newLinesRemoved) { + $isMultiline = true; + } + } + + for ($index = $endFunctionIndex - 1; $index > $startFunctionIndex; --$index) { + $token = $tokens[$index]; + + if ($token->equals(')')) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + + continue; + } + + if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_CLOSE)) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); + + continue; + } + + if ($token->equals('}')) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + + continue; + } + + if ($token->equals(',')) { + $this->fixSpace($tokens, $index); + if (!$isMultiline && $this->isNewline($tokens[$index + 1])) { + $isMultiline = true; + } + } + } + + return $isMultiline; + } + + private function findWhitespaceIndexAfterParenthesis(Tokens $tokens, int $startParenthesisIndex, int $endParenthesisIndex): ?int + { + $direction = $endParenthesisIndex > $startParenthesisIndex ? 1 : -1; + $startIndex = $startParenthesisIndex + $direction; + $endIndex = $endParenthesisIndex - $direction; + + for ($index = $startIndex; $index !== $endIndex; $index += $direction) { + $token = $tokens[$index]; + + if ($token->isWhitespace()) { + return $index; + } + + if (!$token->isComment()) { + break; + } + } + + return null; + } + + /** + * @return bool Whether newlines were removed from the whitespace token + */ + private function ensureSingleLine(Tokens $tokens, int $index): bool + { + $previousToken = $tokens[$index - 1]; + + if ($previousToken->isComment() && !str_starts_with($previousToken->getContent(), '/*')) { + return false; + } + + $content = Preg::replace('/\R\h*/', '', $tokens[$index]->getContent()); + + $tokens->ensureWhitespaceAtIndex($index, 0, $content); + + return true; + } + + private function ensureFunctionFullyMultiline(Tokens $tokens, int $startFunctionIndex): void + { + // find out what the indentation is + $searchIndex = $startFunctionIndex; + do { + $prevWhitespaceTokenIndex = $tokens->getPrevTokenOfKind( + $searchIndex, + [[T_WHITESPACE]] + ); + + $searchIndex = $prevWhitespaceTokenIndex; + } while (null !== $prevWhitespaceTokenIndex + && !str_contains($tokens[$prevWhitespaceTokenIndex]->getContent(), "\n") + ); + + if (null === $prevWhitespaceTokenIndex) { + $existingIndentation = ''; + } else { + $existingIndentation = $tokens[$prevWhitespaceTokenIndex]->getContent(); + $lastLineIndex = strrpos($existingIndentation, "\n"); + $existingIndentation = false === $lastLineIndex + ? $existingIndentation + : substr($existingIndentation, $lastLineIndex + 1); + } + + $indentation = $existingIndentation.$this->whitespacesConfig->getIndent(); + $endFunctionIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startFunctionIndex); + + $wasWhitespaceBeforeEndFunctionAddedAsNewToken = $tokens->ensureWhitespaceAtIndex( + $tokens[$endFunctionIndex - 1]->isWhitespace() ? $endFunctionIndex - 1 : $endFunctionIndex, + 0, + $this->whitespacesConfig->getLineEnding().$existingIndentation + ); + + if ($wasWhitespaceBeforeEndFunctionAddedAsNewToken) { + ++$endFunctionIndex; + } + + for ($index = $endFunctionIndex - 1; $index > $startFunctionIndex; --$index) { + $token = $tokens[$index]; + + // skip nested method calls and arrays + if ($token->equals(')')) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + + continue; + } + + // skip nested arrays + if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_CLOSE)) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); + + continue; + } + + if ($token->equals('}')) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + + continue; + } + + if ($tokens[$tokens->getNextMeaningfulToken($index)]->equals(')')) { + continue; + } + + if ($token->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + if ('standalone' === $this->configuration['attribute_placement']) { + $this->fixNewline($tokens, $index, $indentation); + } elseif ('same_line' === $this->configuration['attribute_placement']) { + $this->ensureSingleLine($tokens, $index + 1); + $tokens->ensureWhitespaceAtIndex($index + 1, 0, ' '); + } + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + + continue; + } + + if ($token->equals(',')) { + $this->fixNewline($tokens, $index, $indentation); + } + } + + $this->fixNewline($tokens, $startFunctionIndex, $indentation, false); + } + + /** + * Method to insert newline after comma, attribute or opening parenthesis. + * + * @param int $index index of a comma + * @param string $indentation the indentation that should be used + * @param bool $override whether to override the existing character or not + */ + private function fixNewline(Tokens $tokens, int $index, string $indentation, bool $override = true): void + { + if ($tokens[$index + 1]->isComment()) { + return; + } + + if ($tokens[$index + 2]->isComment()) { + $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index + 2); + if (!$this->isNewline($tokens[$nextMeaningfulTokenIndex - 1])) { + if ($tokens[$nextMeaningfulTokenIndex - 1]->isWhitespace()) { + $tokens->clearAt($nextMeaningfulTokenIndex - 1); + } + + $tokens->ensureWhitespaceAtIndex($nextMeaningfulTokenIndex, 0, $this->whitespacesConfig->getLineEnding().$indentation); + } + + return; + } + + $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$nextMeaningfulTokenIndex]->equals(')')) { + return; + } + + $tokens->ensureWhitespaceAtIndex($index + 1, 0, $this->whitespacesConfig->getLineEnding().$indentation); + } + + /** + * Method to insert space after comma and remove space before comma. + */ + private function fixSpace(Tokens $tokens, int $index): void + { + // remove space before comma if exist + if ($tokens[$index - 1]->isWhitespace()) { + $prevIndex = $tokens->getPrevNonWhitespace($index - 1); + + if ( + !$tokens[$prevIndex]->equals(',') && !$tokens[$prevIndex]->isComment() + && (true === $this->configuration['after_heredoc'] || !$tokens[$prevIndex]->isGivenKind(T_END_HEREDOC)) + ) { + $tokens->clearAt($index - 1); + } + } + + $nextIndex = $index + 1; + $nextToken = $tokens[$nextIndex]; + + // Two cases for fix space after comma (exclude multiline comments) + // 1) multiple spaces after comma + // 2) no space after comma + if ($nextToken->isWhitespace()) { + $newContent = $nextToken->getContent(); + + if ('ensure_single_line' === $this->configuration['on_multiline']) { + $newContent = Preg::replace('/\R/', '', $newContent); + } + + if ( + (false === $this->configuration['keep_multiple_spaces_after_comma'] || Preg::match('/\R/', $newContent)) + && !$this->isCommentLastLineToken($tokens, $index + 2) + ) { + $newContent = ltrim($newContent, " \t"); + } + + $tokens[$nextIndex] = new Token([T_WHITESPACE, '' === $newContent ? ' ' : $newContent]); + + return; + } + + if (!$this->isCommentLastLineToken($tokens, $index + 1)) { + $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); + } + } + + /** + * Check if last item of current line is a comment. + * + * @param Tokens $tokens tokens to handle + * @param int $index index of token + */ + private function isCommentLastLineToken(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->isComment() || !$tokens[$index + 1]->isWhitespace()) { + return false; + } + + $content = $tokens[$index + 1]->getContent(); + + return $content !== ltrim($content, "\r\n"); + } + + /** + * Checks if token is new line. + */ + private function isNewline(Token $token): bool + { + return $token->isWhitespace() && str_contains($token->getContent(), "\n"); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php new file mode 100644 index 00000000..06f9b660 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php @@ -0,0 +1,401 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @author Andreas Möller + */ +final class NativeFunctionInvocationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const SET_ALL = '@all'; + + /** + * Subset of SET_INTERNAL. + * + * Change function call to functions known to be optimized by the Zend engine. + * For details: + * - @see https://github.com/php/php-src/blob/php-7.2.6/Zend/zend_compile.c "zend_try_compile_special_func" + * - @see https://github.com/php/php-src/blob/php-7.2.6/ext/opcache/Optimizer/pass1_5.c + * + * @internal + */ + public const SET_COMPILER_OPTIMIZED = '@compiler_optimized'; + + /** + * @internal + */ + public const SET_INTERNAL = '@internal'; + + /** + * @var callable + */ + private $functionFilter; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->functionFilter = $this->getFunctionFilter(); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Add leading `\` before function invocation to speed up resolving.', + [ + new CodeSample( + ' [ + 'json_encode', + ], + ] + ), + new CodeSample( + ' 'all'] + ), + new CodeSample( + ' 'namespaced'] + ), + new CodeSample( + ' ['myGlobalFunction']] + ), + new CodeSample( + ' ['@all']] + ), + new CodeSample( + ' ['@internal']] + ), + new CodeSample( + ' ['@compiler_optimized']] + ), + ], + null, + 'Risky when any of the functions are overridden.' + ); + } + + /** + * {@inheritdoc} + * + * Must run before GlobalNamespaceImportFixer. + * Must run after BacktickToShellExecFixer, RegularCallableCallFixer, StrictParamFixer. + */ + public function getPriority(): int + { + return 1; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if ('all' === $this->configuration['scope']) { + $this->fixFunctionCalls($tokens, $this->functionFilter, 0, \count($tokens) - 1, false); + + return; + } + + $namespaces = $tokens->getNamespaceDeclarations(); + + // 'scope' is 'namespaced' here + /** @var NamespaceAnalysis $namespace */ + foreach (array_reverse($namespaces) as $namespace) { + $this->fixFunctionCalls($tokens, $this->functionFilter, $namespace->getScopeStartIndex(), $namespace->getScopeEndIndex(), $namespace->isGlobalNamespace()); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('exclude', 'List of functions to ignore.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([static function (array $value): bool { + foreach ($value as $functionName) { + if (!\is_string($functionName) || '' === trim($functionName) || trim($functionName) !== $functionName) { + throw new InvalidOptionsException(sprintf( + 'Each element must be a non-empty, trimmed string, got "%s" instead.', + get_debug_type($functionName) + )); + } + } + + return true; + }]) + ->setDefault([]) + ->getOption(), + (new FixerOptionBuilder('include', 'List of function names or sets to fix. Defined sets are `@internal` (all native functions), `@all` (all global functions) and `@compiler_optimized` (functions that are specially optimized by Zend).')) + ->setAllowedTypes(['array']) + ->setAllowedValues([static function (array $value): bool { + foreach ($value as $functionName) { + if (!\is_string($functionName) || '' === trim($functionName) || trim($functionName) !== $functionName) { + throw new InvalidOptionsException(sprintf( + 'Each element must be a non-empty, trimmed string, got "%s" instead.', + get_debug_type($functionName) + )); + } + + $sets = [ + self::SET_ALL, + self::SET_INTERNAL, + self::SET_COMPILER_OPTIMIZED, + ]; + + if (str_starts_with($functionName, '@') && !\in_array($functionName, $sets, true)) { + throw new InvalidOptionsException(sprintf('Unknown set "%s", known sets are %s.', $functionName, Utils::naturalLanguageJoin($sets))); + } + } + + return true; + }]) + ->setDefault([self::SET_COMPILER_OPTIMIZED]) + ->getOption(), + (new FixerOptionBuilder('scope', 'Only fix function calls that are made within a namespace or fix all.')) + ->setAllowedValues(['all', 'namespaced']) + ->setDefault('all') + ->getOption(), + (new FixerOptionBuilder('strict', 'Whether leading `\` of function call not meant to have it should be removed.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + private function fixFunctionCalls(Tokens $tokens, callable $functionFilter, int $start, int $end, bool $tryToRemove): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + $tokensToInsert = []; + for ($index = $start; $index < $end; ++$index) { + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$functionFilter($tokens[$index]->getContent()) || $tryToRemove) { + if (false === $this->configuration['strict']) { + continue; + } + + if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + } + + continue; + } + + if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { + continue; // do not bother if previous token is already namespace separator + } + + $tokensToInsert[$index] = new Token([T_NS_SEPARATOR, '\\']); + } + + $tokens->insertSlices($tokensToInsert); + } + + private function getFunctionFilter(): callable + { + $exclude = $this->normalizeFunctionNames($this->configuration['exclude']); + + if (\in_array(self::SET_ALL, $this->configuration['include'], true)) { + if (\count($exclude) > 0) { + return static fn (string $functionName): bool => !isset($exclude[strtolower($functionName)]); + } + + return static fn (): bool => true; + } + + $include = []; + + if (\in_array(self::SET_INTERNAL, $this->configuration['include'], true)) { + $include = $this->getAllInternalFunctionsNormalized(); + } elseif (\in_array(self::SET_COMPILER_OPTIMIZED, $this->configuration['include'], true)) { + $include = $this->getAllCompilerOptimizedFunctionsNormalized(); // if `@internal` is set all compiler optimized function are already loaded + } + + foreach ($this->configuration['include'] as $additional) { + if (!str_starts_with($additional, '@')) { + $include[strtolower($additional)] = true; + } + } + + if (\count($exclude) > 0) { + return static fn (string $functionName): bool => isset($include[strtolower($functionName)]) && !isset($exclude[strtolower($functionName)]); + } + + return static fn (string $functionName): bool => isset($include[strtolower($functionName)]); + } + + /** + * @return array normalized function names of which the PHP compiler optimizes + */ + private function getAllCompilerOptimizedFunctionsNormalized(): array + { + return $this->normalizeFunctionNames([ + // @see https://github.com/php/php-src/blob/PHP-7.4/Zend/zend_compile.c "zend_try_compile_special_func" + 'array_key_exists', + 'array_slice', + 'assert', + 'boolval', + 'call_user_func', + 'call_user_func_array', + 'chr', + 'count', + 'defined', + 'doubleval', + 'floatval', + 'func_get_args', + 'func_num_args', + 'get_called_class', + 'get_class', + 'gettype', + 'in_array', + 'intval', + 'is_array', + 'is_bool', + 'is_double', + 'is_float', + 'is_int', + 'is_integer', + 'is_long', + 'is_null', + 'is_object', + 'is_real', + 'is_resource', + 'is_scalar', + 'is_string', + 'ord', + 'sizeof', + 'strlen', + 'strval', + // @see https://github.com/php/php-src/blob/php-7.2.6/ext/opcache/Optimizer/pass1_5.c + // @see https://github.com/php/php-src/blob/PHP-8.1.2/Zend/Optimizer/block_pass.c + // @see https://github.com/php/php-src/blob/php-8.1.3/Zend/Optimizer/zend_optimizer.c + 'constant', + 'define', + 'dirname', + 'extension_loaded', + 'function_exists', + 'is_callable', + 'ini_get', + ]); + } + + /** + * @return array normalized function names of all internal defined functions + */ + private function getAllInternalFunctionsNormalized(): array + { + return $this->normalizeFunctionNames(get_defined_functions()['internal']); + } + + /** + * @param string[] $functionNames + * + * @return array all function names lower cased + */ + private function normalizeFunctionNames(array $functionNames): array + { + foreach ($functionNames as $index => $functionName) { + $functionNames[strtolower($functionName)] = true; + unset($functionNames[$index]); + } + + return $functionNames; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php new file mode 100644 index 00000000..5b0bcb15 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php @@ -0,0 +1,178 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶4.6. + * + * @author Varga Bence + * @author Dariusz Rumiński + */ +final class NoSpacesAfterFunctionNameFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'When making a method or function call, there MUST NOT be a space between the method or function name and the opening parenthesis.', + [new CodeSample("isAnyTokenKindsFound([T_STRING, ...$this->getFunctionyTokenKinds()]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionyTokens = $this->getFunctionyTokenKinds(); + $languageConstructionTokens = $this->getLanguageConstructionTokenKinds(); + $braceTypes = $this->getBraceAfterVariableKinds(); + + foreach ($tokens as $index => $token) { + // looking for start brace + if (!$token->equals('(')) { + continue; + } + + // last non-whitespace token, can never be `null` always at least PHP open tag before it + $lastTokenIndex = $tokens->getPrevNonWhitespace($index); + + // check for ternary operator + $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $nextNonWhiteSpace = $tokens->getNextMeaningfulToken($endParenthesisIndex); + if ( + null !== $nextNonWhiteSpace + && !$tokens[$nextNonWhiteSpace]->equals(';') + && $tokens[$lastTokenIndex]->isGivenKind($languageConstructionTokens) + ) { + continue; + } + + // check if it is a function call + if ($tokens[$lastTokenIndex]->isGivenKind($functionyTokens)) { + $this->fixFunctionCall($tokens, $index); + } elseif ($tokens[$lastTokenIndex]->isGivenKind(T_STRING)) { // for real function calls or definitions + $possibleDefinitionIndex = $tokens->getPrevMeaningfulToken($lastTokenIndex); + if (!$tokens[$possibleDefinitionIndex]->isGivenKind(T_FUNCTION)) { + $this->fixFunctionCall($tokens, $index); + } + } elseif ($tokens[$lastTokenIndex]->equalsAny($braceTypes)) { + $block = Tokens::detectBlockType($tokens[$lastTokenIndex]); + if ( + Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE === $block['type'] + || Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE === $block['type'] + || Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE === $block['type'] + || Tokens::BLOCK_TYPE_PARENTHESIS_BRACE === $block['type'] + ) { + $this->fixFunctionCall($tokens, $index); + } + } + } + } + + /** + * Fixes whitespaces around braces of a function(y) call. + * + * @param Tokens $tokens tokens to handle + * @param int $index index of token + */ + private function fixFunctionCall(Tokens $tokens, int $index): void + { + // remove space before opening brace + if ($tokens[$index - 1]->isWhitespace()) { + $tokens->clearAt($index - 1); + } + } + + /** + * @return array|string> + */ + private function getBraceAfterVariableKinds(): array + { + static $tokens = [ + ')', + ']', + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], + ]; + + return $tokens; + } + + /** + * Gets the token kinds which can work as function calls. + * + * @return int[] Token names + */ + private function getFunctionyTokenKinds(): array + { + static $tokens = [ + T_ARRAY, + T_ECHO, + T_EMPTY, + T_EVAL, + T_EXIT, + T_INCLUDE, + T_INCLUDE_ONCE, + T_ISSET, + T_LIST, + T_PRINT, + T_REQUIRE, + T_REQUIRE_ONCE, + T_UNSET, + T_VARIABLE, + ]; + + return $tokens; + } + + /** + * Gets the token kinds of actually language construction. + * + * @return int[] + */ + private function getLanguageConstructionTokenKinds(): array + { + static $languageConstructionTokens = [ + T_ECHO, + T_PRINT, + T_INCLUDE, + T_INCLUDE_ONCE, + T_REQUIRE, + T_REQUIRE_ONCE, + ]; + + return $languageConstructionTokens; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoTrailingCommaInSinglelineFunctionCallFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoTrailingCommaInSinglelineFunctionCallFixer.php new file mode 100644 index 00000000..b0be871d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoTrailingCommaInSinglelineFunctionCallFixer.php @@ -0,0 +1,59 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\Basic\NoTrailingCommaInSinglelineFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @deprecated + */ +final class NoTrailingCommaInSinglelineFunctionCallFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'When making a method or function call on a single line there MUST NOT be a trailing comma after the last argument.', + [new CodeSample("proxyFixers); + } + + protected function createProxyFixers(): array + { + $fixer = new NoTrailingCommaInSinglelineFixer(); + $fixer->configure(['elements' => ['arguments', 'array_destructuring']]); + + return [$fixer]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php new file mode 100644 index 00000000..108901da --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php @@ -0,0 +1,191 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Mark Scherer + * @author Lucas Manzke + * @author Gregor Harlan + */ +final class NoUnreachableDefaultArgumentValueFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'In function arguments there must not be arguments with default values before non-default ones.', + [ + new CodeSample( + 'isAnyTokenKindsFound([T_FUNCTION, T_FN]); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionKinds = [T_FUNCTION, T_FN]; + + for ($i = 0, $l = $tokens->count(); $i < $l; ++$i) { + if (!$tokens[$i]->isGivenKind($functionKinds)) { + continue; + } + + $startIndex = $tokens->getNextTokenOfKind($i, ['(']); + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); + + $this->fixFunctionDefinition($tokens, $startIndex, $i); + } + } + + private function fixFunctionDefinition(Tokens $tokens, int $startIndex, int $endIndex): void + { + $lastArgumentIndex = $this->getLastNonDefaultArgumentIndex($tokens, $startIndex, $endIndex); + + if (null === $lastArgumentIndex) { + return; + } + + for ($i = $lastArgumentIndex; $i > $startIndex; --$i) { + $token = $tokens[$i]; + + if ($token->isGivenKind(T_VARIABLE)) { + $lastArgumentIndex = $i; + + continue; + } + + if (!$token->equals('=') || $this->isNonNullableTypehintedNullableVariable($tokens, $i)) { + continue; + } + + $this->removeDefaultValue($tokens, $i, $this->getDefaultValueEndIndex($tokens, $lastArgumentIndex)); + } + } + + private function getLastNonDefaultArgumentIndex(Tokens $tokens, int $startIndex, int $endIndex): ?int + { + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + $token = $tokens[$i]; + + if ($token->equals('=')) { + $i = $tokens->getPrevMeaningfulToken($i); + + continue; + } + + if ($token->isGivenKind(T_VARIABLE) && !$this->isEllipsis($tokens, $i)) { + return $i; + } + } + + return null; + } + + private function isEllipsis(Tokens $tokens, int $variableIndex): bool + { + return $tokens[$tokens->getPrevMeaningfulToken($variableIndex)]->isGivenKind(T_ELLIPSIS); + } + + private function getDefaultValueEndIndex(Tokens $tokens, int $index): int + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + } + } while (!$tokens[$index]->equals(',')); + + return $tokens->getPrevMeaningfulToken($index); + } + + private function removeDefaultValue(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($i = $startIndex; $i <= $endIndex;) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + $this->clearWhitespacesBeforeIndex($tokens, $i); + $i = $tokens->getNextMeaningfulToken($i); + } + } + + /** + * @param int $index Index of "=" + */ + private function isNonNullableTypehintedNullableVariable(Tokens $tokens, int $index): bool + { + $nextToken = $tokens[$tokens->getNextMeaningfulToken($index)]; + + if (!$nextToken->equals([T_STRING, 'null'], false)) { + return false; + } + + $variableIndex = $tokens->getPrevMeaningfulToken($index); + + $searchTokens = [',', '(', [T_STRING], [CT::T_ARRAY_TYPEHINT], [T_CALLABLE]]; + $typehintKinds = [T_STRING, CT::T_ARRAY_TYPEHINT, T_CALLABLE]; + + $prevIndex = $tokens->getPrevTokenOfKind($variableIndex, $searchTokens); + + if (!$tokens[$prevIndex]->isGivenKind($typehintKinds)) { + return false; + } + + return !$tokens[$tokens->getPrevMeaningfulToken($prevIndex)]->isGivenKind(CT::T_NULLABLE_TYPE); + } + + private function clearWhitespacesBeforeIndex(Tokens $tokens, int $index): void + { + $prevIndex = $tokens->getNonEmptySibling($index, -1); + if (!$tokens[$prevIndex]->isWhitespace()) { + return; + } + + $prevNonWhiteIndex = $tokens->getPrevNonWhitespace($prevIndex); + if (null === $prevNonWhiteIndex || !$tokens[$prevNonWhiteIndex]->isComment()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUselessSprintfFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUselessSprintfFixer.php new file mode 100644 index 00000000..125bbab6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUselessSprintfFixer.php @@ -0,0 +1,109 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; + +final class NoUselessSprintfFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There must be no `sprintf` calls with only the first argument.', + [ + new CodeSample( + "isTokenKindFound(T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run before MethodArgumentSpaceFixer, NativeFunctionCasingFixer, NoEmptyStatementFixer, NoExtraBlankLinesFixer, NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer. + */ + public function getPriority(): int + { + return 42; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionAnalyzer = new FunctionsAnalyzer(); + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + for ($index = \count($tokens) - 1; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(T_STRING)) { + continue; + } + + if ('sprintf' !== strtolower($tokens[$index]->getContent())) { + continue; + } + + if (!$functionAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + $openParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(']); + + if ($tokens[$tokens->getNextMeaningfulToken($openParenthesisIndex)]->isGivenKind(T_ELLIPSIS)) { + continue; + } + + $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesisIndex); + + if (1 !== $argumentsAnalyzer->countArguments($tokens, $openParenthesisIndex, $closeParenthesisIndex)) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesisIndex); + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex); + + if ($tokens[$prevMeaningfulTokenIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevMeaningfulTokenIndex); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesisIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prevMeaningfulTokenIndex]->isGivenKind(T_NS_SEPARATOR)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevMeaningfulTokenIndex); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php new file mode 100644 index 00000000..a8cec92c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php @@ -0,0 +1,233 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author HypeMC + */ +final class NullableTypeDeclarationForDefaultNullValueFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Adds or removes `?` before single type declarations or `|null` at the end of union types when parameters have a default `null` value.', + [ + new CodeSample( + " false] + ), + new VersionSpecificCodeSample( + " false] + ), + new VersionSpecificCodeSample( + " false] + ), + ], + 'Rule is applied only in a PHP 7.1+ environment.' + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_VARIABLE) && $tokens->isAnyTokenKindsFound([T_FUNCTION, T_FN]); + } + + /** + * {@inheritdoc} + * + * Must run before NoUnreachableDefaultArgumentValueFixer, NullableTypeDeclarationFixer, OrderedTypesFixer. + */ + public function getPriority(): int + { + return 3; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('use_nullable_type_declaration', 'Whether to add or remove `?` or `|null` to parameters with a default `null` value.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $tokenKinds = [T_FUNCTION, T_FN]; + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind($tokenKinds)) { + continue; + } + + $arguments = $functionsAnalyzer->getFunctionArguments($tokens, $index); + $this->fixFunctionParameters($tokens, $arguments); + } + } + + /** + * @param ArgumentAnalysis[] $arguments + */ + private function fixFunctionParameters(Tokens $tokens, array $arguments): void + { + $constructorPropertyModifiers = [ + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, + ]; + + if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required + $constructorPropertyModifiers[] = T_READONLY; + } + + foreach (array_reverse($arguments) as $argumentInfo) { + if ( + // Skip, if the parameter + // - doesn't have a type declaration + !$argumentInfo->hasTypeAnalysis() + // - has a mixed or standalone null type + || \in_array(strtolower($argumentInfo->getTypeAnalysis()->getName()), ['mixed', 'null'], true) + // - a default value is not null we can continue + || !$argumentInfo->hasDefault() || 'null' !== strtolower($argumentInfo->getDefault()) + ) { + continue; + } + + $argumentTypeInfo = $argumentInfo->getTypeAnalysis(); + + if (\PHP_VERSION_ID >= 8_00_00 && false === $this->configuration['use_nullable_type_declaration']) { + $visibility = $tokens[$tokens->getPrevMeaningfulToken($argumentTypeInfo->getStartIndex())]; + + if ($visibility->isGivenKind($constructorPropertyModifiers)) { + continue; + } + } + + $typeAnalysisName = $argumentTypeInfo->getName(); + if (str_contains($typeAnalysisName, '|') || str_contains($typeAnalysisName, '&')) { + $this->fixUnionTypeParameter($tokens, $argumentTypeInfo); + } else { + $this->fixSingleTypeParameter($tokens, $argumentTypeInfo); + } + } + } + + private function fixSingleTypeParameter(Tokens $tokens, TypeAnalysis $argumentTypeInfo): void + { + if (true === $this->configuration['use_nullable_type_declaration']) { + if (!$argumentTypeInfo->isNullable()) { + $tokens->insertAt($argumentTypeInfo->getStartIndex(), new Token([CT::T_NULLABLE_TYPE, '?'])); + } + } elseif ($argumentTypeInfo->isNullable()) { + $tokens->removeTrailingWhitespace($startIndex = $argumentTypeInfo->getStartIndex()); + $tokens->clearTokenAndMergeSurroundingWhitespace($startIndex); + } + } + + private function fixUnionTypeParameter(Tokens $tokens, TypeAnalysis $argumentTypeInfo): void + { + if (true === $this->configuration['use_nullable_type_declaration']) { + if ($argumentTypeInfo->isNullable()) { + return; + } + + $typeAnalysisName = $argumentTypeInfo->getName(); + $endIndex = $argumentTypeInfo->getEndIndex(); + + if (str_contains($typeAnalysisName, '&') && !str_contains($typeAnalysisName, '|')) { + $endIndex += 2; + $tokens->insertAt($argumentTypeInfo->getStartIndex(), new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '('])); + $tokens->insertAt($endIndex, new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')'])); + } + + $tokens->insertAt($endIndex + 1, [ + new Token([CT::T_TYPE_ALTERNATION, '|']), + new Token([T_STRING, 'null']), + ]); + } elseif ($argumentTypeInfo->isNullable()) { + $startIndex = $argumentTypeInfo->getStartIndex(); + + $index = $tokens->getNextTokenOfKind($startIndex - 1, [[T_STRING, 'null']], false); + + if ($index === $startIndex) { + $tokens->removeTrailingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + $index = $tokens->getNextMeaningfulToken($index); + if ($tokens[$index]->equals([CT::T_TYPE_ALTERNATION, '|'])) { + $tokens->removeTrailingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } else { + $tokens->removeLeadingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + $index = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$index]->equals([CT::T_TYPE_ALTERNATION, '|'])) { + $tokens->removeLeadingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + + $typeAnalysisName = $argumentTypeInfo->getName(); + + if (str_contains($typeAnalysisName, '&') && 1 === substr_count($typeAnalysisName, '|')) { + $index = $tokens->getNextTokenOfKind($startIndex - 1, [[CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN]]); + $tokens->removeTrailingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + $index = $tokens->getPrevTokenOfKind($argumentTypeInfo->getEndIndex() + 1, [[CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE]]); + $tokens->removeLeadingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php new file mode 100644 index 00000000..2ab13430 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php @@ -0,0 +1,218 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Jan Gantzert + */ +final class PhpdocToParamTypeFixer extends AbstractPhpdocToTypeDeclarationFixer +{ + private const TYPE_CHECK_TEMPLATE = ' + */ + private const SKIPPED_TYPES = [ + 'resource' => true, + 'static' => true, + 'void' => true, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'EXPERIMENTAL: Takes `@param` annotations of non-mixed types and adjusts accordingly the function signature. Requires PHP >= 7.0.', + [ + new CodeSample( + ' false] + ), + ], + null, + 'This rule is EXPERIMENTAL and [1] is not covered with backward compatibility promise. [2] `@param` annotation is mandatory for the fixer to make changes, signatures of methods without it (no docblock, inheritdocs) will not be fixed. [3] Manual actions are required if inherited signatures are not properly documented.' + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_FUNCTION); + } + + /** + * {@inheritdoc} + * + * Must run before NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 8; + } + + protected function isSkippedType(string $type): bool + { + return isset(self::SKIPPED_TYPES[$type]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; 0 < $index; --$index) { + if (!$tokens[$index]->isGivenKind(T_FUNCTION)) { + continue; + } + + $funcName = $tokens->getNextMeaningfulToken($index); + if ($tokens[$funcName]->equalsAny(self::EXCLUDE_FUNC_NAMES, false)) { + continue; + } + + $docCommentIndex = $this->findFunctionDocComment($tokens, $index); + + if (null === $docCommentIndex) { + continue; + } + + foreach ($this->getAnnotationsFromDocComment('param', $tokens, $docCommentIndex) as $paramTypeAnnotation) { + $typesExpression = $paramTypeAnnotation->getTypeExpression(); + + if (null === $typesExpression) { + continue; + } + + $typeInfo = $this->getCommonTypeInfo($typesExpression, false); + $unionTypes = null; + + if (null === $typeInfo) { + $unionTypes = $this->getUnionTypes($typesExpression, false); + } + + if (null === $typeInfo && null === $unionTypes) { + continue; + } + + if (null !== $typeInfo) { + [$paramType, $isNullable] = $typeInfo; + } elseif (null !== $unionTypes) { + $paramType = $unionTypes; + $isNullable = false; + } + + if (!isset($paramType, $isNullable)) { + continue; + } + + $startIndex = $tokens->getNextTokenOfKind($index, ['(']); + $variableIndex = $this->findCorrectVariable($tokens, $startIndex, $paramTypeAnnotation); + + if (null === $variableIndex) { + continue; + } + + $byRefIndex = $tokens->getPrevMeaningfulToken($variableIndex); + + if ($tokens[$byRefIndex]->equals('&')) { + $variableIndex = $byRefIndex; + } + + if ($this->hasParamTypeHint($tokens, $variableIndex)) { + continue; + } + + if (!$this->isValidSyntax(sprintf(self::TYPE_CHECK_TEMPLATE, $paramType))) { + continue; + } + + $tokens->insertAt($variableIndex, array_merge( + $this->createTypeDeclarationTokens($paramType, $isNullable), + [new Token([T_WHITESPACE, ' '])] + )); + } + } + } + + protected function createTokensFromRawType(string $type): Tokens + { + $typeTokens = Tokens::fromCode(sprintf(self::TYPE_CHECK_TEMPLATE, $type)); + $typeTokens->clearRange(0, 4); + $typeTokens->clearRange(\count($typeTokens) - 6, \count($typeTokens) - 1); + $typeTokens->clearEmptyTokens(); + + return $typeTokens; + } + + private function findCorrectVariable(Tokens $tokens, int $startIndex, Annotation $paramTypeAnnotation): ?int + { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); + + for ($index = $startIndex + 1; $index < $endIndex; ++$index) { + if (!$tokens[$index]->isGivenKind(T_VARIABLE)) { + continue; + } + + $variableName = $tokens[$index]->getContent(); + + if ($paramTypeAnnotation->getVariableName() === $variableName) { + return $index; + } + } + + return null; + } + + /** + * Determine whether the function already has a param type hint. + * + * @param int $index The index of the end of the function definition line, EG at { or ; + */ + private function hasParamTypeHint(Tokens $tokens, int $index): bool + { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + return !$tokens[$prevIndex]->equalsAny([',', '(']); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToPropertyTypeFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToPropertyTypeFixer.php new file mode 100644 index 00000000..7a1f287e --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToPropertyTypeFixer.php @@ -0,0 +1,264 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class PhpdocToPropertyTypeFixer extends AbstractPhpdocToTypeDeclarationFixer +{ + private const TYPE_CHECK_TEMPLATE = ' + */ + private array $skippedTypes = [ + 'resource' => true, + 'null' => true, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'EXPERIMENTAL: Takes `@var` annotation of non-mixed types and adjusts accordingly the property signature. Requires PHP >= 7.4.', + [ + new CodeSample( + ' false] + ), + ], + null, + 'This rule is EXPERIMENTAL and [1] is not covered with backward compatibility promise. [2] `@var` annotation is mandatory for the fixer to make changes, signatures of properties without it (no docblock) will not be fixed. [3] Manual actions might be required for newly typed properties that are read before initialization.' + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + /** + * {@inheritdoc} + * + * Must run before NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 7; + } + + protected function isSkippedType(string $type): bool + { + return isset($this->skippedTypes[$type]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; 0 < $index; --$index) { + if ($tokens[$index]->isGivenKind([T_CLASS, T_TRAIT])) { + $this->fixClass($tokens, $index); + } + } + } + + protected function createTokensFromRawType(string $type): Tokens + { + $typeTokens = Tokens::fromCode(sprintf(self::TYPE_CHECK_TEMPLATE, $type)); + $typeTokens->clearRange(0, 8); + $typeTokens->clearRange(\count($typeTokens) - 5, \count($typeTokens) - 1); + $typeTokens->clearEmptyTokens(); + + return $typeTokens; + } + + private function fixClass(Tokens $tokens, int $index): void + { + $index = $tokens->getNextTokenOfKind($index, ['{']); + $classEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + + for (; $index < $classEndIndex; ++$index) { + if ($tokens[$index]->isGivenKind(T_FUNCTION)) { + $index = $tokens->getNextTokenOfKind($index, ['{', ';']); + + if ($tokens[$index]->equals('{')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + } + + continue; + } + + if (!$tokens[$index]->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $docCommentIndex = $index; + $propertyIndices = $this->findNextUntypedPropertiesDeclaration($tokens, $docCommentIndex); + + if ([] === $propertyIndices) { + continue; + } + + $typeInfo = $this->resolveApplicableType( + $propertyIndices, + $this->getAnnotationsFromDocComment('var', $tokens, $docCommentIndex) + ); + + if (null === $typeInfo) { + continue; + } + + [$propertyType, $isNullable] = $typeInfo; + + if (\in_array($propertyType, ['callable', 'never', 'void'], true)) { + continue; + } + + if (!$this->isValidSyntax(sprintf(self::TYPE_CHECK_TEMPLATE, $propertyType))) { + continue; + } + + $newTokens = array_merge( + $this->createTypeDeclarationTokens($propertyType, $isNullable), + [new Token([T_WHITESPACE, ' '])] + ); + + $tokens->insertAt(current($propertyIndices), $newTokens); + + $index = max($propertyIndices) + \count($newTokens) + 1; + $classEndIndex += \count($newTokens); + } + } + + /** + * @return array + */ + private function findNextUntypedPropertiesDeclaration(Tokens $tokens, int $index): array + { + do { + $index = $tokens->getNextMeaningfulToken($index); + } while ($tokens[$index]->isGivenKind([ + T_PRIVATE, + T_PROTECTED, + T_PUBLIC, + T_STATIC, + T_VAR, + ])); + + if (!$tokens[$index]->isGivenKind(T_VARIABLE)) { + return []; + } + + $properties = []; + + while (!$tokens[$index]->equals(';')) { + if ($tokens[$index]->isGivenKind(T_VARIABLE)) { + $properties[$tokens[$index]->getContent()] = $index; + } + + $index = $tokens->getNextMeaningfulToken($index); + } + + return $properties; + } + + /** + * @param array $propertyIndices + * @param Annotation[] $annotations + */ + private function resolveApplicableType(array $propertyIndices, array $annotations): ?array + { + $propertyTypes = []; + + foreach ($annotations as $annotation) { + $propertyName = $annotation->getVariableName(); + + if (null === $propertyName) { + if (1 !== \count($propertyIndices)) { + continue; + } + + $propertyName = key($propertyIndices); + } + + if (!isset($propertyIndices[$propertyName])) { + continue; + } + + $typesExpression = $annotation->getTypeExpression(); + + if (null === $typesExpression) { + continue; + } + + $typeInfo = $this->getCommonTypeInfo($typesExpression, false); + $unionTypes = null; + + if (null === $typeInfo) { + $unionTypes = $this->getUnionTypes($typesExpression, false); + } + + if (null === $typeInfo && null === $unionTypes) { + continue; + } + + if (null !== $unionTypes) { + $typeInfo = [$unionTypes, false]; + } + + if (\array_key_exists($propertyName, $propertyTypes) && $typeInfo !== $propertyTypes[$propertyName]) { + return null; + } + + $propertyTypes[$propertyName] = $typeInfo; + } + + if (\count($propertyTypes) !== \count($propertyIndices)) { + return null; + } + + $type = array_shift($propertyTypes); + + foreach ($propertyTypes as $propertyType) { + if ($propertyType !== $type) { + return null; + } + } + + return $type; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php new file mode 100644 index 00000000..5ce5f9db --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php @@ -0,0 +1,224 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + */ +final class PhpdocToReturnTypeFixer extends AbstractPhpdocToTypeDeclarationFixer +{ + private const TYPE_CHECK_TEMPLATE = '> + */ + private array $excludeFuncNames = [ + [T_STRING, '__construct'], + [T_STRING, '__destruct'], + [T_STRING, '__clone'], + ]; + + /** + * @var array + */ + private array $skippedTypes = [ + 'resource' => true, + 'null' => true, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'EXPERIMENTAL: Takes `@return` annotation of non-mixed types and adjusts accordingly the function signature.', + [ + new CodeSample( + ' false] + ), + new VersionSpecificCodeSample( + 'isAnyTokenKindsFound([T_FUNCTION, T_FN]); + } + + /** + * {@inheritdoc} + * + * Must run before FullyQualifiedStrictTypesFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer, ReturnToYieldFromFixer, ReturnTypeDeclarationFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 13; + } + + protected function isSkippedType(string $type): bool + { + return isset($this->skippedTypes[$type]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; 0 < $index; --$index) { + if (!$tokens[$index]->isGivenKind([T_FUNCTION, T_FN])) { + continue; + } + + $funcName = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$funcName]->equalsAny($this->excludeFuncNames, false)) { + continue; + } + + $docCommentIndex = $this->findFunctionDocComment($tokens, $index); + if (null === $docCommentIndex) { + continue; + } + + $returnTypeAnnotations = $this->getAnnotationsFromDocComment('return', $tokens, $docCommentIndex); + if (1 !== \count($returnTypeAnnotations)) { + continue; + } + + /** @var Annotation $returnTypeAnnotation */ + $returnTypeAnnotation = current($returnTypeAnnotations); + + $typesExpression = $returnTypeAnnotation->getTypeExpression(); + + if (null === $typesExpression) { + continue; + } + + $typeInfo = $this->getCommonTypeInfo($typesExpression, true); + $unionTypes = null; + + if (null === $typeInfo) { + $unionTypes = $this->getUnionTypes($typesExpression, true); + } + + if (null === $typeInfo && null === $unionTypes) { + continue; + } + + if (null !== $typeInfo) { + [$returnType, $isNullable] = $typeInfo; + } elseif (null !== $unionTypes) { + $returnType = $unionTypes; + $isNullable = false; + } + + if (!isset($returnType, $isNullable)) { + continue; + } + + $startIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + + if ($this->hasReturnTypeHint($tokens, $startIndex)) { + continue; + } + + if (!$this->isValidSyntax(sprintf(self::TYPE_CHECK_TEMPLATE, $returnType))) { + continue; + } + + $endFuncIndex = $tokens->getPrevTokenOfKind($startIndex, [')']); + + $tokens->insertAt( + $endFuncIndex + 1, + array_merge( + [ + new Token([CT::T_TYPE_COLON, ':']), + new Token([T_WHITESPACE, ' ']), + ], + $this->createTypeDeclarationTokens($returnType, $isNullable) + ) + ); + } + } + + protected function createTokensFromRawType(string $type): Tokens + { + $typeTokens = Tokens::fromCode(sprintf(self::TYPE_CHECK_TEMPLATE, $type)); + $typeTokens->clearRange(0, 7); + $typeTokens->clearRange(\count($typeTokens) - 3, \count($typeTokens) - 1); + $typeTokens->clearEmptyTokens(); + + return $typeTokens; + } + + /** + * Determine whether the function already has a return type hint. + * + * @param int $index The index of the end of the function definition line, EG at { or ; + */ + private function hasReturnTypeHint(Tokens $tokens, int $index): bool + { + $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); + $nextIndex = $tokens->getNextMeaningfulToken($endFuncIndex); + + return $tokens[$nextIndex]->isGivenKind(CT::T_TYPE_COLON); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/RegularCallableCallFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/RegularCallableCallFixer.php new file mode 100644 index 00000000..2bb372c3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/RegularCallableCallFixer.php @@ -0,0 +1,256 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class RegularCallableCallFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Callables must be called without using `call_user_func*` when possible.', + [ + new CodeSample( + ' \'baz\'])` or `call_user_func($foo, $foo = \'bar\')`.' + ); + } + + /** + * {@inheritdoc} + * + * Must run before NativeFunctionInvocationFixer. + * Must run after NoBinaryStringFixer, NoUselessConcatOperatorFixer. + */ + public function getPriority(): int + { + return 2; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->equalsAny([[T_STRING, 'call_user_func'], [T_STRING, 'call_user_func_array']], false)) { + continue; + } + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; // redeclare/override + } + + $openParenthesis = $tokens->getNextMeaningfulToken($index); + $closeParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis); + $arguments = $argumentsAnalyzer->getArguments($tokens, $openParenthesis, $closeParenthesis); + + if (1 > \count($arguments)) { + return; // no arguments! + } + + $this->processCall($tokens, $index, $arguments); + } + } + + /** + * @param array $arguments + */ + private function processCall(Tokens $tokens, int $index, array $arguments): void + { + $firstArgIndex = $tokens->getNextMeaningfulToken( + $tokens->getNextMeaningfulToken($index) + ); + + /** @var Token $firstArgToken */ + $firstArgToken = $tokens[$firstArgIndex]; + + if ($firstArgToken->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) { + $afterFirstArgIndex = $tokens->getNextMeaningfulToken($firstArgIndex); + + if (!$tokens[$afterFirstArgIndex]->equalsAny([',', ')'])) { + return; // first argument is an expression like `call_user_func("foo"."bar", ...)`, not supported! + } + + $firstArgTokenContent = $firstArgToken->getContent(); + + if (!$this->isValidFunctionInvoke($firstArgTokenContent)) { + return; + } + + $newCallTokens = Tokens::fromCode('getContent()), 1, -1).'();'); + $newCallTokensSize = $newCallTokens->count(); + $newCallTokens->clearAt(0); + $newCallTokens->clearRange($newCallTokensSize - 3, $newCallTokensSize - 1); + $newCallTokens->clearEmptyTokens(); + + $this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgIndex); + } elseif ( + $firstArgToken->isGivenKind(T_FUNCTION) + || ( + $firstArgToken->isGivenKind(T_STATIC) + && $tokens[$tokens->getNextMeaningfulToken($firstArgIndex)]->isGivenKind(T_FUNCTION) + ) + ) { + $firstArgEndIndex = $tokens->findBlockEnd( + Tokens::BLOCK_TYPE_CURLY_BRACE, + $tokens->getNextTokenOfKind($firstArgIndex, ['{']) + ); + + $newCallTokens = $this->getTokensSubcollection($tokens, $firstArgIndex, $firstArgEndIndex); + $newCallTokens->insertAt($newCallTokens->count(), new Token(')')); + $newCallTokens->insertAt(0, new Token('(')); + $this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgEndIndex); + } elseif ($firstArgToken->isGivenKind(T_VARIABLE)) { + $firstArgEndIndex = reset($arguments); + + // check if the same variable is used multiple times and if so do not fix + + foreach ($arguments as $argumentStart => $argumentEnd) { + if ($firstArgEndIndex === $argumentEnd) { + continue; + } + + for ($i = $argumentStart; $i <= $argumentEnd; ++$i) { + if ($tokens[$i]->equals($firstArgToken)) { + return; + } + } + } + + // check if complex statement and if so wrap the call in () if on PHP 7 or up, else do not fix + + $newCallTokens = $this->getTokensSubcollection($tokens, $firstArgIndex, $firstArgEndIndex); + $complex = false; + + for ($newCallIndex = \count($newCallTokens) - 1; $newCallIndex >= 0; --$newCallIndex) { + if ($newCallTokens[$newCallIndex]->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT, T_VARIABLE])) { + continue; + } + + $blockType = Tokens::detectBlockType($newCallTokens[$newCallIndex]); + + if (null !== $blockType && (Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE === $blockType['type'] || Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE === $blockType['type'])) { + $newCallIndex = $newCallTokens->findBlockStart($blockType['type'], $newCallIndex); + + continue; + } + + $complex = true; + + break; + } + + if ($complex) { + $newCallTokens->insertAt($newCallTokens->count(), new Token(')')); + $newCallTokens->insertAt(0, new Token('(')); + } + $this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgEndIndex); + } + } + + private function replaceCallUserFuncWithCallback(Tokens $tokens, int $callIndex, Tokens $newCallTokens, int $firstArgStartIndex, int $firstArgEndIndex): void + { + $tokens->clearRange($firstArgStartIndex, $firstArgEndIndex); + + $afterFirstArgIndex = $tokens->getNextMeaningfulToken($firstArgEndIndex); + $afterFirstArgToken = $tokens[$afterFirstArgIndex]; + + if ($afterFirstArgToken->equals(',')) { + $useEllipsis = $tokens[$callIndex]->equals([T_STRING, 'call_user_func_array'], false); + + if ($useEllipsis) { + $secondArgIndex = $tokens->getNextMeaningfulToken($afterFirstArgIndex); + $tokens->insertAt($secondArgIndex, new Token([T_ELLIPSIS, '...'])); + } + + $tokens->clearAt($afterFirstArgIndex); + $tokens->removeTrailingWhitespace($afterFirstArgIndex); + } + + $tokens->overrideRange($callIndex, $callIndex, $newCallTokens); + $prevIndex = $tokens->getPrevMeaningfulToken($callIndex); + + if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + } + } + + private function getTokensSubcollection(Tokens $tokens, int $indexStart, int $indexEnd): Tokens + { + $size = $indexEnd - $indexStart + 1; + $subCollection = new Tokens($size); + + for ($i = 0; $i < $size; ++$i) { + /** @var Token $toClone */ + $toClone = $tokens[$i + $indexStart]; + $subCollection[$i] = clone $toClone; + } + + return $subCollection; + } + + private function isValidFunctionInvoke(string $name): bool + { + if (\strlen($name) < 3 || 'b' === $name[0] || 'B' === $name[0]) { + return false; + } + + $name = substr($name, 1, -1); + + if ($name !== trim($name)) { + return false; + } + + return true; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php new file mode 100644 index 00000000..356bf45c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php @@ -0,0 +1,119 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class ReturnTypeDeclarationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Adjust spacing around colon in return type declarations and backed enum types.', + [ + new CodeSample( + " 'none'] + ), + new CodeSample( + " 'one'] + ), + ], + 'Rule is applied only in a PHP 7+ environment.' + ); + } + + /** + * {@inheritdoc} + * + * Must run after PhpUnitDataProviderReturnTypeFixer, PhpdocToReturnTypeFixer, VoidReturnFixer. + */ + public function getPriority(): int + { + return -17; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(CT::T_TYPE_COLON); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $oneSpaceBefore = 'one' === $this->configuration['space_before']; + + for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) { + if (!$tokens[$index]->isGivenKind(CT::T_TYPE_COLON)) { + continue; + } + + $previousIndex = $index - 1; + $previousToken = $tokens[$previousIndex]; + + if ($previousToken->isWhitespace()) { + if (!$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { + if ($oneSpaceBefore) { + $tokens[$previousIndex] = new Token([T_WHITESPACE, ' ']); + } else { + $tokens->clearAt($previousIndex); + } + } + } elseif ($oneSpaceBefore) { + $tokenWasAdded = $tokens->ensureWhitespaceAtIndex($index, 0, ' '); + + if ($tokenWasAdded) { + ++$limit; + } + + ++$index; + } + + ++$index; + + $tokenWasAdded = $tokens->ensureWhitespaceAtIndex($index, 0, ' '); + + if ($tokenWasAdded) { + ++$limit; + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('space_before', 'Spacing to apply before colon.')) + ->setAllowedValues(['one', 'none']) + ->setDefault('none') + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/SingleLineThrowFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/SingleLineThrowFixer.php new file mode 100644 index 00000000..3ee0d51a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/SingleLineThrowFixer.php @@ -0,0 +1,159 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + */ +final class SingleLineThrowFixer extends AbstractFixer +{ + private const REMOVE_WHITESPACE_AFTER_TOKENS = ['[']; + private const REMOVE_WHITESPACE_AROUND_TOKENS = ['(', [T_DOUBLE_COLON]]; + private const REMOVE_WHITESPACE_BEFORE_TOKENS = [')', ']', ',', ';']; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Throwing exception must be done in single line.', + [ + new CodeSample("isTokenKindFound(T_THROW); + } + + /** + * {@inheritdoc} + * + * Must run before BracesFixer, ConcatSpaceFixer. + */ + public function getPriority(): int + { + return 36; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + if (!$tokens[$index]->isGivenKind(T_THROW)) { + continue; + } + + $endCandidateIndex = $tokens->getNextMeaningfulToken($index); + + while (!$tokens[$endCandidateIndex]->equalsAny([')', ']', ',', ';', [T_CLOSE_TAG]])) { + $blockType = Tokens::detectBlockType($tokens[$endCandidateIndex]); + + if (null !== $blockType) { + if (Tokens::BLOCK_TYPE_CURLY_BRACE === $blockType['type'] || !$blockType['isStart']) { + break; + } + + $endCandidateIndex = $tokens->findBlockEnd($blockType['type'], $endCandidateIndex); + } + + $endCandidateIndex = $tokens->getNextMeaningfulToken($endCandidateIndex); + } + + $this->trimNewLines($tokens, $index, $tokens->getPrevMeaningfulToken($endCandidateIndex)); + } + } + + private function trimNewLines(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($index = $startIndex; $index < $endIndex; ++$index) { + $content = $tokens[$index]->getContent(); + + if ($tokens[$index]->isGivenKind(T_COMMENT)) { + if (str_starts_with($content, '//')) { + $content = '/*'.substr($content, 2).' */'; + $tokens->clearAt($index + 1); + } elseif (str_starts_with($content, '#')) { + $content = '/*'.substr($content, 1).' */'; + $tokens->clearAt($index + 1); + } elseif (Preg::match('/\R/', $content)) { + $content = Preg::replace('/\R/', ' ', $content); + } + + $tokens[$index] = new Token([T_COMMENT, $content]); + + continue; + } + + if (!$tokens[$index]->isGivenKind(T_WHITESPACE)) { + continue; + } + + if (!Preg::match('/\R/', $content)) { + continue; + } + + $prevIndex = $tokens->getNonEmptySibling($index, -1); + + if ($this->isPreviousTokenToClear($tokens[$prevIndex])) { + $tokens->clearAt($index); + + continue; + } + + $nextIndex = $tokens->getNonEmptySibling($index, 1); + + if ( + $this->isNextTokenToClear($tokens[$nextIndex]) + && !$tokens[$prevIndex]->isGivenKind(T_FUNCTION) + ) { + $tokens->clearAt($index); + + continue; + } + + $tokens[$index] = new Token([T_WHITESPACE, ' ']); + } + } + + private function isPreviousTokenToClear(Token $token): bool + { + static $tokens = null; + + if (null === $tokens) { + $tokens = [...self::REMOVE_WHITESPACE_AFTER_TOKENS, ...self::REMOVE_WHITESPACE_AROUND_TOKENS]; + } + + return $token->equalsAny($tokens) || $token->isObjectOperator(); + } + + private function isNextTokenToClear(Token $token): bool + { + static $tokens = null; + + if (null === $tokens) { + $tokens = [...self::REMOVE_WHITESPACE_AROUND_TOKENS, ...self::REMOVE_WHITESPACE_BEFORE_TOKENS]; + } + + return $token->equalsAny($tokens) || $token->isObjectOperator(); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/StaticLambdaFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/StaticLambdaFixer.php new file mode 100644 index 00000000..81763f7f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/StaticLambdaFixer.php @@ -0,0 +1,130 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +final class StaticLambdaFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Lambdas not (indirectly) referencing `$this` must be declared `static`.', + [new CodeSample("bindTo` on lambdas without referencing to `$this`.' + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([T_FUNCTION, T_FN]); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $analyzer = new TokensAnalyzer($tokens); + $expectedFunctionKinds = [T_FUNCTION, T_FN]; + + for ($index = $tokens->count() - 4; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind($expectedFunctionKinds) || !$analyzer->isLambda($index)) { + continue; + } + + $prev = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prev]->isGivenKind(T_STATIC)) { + continue; // lambda is already 'static' + } + + $argumentsStartIndex = $tokens->getNextTokenOfKind($index, ['(']); + $argumentsEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $argumentsStartIndex); + + // figure out where the lambda starts and ends + + if ($tokens[$index]->isGivenKind(T_FUNCTION)) { + $lambdaOpenIndex = $tokens->getNextTokenOfKind($argumentsEndIndex, ['{']); + $lambdaEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $lambdaOpenIndex); + } else { // T_FN + $lambdaOpenIndex = $tokens->getNextTokenOfKind($argumentsEndIndex, [[T_DOUBLE_ARROW]]); + $lambdaEndIndex = $analyzer->getLastTokenIndexOfArrowFunction($index); + } + + if ($this->hasPossibleReferenceToThis($tokens, $lambdaOpenIndex, $lambdaEndIndex)) { + continue; + } + + // make the lambda static + $tokens->insertAt( + $index, + [ + new Token([T_STATIC, 'static']), + new Token([T_WHITESPACE, ' ']), + ] + ); + + $index -= 4; // fixed after a lambda, closes candidate is at least 4 tokens before that + } + } + + /** + * Returns 'true' if there is a possible reference to '$this' within the given tokens index range. + */ + private function hasPossibleReferenceToThis(Tokens $tokens, int $startIndex, int $endIndex): bool + { + for ($i = $startIndex; $i <= $endIndex; ++$i) { + if ($tokens[$i]->isGivenKind(T_VARIABLE) && '$this' === strtolower($tokens[$i]->getContent())) { + return true; // directly accessing '$this' + } + + if ($tokens[$i]->isGivenKind([ + T_INCLUDE, // loading additional symbols we cannot analyze here + T_INCLUDE_ONCE, // " + T_REQUIRE, // " + T_REQUIRE_ONCE, // " + CT::T_DYNAMIC_VAR_BRACE_OPEN, // "$h = ${$g};" case + T_EVAL, // "$c = eval('return $this;');" case + ])) { + return true; + } + + if ($tokens[$i]->equals('$')) { + $nextIndex = $tokens->getNextMeaningfulToken($i); + + if ($tokens[$nextIndex]->isGivenKind(T_VARIABLE)) { + return true; // "$$a" case + } + } + + if ($tokens[$i]->equals([T_STRING, 'parent'], false)) { + return true; // parent:: case + } + } + + return false; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/UseArrowFunctionsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/UseArrowFunctionsFixer.php new file mode 100644 index 00000000..5cafd0a3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/UseArrowFunctionsFixer.php @@ -0,0 +1,203 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Gregor Harlan + */ +final class UseArrowFunctionsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Anonymous functions with one-liner return statement must use arrow functions.', + [ + new CodeSample( + <<<'SAMPLE' + isAllTokenKindsFound([T_FUNCTION, T_RETURN]); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run before FunctionDeclarationFixer. + */ + public function getPriority(): int + { + return 32; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $analyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(T_FUNCTION) || !$analyzer->isLambda($index)) { + continue; + } + + // Find parameters end + // Abort if they are multilined + + $parametersStart = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$parametersStart]->isGivenKind(CT::T_RETURN_REF)) { + $parametersStart = $tokens->getNextMeaningfulToken($parametersStart); + } + + $parametersEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $parametersStart); + + if ($this->isMultilined($tokens, $parametersStart, $parametersEnd)) { + continue; + } + + // Find `use ()` start and end + // Abort if it contains reference variables + + $next = $tokens->getNextMeaningfulToken($parametersEnd); + + $useStart = null; + $useEnd = null; + + if ($tokens[$next]->isGivenKind(CT::T_USE_LAMBDA)) { + $useStart = $next; + + if ($tokens[$useStart - 1]->isGivenKind(T_WHITESPACE)) { + --$useStart; + } + + $next = $tokens->getNextMeaningfulToken($next); + + while (!$tokens[$next]->equals(')')) { + if ($tokens[$next]->equals('&')) { + // variables used by reference are not supported by arrow functions + continue 2; + } + + $next = $tokens->getNextMeaningfulToken($next); + } + + $useEnd = $next; + $next = $tokens->getNextMeaningfulToken($next); + } + + // Find opening brace and following `return` + // Abort if there is more than whitespace between them (like comments) + + $braceOpen = $tokens[$next]->equals('{') ? $next : $tokens->getNextTokenOfKind($next, ['{']); + $return = $braceOpen + 1; + + if ($tokens[$return]->isGivenKind(T_WHITESPACE)) { + ++$return; + } + + if (!$tokens[$return]->isGivenKind(T_RETURN)) { + continue; + } + + // Find semicolon of `return` statement + + $semicolon = $tokens->getNextTokenOfKind($return, ['{', ';']); + + if (!$tokens[$semicolon]->equals(';')) { + continue; + } + + // Find closing brace + // Abort if there is more than whitespace between semicolon and closing brace + + $braceClose = $semicolon + 1; + + if ($tokens[$braceClose]->isGivenKind(T_WHITESPACE)) { + ++$braceClose; + } + + if (!$tokens[$braceClose]->equals('}')) { + continue; + } + + // Abort if the `return` statement is multilined + + if ($this->isMultilined($tokens, $return, $semicolon)) { + continue; + } + + // Transform the function to an arrow function + + $this->transform($tokens, $index, $useStart, $useEnd, $braceOpen, $return, $semicolon, $braceClose); + } + } + + private function isMultilined(Tokens $tokens, int $start, int $end): bool + { + for ($i = $start; $i < $end; ++$i) { + if (str_contains($tokens[$i]->getContent(), "\n")) { + return true; + } + } + + return false; + } + + private function transform(Tokens $tokens, int $index, ?int $useStart, ?int $useEnd, int $braceOpen, int $return, int $semicolon, int $braceClose): void + { + $tokensToInsert = [new Token([T_DOUBLE_ARROW, '=>'])]; + + if ($tokens->getNextMeaningfulToken($return) === $semicolon) { + $tokensToInsert[] = new Token([T_WHITESPACE, ' ']); + $tokensToInsert[] = new Token([T_STRING, 'null']); + } + + $tokens->clearRange($semicolon, $braceClose); + $tokens->clearRange($braceOpen + 1, $return); + $tokens->overrideRange($braceOpen, $braceOpen, $tokensToInsert); + + if (null !== $useStart) { + $tokens->clearRange($useStart, $useEnd); + } + + $tokens[$index] = new Token([T_FN, 'fn']); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/VoidReturnFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/VoidReturnFixer.php new file mode 100644 index 00000000..65e8268d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/VoidReturnFixer.php @@ -0,0 +1,256 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Mark Nielsen + */ +final class VoidReturnFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Add `void` return type to functions with missing or empty return statements, but priority is given to `@return` annotations. Requires PHP >= 7.1.', + [ + new CodeSample( + "isTokenKindFound(T_FUNCTION); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + // These cause syntax errors. + static $excludedFunctions = [ + [T_STRING, '__clone'], + [T_STRING, '__construct'], + [T_STRING, '__debugInfo'], + [T_STRING, '__destruct'], + [T_STRING, '__isset'], + [T_STRING, '__serialize'], + [T_STRING, '__set_state'], + [T_STRING, '__sleep'], + [T_STRING, '__toString'], + ]; + + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + if (!$tokens[$index]->isGivenKind(T_FUNCTION)) { + continue; + } + + $functionName = $tokens->getNextMeaningfulToken($index); + if ($tokens[$functionName]->equalsAny($excludedFunctions, false)) { + continue; + } + + $startIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + + if ($this->hasReturnTypeHint($tokens, $startIndex)) { + continue; + } + + if ($tokens[$startIndex]->equals(';')) { + // No function body defined, fallback to PHPDoc. + if ($this->hasVoidReturnAnnotation($tokens, $index)) { + $this->fixFunctionDefinition($tokens, $startIndex); + } + + continue; + } + + if ($this->hasReturnAnnotation($tokens, $index)) { + continue; + } + + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex); + + if ($this->hasVoidReturn($tokens, $startIndex, $endIndex)) { + $this->fixFunctionDefinition($tokens, $startIndex); + } + } + } + + /** + * Determine whether there is a non-void return annotation in the function's PHPDoc comment. + * + * @param int $index The index of the function token + */ + private function hasReturnAnnotation(Tokens $tokens, int $index): bool + { + foreach ($this->findReturnAnnotations($tokens, $index) as $return) { + if (['void'] !== $return->getTypes()) { + return true; + } + } + + return false; + } + + /** + * Determine whether there is a void return annotation in the function's PHPDoc comment. + * + * @param int $index The index of the function token + */ + private function hasVoidReturnAnnotation(Tokens $tokens, int $index): bool + { + foreach ($this->findReturnAnnotations($tokens, $index) as $return) { + if (['void'] === $return->getTypes()) { + return true; + } + } + + return false; + } + + /** + * Determine whether the function already has a return type hint. + * + * @param int $index The index of the end of the function definition line, EG at { or ; + */ + private function hasReturnTypeHint(Tokens $tokens, int $index): bool + { + $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); + $nextIndex = $tokens->getNextMeaningfulToken($endFuncIndex); + + return $tokens[$nextIndex]->isGivenKind(CT::T_TYPE_COLON); + } + + /** + * Determine whether the function has a void return. + * + * @param int $startIndex Start of function body + * @param int $endIndex End of function body + */ + private function hasVoidReturn(Tokens $tokens, int $startIndex, int $endIndex): bool + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($i = $startIndex; $i < $endIndex; ++$i) { + if ( + // skip anonymous classes + ($tokens[$i]->isGivenKind(T_CLASS) && $tokensAnalyzer->isAnonymousClass($i)) + // skip lambda functions + || ($tokens[$i]->isGivenKind(T_FUNCTION) && $tokensAnalyzer->isLambda($i)) + ) { + $i = $tokens->getNextTokenOfKind($i, ['{']); + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $i); + + continue; + } + + if ($tokens[$i]->isGivenKind([T_YIELD, T_YIELD_FROM])) { + return false; // Generators cannot return void. + } + + if (!$tokens[$i]->isGivenKind(T_RETURN)) { + continue; + } + + $i = $tokens->getNextMeaningfulToken($i); + if (!$tokens[$i]->equals(';')) { + return false; + } + } + + return true; + } + + /** + * @param int $index The index of the end of the function definition line, EG at { or ; + */ + private function fixFunctionDefinition(Tokens $tokens, int $index): void + { + $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); + $tokens->insertAt($endFuncIndex + 1, [ + new Token([CT::T_TYPE_COLON, ':']), + new Token([T_WHITESPACE, ' ']), + new Token([T_STRING, 'void']), + ]); + } + + /** + * Find all the return annotations in the function's PHPDoc comment. + * + * @param int $index The index of the function token + * + * @return Annotation[] + */ + private function findReturnAnnotations(Tokens $tokens, int $index): array + { + $previousTokens = [ + T_ABSTRACT, + T_FINAL, + T_PRIVATE, + T_PROTECTED, + T_PUBLIC, + T_STATIC, + ]; + + if (\defined('T_ATTRIBUTE')) { // @TODO: drop condition when PHP 8.0+ is required + $previousTokens[] = T_ATTRIBUTE; + } + + do { + $index = $tokens->getPrevNonWhitespace($index); + + if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $index = $tokens->getPrevTokenOfKind($index, [[T_ATTRIBUTE]]); + } + } while ($tokens[$index]->isGivenKind($previousTokens)); + + if (!$tokens[$index]->isGivenKind(T_DOC_COMMENT)) { + return []; + } + + $doc = new DocBlock($tokens[$index]->getContent()); + + return $doc->getAnnotationsOfType('return'); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php new file mode 100644 index 00000000..e9f04f3c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php @@ -0,0 +1,303 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author VeeWee + */ +final class FullyQualifiedStrictTypesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Transforms imported FQCN parameters and return types in function arguments to short version.', + [ + new CodeSample( + ' true] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoSuperfluousPhpdocTagsFixer. + * Must run after PhpdocToReturnTypeFixer. + */ + public function getPriority(): int + { + return 7; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_FUNCTION); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder( + 'leading_backslash_in_global_namespace', + 'Whether FQCN is prefixed with backslash when that FQCN is used in global namespace context.' + )) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); + $functionsAnalyzer = new FunctionsAnalyzer(); + + foreach ($tokens->getNamespaceDeclarations() as $namespace) { + $namespaceName = strtolower($namespace->getFullName()); + $uses = []; + + foreach ($namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace) as $use) { + $uses[strtolower(ltrim($use->getFullName(), '\\'))] = $use->getShortName(); + } + + for ($index = $namespace->getScopeStartIndex(); $index < $namespace->getScopeEndIndex(); ++$index) { + if ($tokens[$index]->isGivenKind(T_FUNCTION)) { + $this->fixFunction($functionsAnalyzer, $tokens, $index, $uses, $namespaceName); + } + } + } + } + + /** + * @param array $uses + */ + private function fixFunction(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index, array $uses, string $namespaceName): void + { + $arguments = $functionsAnalyzer->getFunctionArguments($tokens, $index); + + foreach ($arguments as $i => $argument) { + $argument = $functionsAnalyzer->getFunctionArguments($tokens, $index)[$i]; + + if ($argument->hasTypeAnalysis()) { + $this->replaceByShortType($tokens, $argument->getTypeAnalysis(), $uses, $namespaceName); + } + } + + $returnTypeAnalysis = $functionsAnalyzer->getFunctionReturnType($tokens, $index); + + if (null !== $returnTypeAnalysis) { + $this->replaceByShortType($tokens, $returnTypeAnalysis, $uses, $namespaceName); + } + } + + /** + * @param array $uses + */ + private function replaceByShortType(Tokens $tokens, TypeAnalysis $type, array $uses, string $namespaceName): void + { + $typeStartIndex = $type->getStartIndex(); + + if ($tokens[$typeStartIndex]->isGivenKind(CT::T_NULLABLE_TYPE)) { + $typeStartIndex = $tokens->getNextMeaningfulToken($typeStartIndex); + } + + $namespaceNameLength = \strlen($namespaceName); + $types = $this->getTypes($tokens, $typeStartIndex, $type->getEndIndex()); + + foreach ($types as $typeName => [$startIndex, $endIndex]) { + if ((new TypeAnalysis($typeName))->isReservedType()) { + return; + } + + $withLeadingBackslash = str_starts_with($typeName, '\\'); + if ($withLeadingBackslash) { + $typeName = substr($typeName, 1); + } + $typeNameLower = strtolower($typeName); + + if (isset($uses[$typeNameLower]) && ($withLeadingBackslash || '' === $namespaceName)) { + // if the type without leading "\" equals any of the full "uses" long names, it can be replaced with the short one + $tokens->overrideRange($startIndex, $endIndex, $this->namespacedStringToTokens($uses[$typeNameLower])); + + continue; + } + + if ('' === $namespaceName) { + foreach ($uses as $useShortName) { + if (strtolower($useShortName) === $typeNameLower) { + continue 2; + } + } + + // if we are in the global namespace and the type is not imported, + // we enforce/remove leading backslash (depending on the configuration) + if (true === $this->configuration['leading_backslash_in_global_namespace']) { + if (!$withLeadingBackslash && !isset($uses[$typeNameLower])) { + $tokens->overrideRange( + $startIndex, + $endIndex, + $this->namespacedStringToTokens($typeName, true) + ); + } + } else { + $tokens->overrideRange($startIndex, $endIndex, $this->namespacedStringToTokens($typeName)); + } + } elseif (!str_contains($typeName, '\\')) { + // If we're NOT in the global namespace, there's no related import, + // AND used type is from global namespace, then it can't be shortened. + continue; + } elseif ($typeNameLower !== $namespaceName && str_starts_with($typeNameLower, $namespaceName.'\\')) { + // if the type starts with namespace and the type is not the same as the namespace it can be shortened + $typeNameShort = substr($typeName, $namespaceNameLength + 1); + + // if short names are the same, but long one are different then it cannot be shortened + foreach ($uses as $useLongName => $useShortName) { + if ( + strtolower($typeNameShort) === strtolower($useShortName) + && strtolower($typeName) !== strtolower($useLongName) + ) { + continue 2; + } + } + + $tokens->overrideRange($startIndex, $endIndex, $this->namespacedStringToTokens($typeNameShort)); + } + } + } + + /** + * @return iterable + */ + private function getTypes(Tokens $tokens, int $index, int $endIndex): iterable + { + $skipNextYield = false; + $typeStartIndex = $typeEndIndex = null; + $type = null; + while (true) { + if ($tokens[$index]->isGivenKind(CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN)) { + $index = $tokens->getNextMeaningfulToken($index); + $typeStartIndex = $typeEndIndex = null; + $type = null; + + continue; + } + + if ( + $tokens[$index]->isGivenKind([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE]) + || $index > $endIndex + ) { + if (!$skipNextYield && null !== $typeStartIndex) { + $origCount = \count($tokens); + + yield $type => [$typeStartIndex, $typeEndIndex]; + + $endIndex += \count($tokens) - $origCount; + + // type tokens were possibly updated, restart type match + $skipNextYield = true; + $index = $typeEndIndex = $typeStartIndex; + $type = null; + } else { + $skipNextYield = false; + $index = $tokens->getNextMeaningfulToken($index); + $typeStartIndex = $typeEndIndex = null; + $type = null; + } + + if ($index > $endIndex) { + break; + } + + continue; + } + + if (null === $typeStartIndex) { + $typeStartIndex = $index; + $type = ''; + } + + $typeEndIndex = $index; + $type .= $tokens[$index]->getContent(); + + $index = $tokens->getNextMeaningfulToken($index); + } + } + + /** + * @return Token[] + */ + private function namespacedStringToTokens(string $input, bool $withLeadingBackslash = false): array + { + $tokens = []; + + if ($withLeadingBackslash) { + $tokens[] = new Token([T_NS_SEPARATOR, '\\']); + } + + $parts = explode('\\', $input); + foreach ($parts as $index => $part) { + $tokens[] = new Token([T_STRING, $part]); + + if ($index !== \count($parts) - 1) { + $tokens[] = new Token([T_NS_SEPARATOR, '\\']); + } + } + + return $tokens; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GlobalNamespaceImportFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GlobalNamespaceImportFixer.php new file mode 100644 index 00000000..adda9828 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GlobalNamespaceImportFixer.php @@ -0,0 +1,730 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\ClassyAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Gregor Harlan + */ +final class GlobalNamespaceImportFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Imports or fully qualifies global classes/functions/constants.', + [ + new CodeSample( + ' true, 'import_constants' => true, 'import_functions' => true] + ), + new CodeSample( + ' false, 'import_constants' => false, 'import_functions' => false] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoUnusedImportsFixer, OrderedImportsFixer. + * Must run after NativeConstantInvocationFixer, NativeFunctionInvocationFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([T_DOC_COMMENT, T_NS_SEPARATOR, T_USE]) + && $tokens->isTokenKindFound(T_NAMESPACE) + && 1 === $tokens->countTokenKind(T_NAMESPACE) + && $tokens->isMonolithicPhp(); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $namespaceAnalyses = $tokens->getNamespaceDeclarations(); + + if (1 !== \count($namespaceAnalyses) || $namespaceAnalyses[0]->isGlobalNamespace()) { + return; + } + + $useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens); + + $newImports = []; + + if (true === $this->configuration['import_constants']) { + $newImports['const'] = $this->importConstants($tokens, $useDeclarations); + } elseif (false === $this->configuration['import_constants']) { + $this->fullyQualifyConstants($tokens, $useDeclarations); + } + + if (true === $this->configuration['import_functions']) { + $newImports['function'] = $this->importFunctions($tokens, $useDeclarations); + } elseif (false === $this->configuration['import_functions']) { + $this->fullyQualifyFunctions($tokens, $useDeclarations); + } + + if (true === $this->configuration['import_classes']) { + $newImports['class'] = $this->importClasses($tokens, $useDeclarations); + } elseif (false === $this->configuration['import_classes']) { + $this->fullyQualifyClasses($tokens, $useDeclarations); + } + + $newImports = array_filter($newImports); + + if (\count($newImports) > 0) { + $this->insertImports($tokens, $newImports, $useDeclarations); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('import_constants', 'Whether to import, not import or ignore global constants.')) + ->setDefault(null) + ->setAllowedValues([true, false, null]) + ->getOption(), + (new FixerOptionBuilder('import_functions', 'Whether to import, not import or ignore global functions.')) + ->setDefault(null) + ->setAllowedValues([true, false, null]) + ->getOption(), + (new FixerOptionBuilder('import_classes', 'Whether to import, not import or ignore global classes.')) + ->setDefault(true) + ->setAllowedValues([true, false, null]) + ->getOption(), + ]); + } + + /** + * @param NamespaceUseAnalysis[] $useDeclarations + * + * @return array + */ + private function importConstants(Tokens $tokens, array $useDeclarations): array + { + [$global, $other] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isConstant(), true); + + // find namespaced const declarations (`const FOO = 1`) + // and add them to the not importable names (already used) + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + $token = $tokens[$index]; + + if ($token->isClassy()) { + $index = $tokens->getNextTokenOfKind($index, ['{']); + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + + continue; + } + + if (!$token->isGivenKind(T_CONST)) { + continue; + } + + $index = $tokens->getNextMeaningfulToken($index); + $other[$tokens[$index]->getContent()] = true; + } + + $analyzer = new TokensAnalyzer($tokens); + $indices = []; + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(T_STRING)) { + continue; + } + + $name = $token->getContent(); + + if (isset($other[$name])) { + continue; + } + + if (!$analyzer->isConstantInvocation($index)) { + continue; + } + + $nsSeparatorIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$nsSeparatorIndex]->isGivenKind(T_NS_SEPARATOR)) { + if (!isset($global[$name])) { + // found an unqualified constant invocation + // add it to the not importable names (already used) + $other[$name] = true; + } + + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($nsSeparatorIndex); + if ($tokens[$prevIndex]->isGivenKind([CT::T_NAMESPACE_OPERATOR, T_STRING])) { + continue; + } + + $indices[] = $index; + } + + return $this->prepareImports($tokens, $indices, $global, $other, true); + } + + /** + * @param NamespaceUseAnalysis[] $useDeclarations + * + * @return array + */ + private function importFunctions(Tokens $tokens, array $useDeclarations): array + { + [$global, $other] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isFunction(), false); + + // find function declarations + // and add them to the not importable names (already used) + foreach ($this->findFunctionDeclarations($tokens, 0, $tokens->count() - 1) as $name) { + $other[strtolower($name)] = true; + } + + $analyzer = new FunctionsAnalyzer(); + $indices = []; + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(T_STRING)) { + continue; + } + + $name = strtolower($token->getContent()); + + if (isset($other[$name])) { + continue; + } + + if (!$analyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + $nsSeparatorIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$nsSeparatorIndex]->isGivenKind(T_NS_SEPARATOR)) { + if (!isset($global[$name])) { + $other[$name] = true; + } + + continue; + } + + $indices[] = $index; + } + + return $this->prepareImports($tokens, $indices, $global, $other, false); + } + + /** + * @param NamespaceUseAnalysis[] $useDeclarations + * + * @return array + */ + private function importClasses(Tokens $tokens, array $useDeclarations): array + { + [$global, $other] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isClass(), false); + + /** @var DocBlock[] $docBlocks */ + $docBlocks = []; + + // find class declarations and class usages in docblocks + // and add them to the not importable names (already used) + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(T_DOC_COMMENT)) { + $docBlocks[$index] = new DocBlock($token->getContent()); + + $this->traverseDocBlockTypes($docBlocks[$index], static function (string $type) use ($global, &$other): void { + if (str_contains($type, '\\')) { + return; + } + + $name = strtolower($type); + + if (!isset($global[$name])) { + $other[$name] = true; + } + }); + } + + if (!$token->isClassy()) { + continue; + } + + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(T_STRING)) { + $other[strtolower($tokens[$index]->getContent())] = true; + } + } + + $analyzer = new ClassyAnalyzer(); + $indices = []; + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(T_STRING)) { + continue; + } + + $name = strtolower($token->getContent()); + + if (isset($other[$name])) { + continue; + } + + if (!$analyzer->isClassyInvocation($tokens, $index)) { + continue; + } + + $nsSeparatorIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$nsSeparatorIndex]->isGivenKind(T_NS_SEPARATOR)) { + if (!isset($global[$name])) { + $other[$name] = true; + } + + continue; + } + + if ($tokens[$tokens->getPrevMeaningfulToken($nsSeparatorIndex)]->isGivenKind([CT::T_NAMESPACE_OPERATOR, T_STRING])) { + continue; + } + + $indices[] = $index; + } + + $imports = []; + + foreach ($docBlocks as $index => $docBlock) { + $changed = $this->traverseDocBlockTypes($docBlock, static function (string $type) use ($global, $other, &$imports): string { + if ('\\' !== $type[0]) { + return $type; + } + + $name = substr($type, 1); + $checkName = strtolower($name); + + if (str_contains($checkName, '\\') || isset($other[$checkName])) { + return $type; + } + + if (isset($global[$checkName])) { + return \is_string($global[$checkName]) ? $global[$checkName] : $name; + } + + $imports[$checkName] = $name; + + return $name; + }); + + if ($changed) { + $tokens[$index] = new Token([T_DOC_COMMENT, $docBlock->getContent()]); + } + } + + return $imports + $this->prepareImports($tokens, $indices, $global, $other, false); + } + + /** + * Removes the leading slash at the given indices (when the name is not already used). + * + * @param int[] $indices + * @param array $other + * + * @return array array keys contain the names that must be imported + */ + private function prepareImports(Tokens $tokens, array $indices, array $global, array $other, bool $caseSensitive): array + { + $imports = []; + + foreach ($indices as $index) { + $name = $tokens[$index]->getContent(); + $checkName = $caseSensitive ? $name : strtolower($name); + + if (isset($other[$checkName])) { + continue; + } + + if (!isset($global[$checkName])) { + $imports[$checkName] = $name; + } elseif (\is_string($global[$checkName])) { + $tokens[$index] = new Token([T_STRING, $global[$checkName]]); + } + + $tokens->clearAt($tokens->getPrevMeaningfulToken($index)); + } + + return $imports; + } + + /** + * @param NamespaceUseAnalysis[] $useDeclarations + */ + private function insertImports(Tokens $tokens, array $imports, array $useDeclarations): void + { + if (\count($useDeclarations) > 0) { + $useDeclaration = end($useDeclarations); + $index = $useDeclaration->getEndIndex() + 1; + } else { + $namespace = $tokens->getNamespaceDeclarations()[0]; + $index = $namespace->getEndIndex() + 1; + } + + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + if (!$tokens[$index]->isWhitespace() || !str_contains($tokens[$index]->getContent(), "\n")) { + $tokens->insertAt($index, new Token([T_WHITESPACE, $lineEnding])); + } + + foreach ($imports as $type => $typeImports) { + foreach ($typeImports as $name) { + $items = [ + new Token([T_WHITESPACE, $lineEnding]), + new Token([T_USE, 'use']), + new Token([T_WHITESPACE, ' ']), + ]; + + if ('const' === $type) { + $items[] = new Token([CT::T_CONST_IMPORT, 'const']); + $items[] = new Token([T_WHITESPACE, ' ']); + } elseif ('function' === $type) { + $items[] = new Token([CT::T_FUNCTION_IMPORT, 'function']); + $items[] = new Token([T_WHITESPACE, ' ']); + } + + $items[] = new Token([T_STRING, $name]); + $items[] = new Token(';'); + + $tokens->insertAt($index, $items); + } + } + } + + /** + * @param NamespaceUseAnalysis[] $useDeclarations + */ + private function fullyQualifyConstants(Tokens $tokens, array $useDeclarations): void + { + if (!$tokens->isTokenKindFound(CT::T_CONST_IMPORT)) { + return; + } + + [$global] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isConstant() && !$declaration->isAliased(), true); + + if (!$global) { + return; + } + + $analyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(T_STRING)) { + continue; + } + + if (!isset($global[$token->getContent()])) { + continue; + } + + if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_NS_SEPARATOR)) { + continue; + } + + if (!$analyzer->isConstantInvocation($index)) { + continue; + } + + $tokens->insertAt($index, new Token([T_NS_SEPARATOR, '\\'])); + } + } + + /** + * @param NamespaceUseAnalysis[] $useDeclarations + */ + private function fullyQualifyFunctions(Tokens $tokens, array $useDeclarations): void + { + if (!$tokens->isTokenKindFound(CT::T_FUNCTION_IMPORT)) { + return; + } + + [$global] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isFunction() && !$declaration->isAliased(), false); + + if (!$global) { + return; + } + + $analyzer = new FunctionsAnalyzer(); + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(T_STRING)) { + continue; + } + + if (!isset($global[strtolower($token->getContent())])) { + continue; + } + + if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_NS_SEPARATOR)) { + continue; + } + + if (!$analyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + $tokens->insertAt($index, new Token([T_NS_SEPARATOR, '\\'])); + } + } + + /** + * @param NamespaceUseAnalysis[] $useDeclarations + */ + private function fullyQualifyClasses(Tokens $tokens, array $useDeclarations): void + { + if (!$tokens->isTokenKindFound(T_USE)) { + return; + } + + [$global] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isClass() && !$declaration->isAliased(), false); + + if (!$global) { + return; + } + + $analyzer = new ClassyAnalyzer(); + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(T_DOC_COMMENT)) { + $doc = new DocBlock($token->getContent()); + + $changed = $this->traverseDocBlockTypes($doc, static function (string $type) use ($global): string { + if (!isset($global[strtolower($type)])) { + return $type; + } + + return '\\'.$type; + }); + + if ($changed) { + $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); + } + + continue; + } + + if (!$token->isGivenKind(T_STRING)) { + continue; + } + + if (!isset($global[strtolower($token->getContent())])) { + continue; + } + + if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_NS_SEPARATOR)) { + continue; + } + + if (!$analyzer->isClassyInvocation($tokens, $index)) { + continue; + } + + $tokens->insertAt($index, new Token([T_NS_SEPARATOR, '\\'])); + } + } + + /** + * @param NamespaceUseAnalysis[] $declarations + */ + private function filterUseDeclarations(array $declarations, callable $callback, bool $caseSensitive): array + { + $global = []; + $other = []; + + foreach ($declarations as $declaration) { + if (!$callback($declaration)) { + continue; + } + + $fullName = ltrim($declaration->getFullName(), '\\'); + + if (str_contains($fullName, '\\')) { + $name = $caseSensitive ? $declaration->getShortName() : strtolower($declaration->getShortName()); + $other[$name] = true; + + continue; + } + + $checkName = $caseSensitive ? $fullName : strtolower($fullName); + $alias = $declaration->getShortName(); + $global[$checkName] = $alias === $fullName ? true : $alias; + } + + return [$global, $other]; + } + + /** + * @return iterable + */ + private function findFunctionDeclarations(Tokens $tokens, int $start, int $end): iterable + { + for ($index = $start; $index <= $end; ++$index) { + $token = $tokens[$index]; + + if ($token->isClassy()) { + $classStart = $tokens->getNextTokenOfKind($index, ['{']); + $classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classStart); + + for ($index = $classStart; $index <= $classEnd; ++$index) { + if (!$tokens[$index]->isGivenKind(T_FUNCTION)) { + continue; + } + + $methodStart = $tokens->getNextTokenOfKind($index, ['{', ';']); + + if ($tokens[$methodStart]->equals(';')) { + $index = $methodStart; + + continue; + } + + $methodEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $methodStart); + + foreach ($this->findFunctionDeclarations($tokens, $methodStart, $methodEnd) as $function) { + yield $function; + } + + $index = $methodEnd; + } + + continue; + } + + if (!$token->isGivenKind(T_FUNCTION)) { + continue; + } + + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(CT::T_RETURN_REF)) { + $index = $tokens->getNextMeaningfulToken($index); + } + + if ($tokens[$index]->isGivenKind(T_STRING)) { + yield $tokens[$index]->getContent(); + } + } + } + + private function traverseDocBlockTypes(DocBlock $doc, callable $callback): bool + { + $annotations = $doc->getAnnotationsOfType(Annotation::getTagsWithTypes()); + + if (0 === \count($annotations)) { + return false; + } + + $changed = false; + + foreach ($annotations as $annotation) { + $types = $new = $annotation->getTypes(); + + foreach ($types as $i => $fullType) { + $newFullType = $fullType; + + Preg::matchAll('/[\\\\\w]+/', $fullType, $matches, PREG_OFFSET_CAPTURE); + + foreach (array_reverse($matches[0]) as [$type, $offset]) { + $newType = $callback($type); + + if (null !== $newType && $type !== $newType) { + $newFullType = substr_replace($newFullType, $newType, $offset, \strlen($type)); + } + } + + $new[$i] = $newFullType; + } + + if ($types !== $new) { + $annotation->setTypes($new); + $changed = true; + } + } + + return $changed; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GroupImportFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GroupImportFixer.php new file mode 100644 index 00000000..bc506ea7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GroupImportFixer.php @@ -0,0 +1,268 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Volodymyr Kupriienko + */ +final class GroupImportFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There MUST be group use for the same namespaces.', + [ + new CodeSample( + "isTokenKindFound(T_USE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $useWithSameNamespaces = $this->getSameNamespaces($tokens); + + if ([] === $useWithSameNamespaces) { + return; + } + + $this->removeSingleUseStatements($useWithSameNamespaces, $tokens); + $this->addGroupUseStatements($useWithSameNamespaces, $tokens); + } + + /** + * Gets namespace use analyzers with same namespaces. + * + * @return NamespaceUseAnalysis[] + */ + private function getSameNamespaces(Tokens $tokens): array + { + $useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens); + + if (0 === \count($useDeclarations)) { + return []; + } + + $allNamespaceAndType = array_map( + fn (NamespaceUseAnalysis $useDeclaration): string => $this->getNamespaceNameWithSlash($useDeclaration).$useDeclaration->getType(), + $useDeclarations + ); + + $sameNamespaces = array_filter(array_count_values($allNamespaceAndType), static fn (int $count): bool => $count > 1); + $sameNamespaces = array_keys($sameNamespaces); + + $sameNamespaceAnalysis = array_filter($useDeclarations, function (NamespaceUseAnalysis $useDeclaration) use ($sameNamespaces): bool { + $namespaceNameAndType = $this->getNamespaceNameWithSlash($useDeclaration).$useDeclaration->getType(); + + return \in_array($namespaceNameAndType, $sameNamespaces, true); + }); + + usort($sameNamespaceAnalysis, function (NamespaceUseAnalysis $a, NamespaceUseAnalysis $b): int { + $namespaceA = $this->getNamespaceNameWithSlash($a); + $namespaceB = $this->getNamespaceNameWithSlash($b); + + $namespaceDifference = \strlen($namespaceA) <=> \strlen($namespaceB); + + return 0 !== $namespaceDifference ? $namespaceDifference : $a->getFullName() <=> $b->getFullName(); + }); + + return $sameNamespaceAnalysis; + } + + /** + * @param NamespaceUseAnalysis[] $statements + */ + private function removeSingleUseStatements(array $statements, Tokens $tokens): void + { + foreach ($statements as $useDeclaration) { + $index = $useDeclaration->getStartIndex(); + $endIndex = $useDeclaration->getEndIndex(); + + $useStatementTokens = [T_USE, T_WHITESPACE, T_STRING, T_NS_SEPARATOR, T_AS, CT::T_CONST_IMPORT, CT::T_FUNCTION_IMPORT]; + + while ($index !== $endIndex) { + if ($tokens[$index]->isGivenKind($useStatementTokens)) { + $tokens->clearAt($index); + } + + ++$index; + } + + if (isset($tokens[$index]) && $tokens[$index]->equals(';')) { + $tokens->clearAt($index); + } + + ++$index; + + if (isset($tokens[$index]) && $tokens[$index]->isGivenKind(T_WHITESPACE)) { + $tokens->clearAt($index); + } + } + } + + /** + * @param NamespaceUseAnalysis[] $statements + */ + private function addGroupUseStatements(array $statements, Tokens $tokens): void + { + $currentUseDeclaration = null; + $insertIndex = \array_slice($statements, -1)[0]->getEndIndex() + 1; + + foreach ($statements as $index => $useDeclaration) { + if ($this->areDeclarationsDifferent($currentUseDeclaration, $useDeclaration)) { + $currentUseDeclaration = $useDeclaration; + $insertIndex += $this->createNewGroup( + $tokens, + $insertIndex, + $useDeclaration, + $this->getNamespaceNameWithSlash($currentUseDeclaration) + ); + } else { + $newTokens = [ + new Token(','), + new Token([T_WHITESPACE, ' ']), + ]; + + if ($useDeclaration->isAliased()) { + $tokens->insertAt($insertIndex, $newTokens); + $insertIndex += \count($newTokens); + $newTokens = []; + + $insertIndex += $this->insertToGroupUseWithAlias($tokens, $insertIndex, $useDeclaration); + } + + $newTokens[] = new Token([T_STRING, $useDeclaration->getShortName()]); + + if (!isset($statements[$index + 1]) || $this->areDeclarationsDifferent($currentUseDeclaration, $statements[$index + 1])) { + $newTokens[] = new Token([CT::T_GROUP_IMPORT_BRACE_CLOSE, '}']); + $newTokens[] = new Token(';'); + $newTokens[] = new Token([T_WHITESPACE, "\n"]); + } + + $tokens->insertAt($insertIndex, $newTokens); + $insertIndex += \count($newTokens); + } + } + } + + private function getNamespaceNameWithSlash(NamespaceUseAnalysis $useDeclaration): string + { + $position = strrpos($useDeclaration->getFullName(), '\\'); + if (false === $position || 0 === $position) { + return $useDeclaration->getFullName(); + } + + return substr($useDeclaration->getFullName(), 0, $position + 1); + } + + /** + * Insert use with alias to the group. + */ + private function insertToGroupUseWithAlias(Tokens $tokens, int $insertIndex, NamespaceUseAnalysis $useDeclaration): int + { + $newTokens = [ + new Token([T_STRING, substr($useDeclaration->getFullName(), strripos($useDeclaration->getFullName(), '\\') + 1)]), + new Token([T_WHITESPACE, ' ']), + new Token([T_AS, 'as']), + new Token([T_WHITESPACE, ' ']), + ]; + + $tokens->insertAt($insertIndex, $newTokens); + + return \count($newTokens); + } + + /** + * Creates new use statement group. + */ + private function createNewGroup(Tokens $tokens, int $insertIndex, NamespaceUseAnalysis $useDeclaration, string $currentNamespace): int + { + $insertedTokens = 0; + + if (\count($tokens) === $insertIndex) { + $tokens->setSize($insertIndex + 1); + } + + $newTokens = [ + new Token([T_USE, 'use']), + new Token([T_WHITESPACE, ' ']), + ]; + + if ($useDeclaration->isFunction() || $useDeclaration->isConstant()) { + $importStatementParams = $useDeclaration->isFunction() + ? [CT::T_FUNCTION_IMPORT, 'function'] + : [CT::T_CONST_IMPORT, 'const']; + + $newTokens[] = new Token($importStatementParams); + $newTokens[] = new Token([T_WHITESPACE, ' ']); + } + + $namespaceParts = array_filter(explode('\\', $currentNamespace)); + + foreach ($namespaceParts as $part) { + $newTokens[] = new Token([T_STRING, $part]); + $newTokens[] = new Token([T_NS_SEPARATOR, '\\']); + } + + $newTokens[] = new Token([CT::T_GROUP_IMPORT_BRACE_OPEN, '{']); + + $newTokensCount = \count($newTokens); + $tokens->insertAt($insertIndex, $newTokens); + $insertedTokens += $newTokensCount; + + $insertIndex += $newTokensCount; + + if ($useDeclaration->isAliased()) { + $inserted = $this->insertToGroupUseWithAlias($tokens, $insertIndex + 1, $useDeclaration) + 1; + $insertedTokens += $inserted; + $insertIndex += $inserted; + } + + $tokens->insertAt($insertIndex, new Token([T_STRING, $useDeclaration->getShortName()])); + + return ++$insertedTokens; + } + + /** + * Check if namespace use analyses are different. + */ + private function areDeclarationsDifferent(?NamespaceUseAnalysis $analysis1, ?NamespaceUseAnalysis $analysis2): bool + { + if (null === $analysis1 || null === $analysis2) { + return true; + } + + $namespaceName1 = $this->getNamespaceNameWithSlash($analysis1); + $namespaceName2 = $this->getNamespaceNameWithSlash($analysis2); + + return $namespaceName1 !== $namespaceName2 || $analysis1->getType() !== $analysis2->getType(); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoLeadingImportSlashFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoLeadingImportSlashFixer.php new file mode 100644 index 00000000..b9120518 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoLeadingImportSlashFixer.php @@ -0,0 +1,90 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Carlos Cirello + */ +final class NoLeadingImportSlashFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Remove leading slashes in `use` clauses.', + [new CodeSample("isTokenKindFound(T_USE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $usesIndices = $tokensAnalyzer->getImportUseIndexes(); + + foreach ($usesIndices as $idx) { + $nextTokenIdx = $tokens->getNextMeaningfulToken($idx); + $nextToken = $tokens[$nextTokenIdx]; + + if ($nextToken->isGivenKind(T_NS_SEPARATOR)) { + $this->removeLeadingImportSlash($tokens, $nextTokenIdx); + } elseif ($nextToken->isGivenKind([CT::T_FUNCTION_IMPORT, CT::T_CONST_IMPORT])) { + $nextTokenIdx = $tokens->getNextMeaningfulToken($nextTokenIdx); + if ($tokens[$nextTokenIdx]->isGivenKind(T_NS_SEPARATOR)) { + $this->removeLeadingImportSlash($tokens, $nextTokenIdx); + } + } + } + } + + private function removeLeadingImportSlash(Tokens $tokens, int $index): void + { + $previousIndex = $tokens->getPrevNonWhitespace($index); + + if ( + $previousIndex < $index - 1 + || $tokens[$previousIndex]->isComment() + ) { + $tokens->clearAt($index); + + return; + } + + $tokens[$index] = new Token([T_WHITESPACE, ' ']); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnneededImportAliasFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnneededImportAliasFixer.php new file mode 100644 index 00000000..2d1532c9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnneededImportAliasFixer.php @@ -0,0 +1,88 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +final class NoUnneededImportAliasFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Imports should not be aliased as the same name.', + [new CodeSample("isAllTokenKindsFound([T_USE, T_AS]); + } + + /** + * {@inheritdoc} + * + * Must run before NoSinglelineWhitespaceBeforeSemicolonsFixer. + */ + public function getPriority(): int + { + return 1; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; 0 <= $index; --$index) { + if (!$tokens[$index]->isGivenKind(T_AS)) { + continue; + } + + $aliasIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$aliasIndex]->isGivenKind(T_STRING)) { + continue; + } + + $importIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$importIndex]->isGivenKind(T_STRING)) { + continue; + } + + if ($tokens[$importIndex]->getContent() !== $tokens[$aliasIndex]->getContent()) { + continue; + } + + do { + $importIndex = $tokens->getPrevMeaningfulToken($importIndex); + } while ($tokens[$importIndex]->isGivenKind([T_NS_SEPARATOR, T_STRING, T_AS]) || $tokens[$importIndex]->equals(',')); + + if ($tokens[$importIndex]->isGivenKind([CT::T_FUNCTION_IMPORT, CT::T_CONST_IMPORT])) { + $importIndex = $tokens->getPrevMeaningfulToken($importIndex); + } + + if (!$tokens[$importIndex]->isGivenKind([T_USE, CT::T_GROUP_IMPORT_BRACE_OPEN])) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($aliasIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnusedImportsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnusedImportsFixer.php new file mode 100644 index 00000000..898865d9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnusedImportsFixer.php @@ -0,0 +1,290 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Dariusz Rumiński + */ +final class NoUnusedImportsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Unused `use` statements must be removed.', + [new CodeSample("isTokenKindFound(T_USE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens); + + if (0 === \count($useDeclarations)) { + return; + } + + foreach ($tokens->getNamespaceDeclarations() as $namespace) { + $currentNamespaceUseDeclarations = []; + $currentNamespaceUseDeclarationIndices = []; + + foreach ($useDeclarations as $useDeclaration) { + if ($useDeclaration->getStartIndex() >= $namespace->getScopeStartIndex() && $useDeclaration->getEndIndex() <= $namespace->getScopeEndIndex()) { + $currentNamespaceUseDeclarations[] = $useDeclaration; + $currentNamespaceUseDeclarationIndices[$useDeclaration->getStartIndex()] = $useDeclaration->getEndIndex(); + } + } + + foreach ($currentNamespaceUseDeclarations as $useDeclaration) { + if (!$this->isImportUsed($tokens, $namespace, $useDeclaration, $currentNamespaceUseDeclarationIndices)) { + $this->removeUseDeclaration($tokens, $useDeclaration); + } + } + + $this->removeUsesInSameNamespace($tokens, $currentNamespaceUseDeclarations, $namespace); + } + } + + /** + * @param array $ignoredIndices indices of the use statements themselves that should not be checked as being "used" + */ + private function isImportUsed(Tokens $tokens, NamespaceAnalysis $namespace, NamespaceUseAnalysis $import, array $ignoredIndices): bool + { + $analyzer = new TokensAnalyzer($tokens); + $gotoLabelAnalyzer = new GotoLabelAnalyzer(); + + $tokensNotBeforeFunctionCall = [T_NEW]; + + $attributeIsDefined = \defined('T_ATTRIBUTE'); + + if ($attributeIsDefined) { // @TODO: drop condition when PHP 8.0+ is required + $tokensNotBeforeFunctionCall[] = T_ATTRIBUTE; + } + + $namespaceEndIndex = $namespace->getScopeEndIndex(); + $inAttribute = false; + + for ($index = $namespace->getScopeStartIndex(); $index <= $namespaceEndIndex; ++$index) { + $token = $tokens[$index]; + + if ($attributeIsDefined && $token->isGivenKind(T_ATTRIBUTE)) { + $inAttribute = true; + + continue; + } + + if ($attributeIsDefined && $token->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $inAttribute = false; + + continue; + } + + if (isset($ignoredIndices[$index])) { + $index = $ignoredIndices[$index]; + + continue; + } + + if ($token->isGivenKind(T_STRING)) { + if (0 !== strcasecmp($import->getShortName(), $token->getContent())) { + continue; + } + + $prevMeaningfulToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + + if ($prevMeaningfulToken->isGivenKind(T_NAMESPACE)) { + $index = $tokens->getNextTokenOfKind($index, [';', '{', [T_CLOSE_TAG]]); + + continue; + } + + if ( + $prevMeaningfulToken->isGivenKind([T_NS_SEPARATOR, T_FUNCTION, T_CONST, T_DOUBLE_COLON]) + || $prevMeaningfulToken->isObjectOperator() + ) { + continue; + } + + if ($inAttribute) { + return true; + } + + $nextMeaningfulIndex = $tokens->getNextMeaningfulToken($index); + + if ($gotoLabelAnalyzer->belongsToGoToLabel($tokens, $nextMeaningfulIndex)) { + continue; + } + + $nextMeaningfulToken = $tokens[$nextMeaningfulIndex]; + + if ($analyzer->isConstantInvocation($index)) { + $type = NamespaceUseAnalysis::TYPE_CONSTANT; + } elseif ($nextMeaningfulToken->equals('(') && !$prevMeaningfulToken->isGivenKind($tokensNotBeforeFunctionCall)) { + $type = NamespaceUseAnalysis::TYPE_FUNCTION; + } else { + $type = NamespaceUseAnalysis::TYPE_CLASS; + } + + if ($import->getType() === $type) { + return true; + } + + continue; + } + + if ($token->isComment() + && Preg::match( + '/(?getShortName().'(?![[:alnum:]])/i', + $token->getContent() + ) + ) { + return true; + } + } + + return false; + } + + private function removeUseDeclaration(Tokens $tokens, NamespaceUseAnalysis $useDeclaration): void + { + for ($index = $useDeclaration->getEndIndex() - 1; $index >= $useDeclaration->getStartIndex(); --$index) { + if ($tokens[$index]->isComment()) { + continue; + } + + if (!$tokens[$index]->isWhitespace() || !str_contains($tokens[$index]->getContent(), "\n")) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + continue; + } + + // when multi line white space keep the line feed if the previous token is a comment + $prevIndex = $tokens->getPrevNonWhitespace($index); + + if ($tokens[$prevIndex]->isComment()) { + $content = $tokens[$index]->getContent(); + $tokens[$index] = new Token([T_WHITESPACE, substr($content, strrpos($content, "\n"))]); // preserve indent only + } else { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + + if ($tokens[$useDeclaration->getEndIndex()]->equals(';')) { // do not remove `? >` + $tokens->clearAt($useDeclaration->getEndIndex()); + } + + // remove white space above and below where the `use` statement was + + $prevIndex = $useDeclaration->getStartIndex() - 1; + $prevToken = $tokens[$prevIndex]; + + if ($prevToken->isWhitespace()) { + $content = rtrim($prevToken->getContent(), " \t"); + + $tokens->ensureWhitespaceAtIndex($prevIndex, 0, $content); + + $prevToken = $tokens[$prevIndex]; + } + + if (!isset($tokens[$useDeclaration->getEndIndex() + 1])) { + return; + } + + $nextIndex = $tokens->getNonEmptySibling($useDeclaration->getEndIndex(), 1); + + if (null === $nextIndex) { + return; + } + + $nextToken = $tokens[$nextIndex]; + + if ($nextToken->isWhitespace()) { + $content = Preg::replace( + "#^\r\n|^\n#", + '', + ltrim($nextToken->getContent(), " \t"), + 1 + ); + + $tokens->ensureWhitespaceAtIndex($nextIndex, 0, $content); + + $nextToken = $tokens[$nextIndex]; + } + + if ($prevToken->isWhitespace() && $nextToken->isWhitespace()) { + $content = $prevToken->getContent().$nextToken->getContent(); + + $tokens->ensureWhitespaceAtIndex($nextIndex, 0, $content); + + $tokens->clearAt($prevIndex); + } + } + + /** + * @param list $useDeclarations + */ + private function removeUsesInSameNamespace(Tokens $tokens, array $useDeclarations, NamespaceAnalysis $namespaceDeclaration): void + { + $namespace = $namespaceDeclaration->getFullName(); + $nsLength = \strlen($namespace.'\\'); + + foreach ($useDeclarations as $useDeclaration) { + if ($useDeclaration->isAliased()) { + continue; + } + + $useDeclarationFullName = ltrim($useDeclaration->getFullName(), '\\'); + + if (!str_starts_with($useDeclarationFullName, $namespace.'\\')) { + continue; + } + + $partName = substr($useDeclarationFullName, $nsLength); + + if (!str_contains($partName, '\\')) { + $this->removeUseDeclaration($tokens, $useDeclaration); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/OrderedImportsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/OrderedImportsFixer.php new file mode 100644 index 00000000..40367746 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/OrderedImportsFixer.php @@ -0,0 +1,601 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @author Sebastiaan Stok + * @author Dariusz Rumiński + * @author Darius Matulionis + * @author Adriano Pilger + */ +final class OrderedImportsFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @internal + */ + public const IMPORT_TYPE_CLASS = 'class'; + + /** + * @internal + */ + public const IMPORT_TYPE_CONST = 'const'; + + /** + * @internal + */ + public const IMPORT_TYPE_FUNCTION = 'function'; + + /** + * @internal + */ + public const SORT_ALPHA = 'alpha'; + + /** + * @internal + */ + public const SORT_LENGTH = 'length'; + + /** + * @internal + */ + public const SORT_NONE = 'none'; + + /** + * Array of supported sort types in configuration. + * + * @var string[] + */ + private const SUPPORTED_SORT_TYPES = [self::IMPORT_TYPE_CLASS, self::IMPORT_TYPE_CONST, self::IMPORT_TYPE_FUNCTION]; + + /** + * Array of supported sort algorithms in configuration. + * + * @var string[] + */ + private const SUPPORTED_SORT_ALGORITHMS = [self::SORT_ALPHA, self::SORT_LENGTH, self::SORT_NONE]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Ordering `use` statements.', + [ + new CodeSample( + " true] + ), + new CodeSample( + ' self::SORT_LENGTH] + ), + new CodeSample( + ' self::SORT_LENGTH, + 'imports_order' => [ + self::IMPORT_TYPE_CONST, + self::IMPORT_TYPE_CLASS, + self::IMPORT_TYPE_FUNCTION, + ], + ] + ), + new CodeSample( + ' self::SORT_ALPHA, + 'imports_order' => [ + self::IMPORT_TYPE_CONST, + self::IMPORT_TYPE_CLASS, + self::IMPORT_TYPE_FUNCTION, + ], + ] + ), + new CodeSample( + ' self::SORT_NONE, + 'imports_order' => [ + self::IMPORT_TYPE_CONST, + self::IMPORT_TYPE_CLASS, + self::IMPORT_TYPE_FUNCTION, + ], + ] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before BlankLineBetweenImportGroupsFixer. + * Must run after GlobalNamespaceImportFixer, NoLeadingImportSlashFixer. + */ + public function getPriority(): int + { + return -30; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_USE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $namespacesImports = $tokensAnalyzer->getImportUseIndexes(true); + + foreach (array_reverse($namespacesImports) as $usesPerNamespaceIndices) { + $count = \count($usesPerNamespaceIndices); + + if (0 === $count) { + continue; // nothing to sort + } + + if (1 === $count) { + $this->setNewOrder($tokens, $this->getNewOrder($usesPerNamespaceIndices, $tokens)); + + continue; + } + + $groupUsesOffset = 0; + $groupUses = [$groupUsesOffset => [$usesPerNamespaceIndices[0]]]; + + // if there's some logic between two `use` statements, sort only imports grouped before that logic + for ($index = 0; $index < $count - 1; ++$index) { + $nextGroupUse = $tokens->getNextTokenOfKind($usesPerNamespaceIndices[$index], [';', [T_CLOSE_TAG]]); + + if ($tokens[$nextGroupUse]->isGivenKind(T_CLOSE_TAG)) { + $nextGroupUse = $tokens->getNextTokenOfKind($usesPerNamespaceIndices[$index], [[T_OPEN_TAG]]); + } + + $nextGroupUse = $tokens->getNextMeaningfulToken($nextGroupUse); + + if ($nextGroupUse !== $usesPerNamespaceIndices[$index + 1]) { + $groupUses[++$groupUsesOffset] = []; + } + + $groupUses[$groupUsesOffset][] = $usesPerNamespaceIndices[$index + 1]; + } + + for ($index = $groupUsesOffset; $index >= 0; --$index) { + $this->setNewOrder($tokens, $this->getNewOrder($groupUses[$index], $tokens)); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $supportedSortTypes = self::SUPPORTED_SORT_TYPES; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('sort_algorithm', 'Whether the statements should be sorted alphabetically or by length, or not sorted.')) + ->setAllowedValues(self::SUPPORTED_SORT_ALGORITHMS) + ->setDefault(self::SORT_ALPHA) + ->getOption(), + (new FixerOptionBuilder('imports_order', 'Defines the order of import types.')) + ->setAllowedTypes(['array', 'null']) + ->setAllowedValues([static function (?array $value) use ($supportedSortTypes): bool { + if (null !== $value) { + $missing = array_diff($supportedSortTypes, $value); + if (\count($missing) > 0) { + throw new InvalidOptionsException(sprintf( + 'Missing sort %s %s.', + 1 === \count($missing) ? 'type' : 'types', + Utils::naturalLanguageJoin($missing) + )); + } + + $unknown = array_diff($value, $supportedSortTypes); + if (\count($unknown) > 0) { + throw new InvalidOptionsException(sprintf( + 'Unknown sort %s %s.', + 1 === \count($unknown) ? 'type' : 'types', + Utils::naturalLanguageJoin($unknown) + )); + } + } + + return true; + }]) + ->setDefault(null) // @TODO set to ['class', 'function', 'const'] on 4.0 + ->getOption(), + (new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * This method is used for sorting the uses in a namespace. + * + * @param array $first + * @param array $second + * + * @internal + */ + private function sortAlphabetically(array $first, array $second): int + { + // Replace backslashes by spaces before sorting for correct sort order + $firstNamespace = str_replace('\\', ' ', $this->prepareNamespace($first['namespace'])); + $secondNamespace = str_replace('\\', ' ', $this->prepareNamespace($second['namespace'])); + + return true === $this->configuration['case_sensitive'] + ? $firstNamespace <=> $secondNamespace + : strcasecmp($firstNamespace, $secondNamespace); + } + + /** + * This method is used for sorting the uses statements in a namespace by length. + * + * @param array $first + * @param array $second + * + * @internal + */ + private function sortByLength(array $first, array $second): int + { + $firstNamespace = (self::IMPORT_TYPE_CLASS === $first['importType'] ? '' : $first['importType'].' ').$this->prepareNamespace($first['namespace']); + $secondNamespace = (self::IMPORT_TYPE_CLASS === $second['importType'] ? '' : $second['importType'].' ').$this->prepareNamespace($second['namespace']); + + $firstNamespaceLength = \strlen($firstNamespace); + $secondNamespaceLength = \strlen($secondNamespace); + + if ($firstNamespaceLength === $secondNamespaceLength) { + $sortResult = true === $this->configuration['case_sensitive'] + ? $firstNamespace <=> $secondNamespace + : strcasecmp($firstNamespace, $secondNamespace); + } else { + $sortResult = $firstNamespaceLength > $secondNamespaceLength ? 1 : -1; + } + + return $sortResult; + } + + private function prepareNamespace(string $namespace): string + { + return trim(Preg::replace('%/\*(.*)\*/%s', '', $namespace)); + } + + /** + * @param list $uses + */ + private function getNewOrder(array $uses, Tokens $tokens): array + { + $indices = []; + $originalIndices = []; + $lineEnding = $this->whitespacesConfig->getLineEnding(); + $usesCount = \count($uses); + + for ($i = 0; $i < $usesCount; ++$i) { + $index = $uses[$i]; + + $startIndex = $tokens->getTokenNotOfKindsSibling($index + 1, 1, [T_WHITESPACE]); + $endIndex = $tokens->getNextTokenOfKind($startIndex, [';', [T_CLOSE_TAG]]); + $previous = $tokens->getPrevMeaningfulToken($endIndex); + + $group = $tokens[$previous]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE); + if ($tokens[$startIndex]->isGivenKind(CT::T_CONST_IMPORT)) { + $type = self::IMPORT_TYPE_CONST; + $index = $tokens->getNextNonWhitespace($startIndex); + } elseif ($tokens[$startIndex]->isGivenKind(CT::T_FUNCTION_IMPORT)) { + $type = self::IMPORT_TYPE_FUNCTION; + $index = $tokens->getNextNonWhitespace($startIndex); + } else { + $type = self::IMPORT_TYPE_CLASS; + $index = $startIndex; + } + + $namespaceTokens = []; + + while ($index <= $endIndex) { + $token = $tokens[$index]; + + if ($index === $endIndex || (!$group && $token->equals(','))) { + if ($group && self::SORT_NONE !== $this->configuration['sort_algorithm']) { + // if group import, sort the items within the group definition + + // figure out where the list of namespace parts within the group def. starts + $namespaceTokensCount = \count($namespaceTokens) - 1; + $namespace = ''; + for ($k = 0; $k < $namespaceTokensCount; ++$k) { + if ($namespaceTokens[$k]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + $namespace .= '{'; + + break; + } + + $namespace .= $namespaceTokens[$k]->getContent(); + } + + // fetch all parts, split up in an array of strings, move comments to the end + $parts = []; + $firstIndent = ''; + $separator = ', '; + $lastIndent = ''; + $hasGroupTrailingComma = false; + + for ($k1 = $k + 1; $k1 < $namespaceTokensCount; ++$k1) { + $comment = ''; + $namespacePart = ''; + for ($k2 = $k1;; ++$k2) { + if ($namespaceTokens[$k2]->equalsAny([',', [CT::T_GROUP_IMPORT_BRACE_CLOSE]])) { + break; + } + + if ($namespaceTokens[$k2]->isComment()) { + $comment .= $namespaceTokens[$k2]->getContent(); + + continue; + } + + // if there is any line ending inside the group import, it should be indented properly + if ( + '' === $firstIndent + && $namespaceTokens[$k2]->isWhitespace() + && str_contains($namespaceTokens[$k2]->getContent(), $lineEnding) + ) { + $lastIndent = $lineEnding; + $firstIndent = $lineEnding.$this->whitespacesConfig->getIndent(); + $separator = ','.$firstIndent; + } + + $namespacePart .= $namespaceTokens[$k2]->getContent(); + } + + $namespacePart = trim($namespacePart); + if ('' === $namespacePart) { + $hasGroupTrailingComma = true; + + continue; + } + + $comment = trim($comment); + if ('' !== $comment) { + $namespacePart .= ' '.$comment; + } + + $parts[] = $namespacePart; + + $k1 = $k2; + } + + $sortedParts = $parts; + sort($parts); + + // check if the order needs to be updated, otherwise don't touch as we might change valid CS (to other valid CS). + if ($sortedParts === $parts) { + $namespace = Tokens::fromArray($namespaceTokens)->generateCode(); + } else { + $namespace .= $firstIndent.implode($separator, $parts).($hasGroupTrailingComma ? ',' : '').$lastIndent.'}'; + } + } else { + $namespace = Tokens::fromArray($namespaceTokens)->generateCode(); + } + + $indices[$startIndex] = [ + 'namespace' => $namespace, + 'startIndex' => $startIndex, + 'endIndex' => $index - 1, + 'importType' => $type, + 'group' => $group, + ]; + + $originalIndices[] = $startIndex; + + if ($index === $endIndex) { + break; + } + + $namespaceTokens = []; + $nextPartIndex = $tokens->getTokenNotOfKindSibling($index, 1, [',', [T_WHITESPACE]]); + $startIndex = $nextPartIndex; + $index = $nextPartIndex; + + continue; + } + + $namespaceTokens[] = $token; + ++$index; + } + } + + // Is sort types provided, sorting by groups and each group by algorithm + if (null !== $this->configuration['imports_order']) { + // Grouping indices by import type. + $groupedByTypes = []; + + foreach ($indices as $startIndex => $item) { + $groupedByTypes[$item['importType']][$startIndex] = $item; + } + + // Sorting each group by algorithm. + foreach ($groupedByTypes as $type => $groupIndices) { + $groupedByTypes[$type] = $this->sortByAlgorithm($groupIndices); + } + + // Ordering groups + $sortedGroups = []; + + foreach ($this->configuration['imports_order'] as $type) { + if (isset($groupedByTypes[$type]) && [] !== $groupedByTypes[$type]) { + foreach ($groupedByTypes[$type] as $startIndex => $item) { + $sortedGroups[$startIndex] = $item; + } + } + } + + $indices = $sortedGroups; + } else { + // Sorting only by algorithm + $indices = $this->sortByAlgorithm($indices); + } + + $index = -1; + $usesOrder = []; + + // Loop through the index but use original index order + foreach ($indices as $v) { + $usesOrder[$originalIndices[++$index]] = $v; + } + + return $usesOrder; + } + + /** + * @param array< + * int, + * array{ + * namespace: string, + * startIndex: int, + * endIndex: int, + * importType: string, + * group: bool, + * } + * > $indices + * + * @return array< + * int, + * array{ + * namespace: string, + * startIndex: int, + * endIndex: int, + * importType: string, + * group: bool, + * } + * > + */ + private function sortByAlgorithm(array $indices): array + { + if (self::SORT_ALPHA === $this->configuration['sort_algorithm']) { + uasort($indices, [$this, 'sortAlphabetically']); + } elseif (self::SORT_LENGTH === $this->configuration['sort_algorithm']) { + uasort($indices, [$this, 'sortByLength']); + } + + return $indices; + } + + /** + * @param array $usesOrder + */ + private function setNewOrder(Tokens $tokens, array $usesOrder): void + { + $mapStartToEnd = []; + + foreach ($usesOrder as $use) { + $mapStartToEnd[$use['startIndex']] = $use['endIndex']; + } + + // Now insert the new tokens, starting from the end + foreach (array_reverse($usesOrder, true) as $index => $use) { + $code = sprintf( + 'getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->equals(',')) { + $numberOfInitialTokensToClear = 5; // clear `clearRange(0, $numberOfInitialTokensToClear - 1); + $declarationTokens->clearAt(\count($declarationTokens) - 1); // clear `;` + $declarationTokens->clearEmptyTokens(); + + $tokens->overrideRange($index, $mapStartToEnd[$index], $declarationTokens); + + if ($use['group']) { + // a group import must start with `use` and cannot be part of comma separated import list + $prev = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prev]->equals(',')) { + $tokens[$prev] = new Token(';'); + $tokens->insertAt($prev + 1, new Token([T_USE, 'use'])); + + if (!$tokens[$prev + 2]->isWhitespace()) { + $tokens->insertAt($prev + 2, new Token([T_WHITESPACE, ' '])); + } + } + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleImportPerStatementFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleImportPerStatementFixer.php new file mode 100644 index 00000000..2ced868c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleImportPerStatementFixer.php @@ -0,0 +1,262 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * Fixer for rules defined in PSR2 ¶3. + * + * @author Dariusz Rumiński + */ +final class SingleImportPerStatementFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There MUST be one use keyword per declaration.', + [ + new CodeSample( + ' true] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before MultilineWhitespaceBeforeSemicolonsFixer, NoLeadingImportSlashFixer, NoSinglelineWhitespaceBeforeSemicolonsFixer, NoUnusedImportsFixer, SpaceAfterSemicolonFixer. + */ + public function getPriority(): int + { + return 1; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_USE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + foreach (array_reverse($tokensAnalyzer->getImportUseIndexes()) as $index) { + $endIndex = $tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]); + $groupClose = $tokens->getPrevMeaningfulToken($endIndex); + + if ($tokens[$groupClose]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) { + if ($this->configuration['group_to_single_imports']) { + $this->fixGroupUse($tokens, $index, $endIndex); + } + } else { + $this->fixMultipleUse($tokens, $index, $endIndex); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('group_to_single_imports', 'Whether to change group imports into single imports.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + private function getGroupDeclaration(Tokens $tokens, int $index): array + { + $groupPrefix = ''; + $comment = ''; + $groupOpenIndex = null; + + for ($i = $index + 1;; ++$i) { + if ($tokens[$i]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + $groupOpenIndex = $i; + + break; + } + + if ($tokens[$i]->isComment()) { + $comment .= $tokens[$i]->getContent(); + if (!$tokens[$i - 1]->isWhitespace() && !$tokens[$i + 1]->isWhitespace()) { + $groupPrefix .= ' '; + } + + continue; + } + + if ($tokens[$i]->isWhitespace()) { + $groupPrefix .= ' '; + + continue; + } + + $groupPrefix .= $tokens[$i]->getContent(); + } + + return [ + rtrim($groupPrefix), + $groupOpenIndex, + $tokens->findBlockEnd(Tokens::BLOCK_TYPE_GROUP_IMPORT_BRACE, $groupOpenIndex), + $comment, + ]; + } + + /** + * @return string[] + */ + private function getGroupStatements(Tokens $tokens, string $groupPrefix, int $groupOpenIndex, int $groupCloseIndex, string $comment): array + { + $statements = []; + $statement = $groupPrefix; + + for ($i = $groupOpenIndex + 1; $i <= $groupCloseIndex; ++$i) { + $token = $tokens[$i]; + + if ($token->equals(',') && $tokens[$tokens->getNextMeaningfulToken($i)]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) { + continue; + } + + if ($token->equalsAny([',', [CT::T_GROUP_IMPORT_BRACE_CLOSE]])) { + $statements[] = 'use'.$statement.';'; + $statement = $groupPrefix; + + continue; + } + + if ($token->isWhitespace()) { + $j = $tokens->getNextMeaningfulToken($i); + + if ($tokens[$j]->isGivenKind(T_AS)) { + $statement .= ' as '; + $i += 2; + } elseif ($tokens[$j]->isGivenKind(CT::T_FUNCTION_IMPORT)) { + $statement = ' function'.$statement; + $i += 2; + } elseif ($tokens[$j]->isGivenKind(CT::T_CONST_IMPORT)) { + $statement = ' const'.$statement; + $i += 2; + } + + if ($token->isWhitespace(" \t") || !str_starts_with($tokens[$i - 1]->getContent(), '//')) { + continue; + } + } + + $statement .= $token->getContent(); + } + + if ('' !== $comment) { + $statements[0] .= ' '.$comment; + } + + return $statements; + } + + private function fixGroupUse(Tokens $tokens, int $index, int $endIndex): void + { + [$groupPrefix, $groupOpenIndex, $groupCloseIndex, $comment] = $this->getGroupDeclaration($tokens, $index); + $statements = $this->getGroupStatements($tokens, $groupPrefix, $groupOpenIndex, $groupCloseIndex, $comment); + + if (\count($statements) < 2) { + return; + } + + $tokens->clearRange($index, $groupCloseIndex); + if ($tokens[$endIndex]->equals(';')) { + $tokens->clearAt($endIndex); + } + + $ending = $this->whitespacesConfig->getLineEnding(); + $importTokens = Tokens::fromCode('clearAt(0); + $importTokens->clearEmptyTokens(); + + $tokens->insertAt($index, $importTokens); + } + + private function fixMultipleUse(Tokens $tokens, int $index, int $endIndex): void + { + $nextTokenIndex = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$nextTokenIndex]->isGivenKind(CT::T_FUNCTION_IMPORT)) { + $leadingTokens = [ + new Token([CT::T_FUNCTION_IMPORT, 'function']), + new Token([T_WHITESPACE, ' ']), + ]; + } elseif ($tokens[$nextTokenIndex]->isGivenKind(CT::T_CONST_IMPORT)) { + $leadingTokens = [ + new Token([CT::T_CONST_IMPORT, 'const']), + new Token([T_WHITESPACE, ' ']), + ]; + } else { + $leadingTokens = []; + } + + $ending = $this->whitespacesConfig->getLineEnding(); + + for ($i = $endIndex - 1; $i > $index; --$i) { + if (!$tokens[$i]->equals(',')) { + continue; + } + + $tokens[$i] = new Token(';'); + $i = $tokens->getNextMeaningfulToken($i); + + $tokens->insertAt($i, new Token([T_USE, 'use'])); + $tokens->insertAt($i + 1, new Token([T_WHITESPACE, ' '])); + + foreach ($leadingTokens as $offset => $leadingToken) { + $tokens->insertAt($i + 2 + $offset, clone $leadingTokens[$offset]); + } + + $indent = WhitespacesAnalyzer::detectIndent($tokens, $index); + + if ($tokens[$i - 1]->isWhitespace()) { + $tokens[$i - 1] = new Token([T_WHITESPACE, $ending.$indent]); + } elseif (!str_contains($tokens[$i - 1]->getContent(), "\n")) { + $tokens->insertAt($i, new Token([T_WHITESPACE, $ending.$indent])); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleLineAfterImportsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleLineAfterImportsFixer.php new file mode 100644 index 00000000..b8b97797 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleLineAfterImportsFixer.php @@ -0,0 +1,152 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; + +/** + * Fixer for rules defined in PSR2 ¶3. + * + * @author Ceeram + * @author Graham Campbell + */ +final class SingleLineAfterImportsFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_USE); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Each namespace use MUST go on its own line and there MUST be one blank line after the use statements block.', + [ + new CodeSample( + 'whitespacesConfig->getLineEnding(); + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $added = 0; + foreach ($tokensAnalyzer->getImportUseIndexes() as $index) { + $index += $added; + $indent = ''; + + // if previous line ends with comment and current line starts with whitespace, use current indent + if ($tokens[$index - 1]->isWhitespace(" \t") && $tokens[$index - 2]->isGivenKind(T_COMMENT)) { + $indent = $tokens[$index - 1]->getContent(); + } elseif ($tokens[$index - 1]->isWhitespace()) { + $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$index - 1]); + } + + $semicolonIndex = $tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]); // Handle insert index for inline T_COMMENT with whitespace after semicolon + $insertIndex = $semicolonIndex; + + if ($tokens[$semicolonIndex]->isGivenKind(T_CLOSE_TAG)) { + if ($tokens[$insertIndex - 1]->isWhitespace()) { + --$insertIndex; + } + + $tokens->insertAt($insertIndex, new Token(';')); + ++$added; + } + + if ($semicolonIndex === \count($tokens) - 1) { + $tokens->insertAt($insertIndex + 1, new Token([T_WHITESPACE, $ending.$ending.$indent])); + ++$added; + } else { + $newline = $ending; + $tokens[$semicolonIndex]->isGivenKind(T_CLOSE_TAG) ? --$insertIndex : ++$insertIndex; + if ($tokens[$insertIndex]->isWhitespace(" \t") && $tokens[$insertIndex + 1]->isComment()) { + ++$insertIndex; + } + + // Increment insert index for inline T_COMMENT or T_DOC_COMMENT + if ($tokens[$insertIndex]->isComment()) { + ++$insertIndex; + } + + $afterSemicolon = $tokens->getNextMeaningfulToken($semicolonIndex); + if (null === $afterSemicolon || !$tokens[$afterSemicolon]->isGivenKind(T_USE)) { + $newline .= $ending; + } + + if ($tokens[$insertIndex]->isWhitespace()) { + $nextToken = $tokens[$insertIndex]; + if (2 === substr_count($nextToken->getContent(), "\n")) { + continue; + } + $nextMeaningfulAfterUseIndex = $tokens->getNextMeaningfulToken($insertIndex); + if (null !== $nextMeaningfulAfterUseIndex && $tokens[$nextMeaningfulAfterUseIndex]->isGivenKind(T_USE)) { + if (substr_count($nextToken->getContent(), "\n") < 1) { + $tokens[$insertIndex] = new Token([T_WHITESPACE, $newline.$indent.ltrim($nextToken->getContent())]); + } + } else { + $tokens[$insertIndex] = new Token([T_WHITESPACE, $newline.$indent.ltrim($nextToken->getContent())]); + } + } else { + $tokens->insertAt($insertIndex, new Token([T_WHITESPACE, $newline.$indent])); + ++$added; + } + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Indentation.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Indentation.php new file mode 100644 index 00000000..0e370f20 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Indentation.php @@ -0,0 +1,92 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + */ +trait Indentation +{ + private function getLineIndentation(Tokens $tokens, int $index): string + { + $newlineTokenIndex = $this->getPreviousNewlineTokenIndex($tokens, $index); + + if (null === $newlineTokenIndex) { + return ''; + } + + return $this->extractIndent($this->computeNewLineContent($tokens, $newlineTokenIndex)); + } + + private function extractIndent(string $content): string + { + if (Preg::match('/\R(\h*)[^\r\n]*$/D', $content, $matches)) { + return $matches[1]; + } + + return ''; + } + + private function getPreviousNewlineTokenIndex(Tokens $tokens, int $index): ?int + { + while ($index > 0) { + $index = $tokens->getPrevTokenOfKind($index, [[T_WHITESPACE], [T_INLINE_HTML]]); + + if (null === $index) { + break; + } + + if ($this->isNewLineToken($tokens, $index)) { + return $index; + } + } + + return null; + } + + private function computeNewLineContent(Tokens $tokens, int $index): string + { + $content = $tokens[$index]->getContent(); + + if (0 !== $index && $tokens[$index - 1]->equalsAny([[T_OPEN_TAG], [T_CLOSE_TAG]])) { + $content = Preg::replace('/\S/', '', $tokens[$index - 1]->getContent()).$content; + } + + return $content; + } + + private function isNewLineToken(Tokens $tokens, int $index): bool + { + $token = $tokens[$index]; + + if ( + $token->isGivenKind(T_OPEN_TAG) + && isset($tokens[$index + 1]) + && !$tokens[$index + 1]->isWhitespace() + && Preg::match('/\R/', $token->getContent()) + ) { + return true; + } + + if (!$tokens[$index]->isGivenKind([T_WHITESPACE, T_INLINE_HTML])) { + return false; + } + + return Preg::match('/\R/', $this->computeNewLineContent($tokens, $index)); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.php new file mode 100644 index 00000000..2c976703 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.php @@ -0,0 +1,234 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @deprecated + * + * @author Sullivan Senechal + */ +final class ClassKeywordRemoveFixer extends AbstractFixer implements DeprecatedFixerInterface +{ + /** + * @var string[] + */ + private array $imports = []; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts `::class` keywords to FQCN strings.', + [ + new CodeSample( + 'isTokenKindFound(CT::T_CLASS_CONSTANT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $previousNamespaceScopeEndIndex = 0; + foreach ($tokens->getNamespaceDeclarations() as $declaration) { + $this->replaceClassKeywordsSection($tokens, '', $previousNamespaceScopeEndIndex, $declaration->getStartIndex()); + $this->replaceClassKeywordsSection($tokens, $declaration->getFullName(), $declaration->getStartIndex(), $declaration->getScopeEndIndex()); + $previousNamespaceScopeEndIndex = $declaration->getScopeEndIndex(); + } + + $this->replaceClassKeywordsSection($tokens, '', $previousNamespaceScopeEndIndex, $tokens->count() - 1); + } + + private function storeImports(Tokens $tokens, int $startIndex, int $endIndex): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $this->imports = []; + + /** @var int $index */ + foreach ($tokensAnalyzer->getImportUseIndexes() as $index) { + if ($index < $startIndex || $index > $endIndex) { + continue; + } + + $import = ''; + while ($index = $tokens->getNextMeaningfulToken($index)) { + if ($tokens[$index]->equalsAny([';', [CT::T_GROUP_IMPORT_BRACE_OPEN]]) || $tokens[$index]->isGivenKind(T_AS)) { + break; + } + + $import .= $tokens[$index]->getContent(); + } + + // Imports group (PHP 7 spec) + if ($tokens[$index]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + $groupEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_GROUP_IMPORT_BRACE, $index); + $groupImports = array_map( + static fn (string $import): string => trim($import), + explode(',', $tokens->generatePartialCode($index + 1, $groupEndIndex - 1)) + ); + foreach ($groupImports as $groupImport) { + $groupImportParts = array_map(static fn (string $import): string => trim($import), explode(' as ', $groupImport)); + if (2 === \count($groupImportParts)) { + $this->imports[$groupImportParts[1]] = $import.$groupImportParts[0]; + } else { + $this->imports[] = $import.$groupImport; + } + } + } elseif ($tokens[$index]->isGivenKind(T_AS)) { + $aliasIndex = $tokens->getNextMeaningfulToken($index); + $alias = $tokens[$aliasIndex]->getContent(); + $this->imports[$alias] = $import; + } else { + $this->imports[] = $import; + } + } + } + + private function replaceClassKeywordsSection(Tokens $tokens, string $namespace, int $startIndex, int $endIndex): void + { + if ($endIndex - $startIndex < 3) { + return; + } + + $this->storeImports($tokens, $startIndex, $endIndex); + + $ctClassTokens = $tokens->findGivenKind(CT::T_CLASS_CONSTANT, $startIndex, $endIndex); + foreach (array_reverse(array_keys($ctClassTokens)) as $classIndex) { + $this->replaceClassKeyword($tokens, $namespace, $classIndex); + } + } + + private function replaceClassKeyword(Tokens $tokens, string $namespacePrefix, int $classIndex): void + { + $classEndIndex = $tokens->getPrevMeaningfulToken($classIndex); + $classEndIndex = $tokens->getPrevMeaningfulToken($classEndIndex); + + if (!$tokens[$classEndIndex]->isGivenKind(T_STRING)) { + return; + } + + if ($tokens[$classEndIndex]->equalsAny([[T_STRING, 'self'], [T_STATIC, 'static'], [T_STRING, 'parent']], false)) { + return; + } + + $classBeginIndex = $classEndIndex; + while (true) { + $prev = $tokens->getPrevMeaningfulToken($classBeginIndex); + if (!$tokens[$prev]->isGivenKind([T_NS_SEPARATOR, T_STRING])) { + break; + } + + $classBeginIndex = $prev; + } + + $classString = $tokens->generatePartialCode( + $tokens[$classBeginIndex]->isGivenKind(T_NS_SEPARATOR) + ? $tokens->getNextMeaningfulToken($classBeginIndex) + : $classBeginIndex, + $classEndIndex + ); + + $classImport = false; + if ($tokens[$classBeginIndex]->isGivenKind(T_NS_SEPARATOR)) { + $namespacePrefix = ''; + } else { + foreach ($this->imports as $alias => $import) { + if ($classString === $alias) { + $classImport = $import; + + break; + } + + $classStringArray = explode('\\', $classString); + $namespaceToTest = $classStringArray[0]; + + if (0 === ($namespaceToTest <=> substr($import, -\strlen($namespaceToTest)))) { + $classImport = $import; + + break; + } + } + } + + for ($i = $classBeginIndex; $i <= $classIndex; ++$i) { + if (!$tokens[$i]->isComment() && !($tokens[$i]->isWhitespace() && str_contains($tokens[$i]->getContent(), "\n"))) { + $tokens->clearAt($i); + } + } + + $tokens->insertAt($classBeginIndex, new Token([ + T_CONSTANT_ENCAPSED_STRING, + "'".$this->makeClassFQN($namespacePrefix, $classImport, $classString)."'", + ])); + } + + /** + * @param false|string $classImport + */ + private function makeClassFQN(string $namespacePrefix, $classImport, string $classString): string + { + if (false === $classImport) { + return ('' !== $namespacePrefix ? ($namespacePrefix.'\\') : '').$classString; + } + + $classStringArray = explode('\\', $classString); + $classStringLength = \count($classStringArray); + $classImportArray = explode('\\', $classImport); + $classImportLength = \count($classImportArray); + + if (1 === $classStringLength) { + return $classImport; + } + + return implode('\\', array_merge( + \array_slice($classImportArray, 0, $classImportLength - $classStringLength + 1), + $classStringArray + )); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php new file mode 100644 index 00000000..10e19180 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php @@ -0,0 +1,163 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class CombineConsecutiveIssetsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Using `isset($var) &&` multiple times should be done in one call.', + [new CodeSample("isAllTokenKindsFound([T_ISSET, T_BOOLEAN_AND]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokenCount = $tokens->count(); + + for ($index = 1; $index < $tokenCount; ++$index) { + if (!$tokens[$index]->isGivenKind(T_ISSET) + || !$tokens[$tokens->getPrevMeaningfulToken($index)]->equalsAny(['(', '{', ';', '=', [T_OPEN_TAG], [T_BOOLEAN_AND], [T_BOOLEAN_OR]])) { + continue; + } + + $issetInfo = $this->getIssetInfo($tokens, $index); + $issetCloseBraceIndex = end($issetInfo); // ')' token + $insertLocation = prev($issetInfo) + 1; // one index after the previous meaningful of ')' + + $booleanAndTokenIndex = $tokens->getNextMeaningfulToken($issetCloseBraceIndex); + + while ($tokens[$booleanAndTokenIndex]->isGivenKind(T_BOOLEAN_AND)) { + $issetIndex = $tokens->getNextMeaningfulToken($booleanAndTokenIndex); + if (!$tokens[$issetIndex]->isGivenKind(T_ISSET)) { + $index = $issetIndex; + + break; + } + + // fetch info about the 'isset' statement that we're merging + $nextIssetInfo = $this->getIssetInfo($tokens, $issetIndex); + + $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken(end($nextIssetInfo)); + $nextMeaningfulToken = $tokens[$nextMeaningfulTokenIndex]; + + if (!$nextMeaningfulToken->equalsAny([')', '}', ';', [T_CLOSE_TAG], [T_BOOLEAN_AND], [T_BOOLEAN_OR]])) { + $index = $nextMeaningfulTokenIndex; + + break; + } + + // clone what we want to move, do not clone '(' and ')' of the 'isset' statement we're merging + $clones = $this->getTokenClones($tokens, \array_slice($nextIssetInfo, 1, -1)); + + // clean up now the tokens of the 'isset' statement we're merging + $this->clearTokens($tokens, array_merge($nextIssetInfo, [$issetIndex, $booleanAndTokenIndex])); + + // insert the tokens to create the new statement + array_unshift($clones, new Token(','), new Token([T_WHITESPACE, ' '])); + $tokens->insertAt($insertLocation, $clones); + + // correct some counts and offset based on # of tokens inserted + $numberOfTokensInserted = \count($clones); + $tokenCount += $numberOfTokensInserted; + $issetCloseBraceIndex += $numberOfTokensInserted; + $insertLocation += $numberOfTokensInserted; + + $booleanAndTokenIndex = $tokens->getNextMeaningfulToken($issetCloseBraceIndex); + } + } + } + + /** + * @param int[] $indices + */ + private function clearTokens(Tokens $tokens, array $indices): void + { + foreach ($indices as $index) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + + /** + * @param int $index of T_ISSET + * + * @return int[] indices of meaningful tokens belonging to the isset statement + */ + private function getIssetInfo(Tokens $tokens, int $index): array + { + $openIndex = $tokens->getNextMeaningfulToken($index); + + $braceOpenCount = 1; + $meaningfulTokenIndices = [$openIndex]; + + for ($i = $openIndex + 1;; ++$i) { + if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { + continue; + } + + $meaningfulTokenIndices[] = $i; + + if ($tokens[$i]->equals(')')) { + --$braceOpenCount; + if (0 === $braceOpenCount) { + break; + } + } elseif ($tokens[$i]->equals('(')) { + ++$braceOpenCount; + } + } + + return $meaningfulTokenIndices; + } + + /** + * @param int[] $indices + * + * @return Token[] + */ + private function getTokenClones(Tokens $tokens, array $indices): array + { + $clones = []; + + foreach ($indices as $i) { + $clones[] = clone $tokens[$i]; + } + + return $clones; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php new file mode 100644 index 00000000..6ec6b753 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php @@ -0,0 +1,179 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class CombineConsecutiveUnsetsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Calling `unset` on multiple items should be done in one call.', + [new CodeSample("isTokenKindFound(T_UNSET); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (!$tokens[$index]->isGivenKind(T_UNSET)) { + continue; + } + + $previousUnsetCall = $this->getPreviousUnsetCall($tokens, $index); + if (\is_int($previousUnsetCall)) { + $index = $previousUnsetCall; + + continue; + } + + [$previousUnset, , $previousUnsetBraceEnd] = $previousUnsetCall; + + // Merge the tokens inside the 'unset' call into the previous one 'unset' call. + $tokensAddCount = $this->moveTokens( + $tokens, + $nextUnsetContentStart = $tokens->getNextTokenOfKind($index, ['(']), + $nextUnsetContentEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextUnsetContentStart), + $previousUnsetBraceEnd - 1 + ); + + if (!$tokens[$previousUnsetBraceEnd]->isWhitespace()) { + $tokens->insertAt($previousUnsetBraceEnd, new Token([T_WHITESPACE, ' '])); + ++$tokensAddCount; + } + + $tokens->insertAt($previousUnsetBraceEnd, new Token(',')); + ++$tokensAddCount; + + // Remove 'unset', '(', ')' and (possibly) ';' from the merged 'unset' call. + $this->clearOffsetTokens($tokens, $tokensAddCount, [$index, $nextUnsetContentStart, $nextUnsetContentEnd]); + + $nextUnsetSemicolon = $tokens->getNextMeaningfulToken($nextUnsetContentEnd); + if (null !== $nextUnsetSemicolon && $tokens[$nextUnsetSemicolon]->equals(';')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($nextUnsetSemicolon); + } + + $index = $previousUnset + 1; + } + } + + /** + * @param int[] $indices + */ + private function clearOffsetTokens(Tokens $tokens, int $offset, array $indices): void + { + foreach ($indices as $index) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index + $offset); + } + } + + /** + * Find a previous call to unset directly before the index. + * + * Returns an array with + * * unset index + * * opening brace index + * * closing brace index + * * end semicolon index + * + * Or the index to where the method looked for a call. + * + * @return int|int[] + */ + private function getPreviousUnsetCall(Tokens $tokens, int $index) + { + $previousUnsetSemicolon = $tokens->getPrevMeaningfulToken($index); + if (null === $previousUnsetSemicolon) { + return $index; + } + + if (!$tokens[$previousUnsetSemicolon]->equals(';')) { + return $previousUnsetSemicolon; + } + + $previousUnsetBraceEnd = $tokens->getPrevMeaningfulToken($previousUnsetSemicolon); + if (null === $previousUnsetBraceEnd) { + return $index; + } + + if (!$tokens[$previousUnsetBraceEnd]->equals(')')) { + return $previousUnsetBraceEnd; + } + + $previousUnsetBraceStart = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $previousUnsetBraceEnd); + $previousUnset = $tokens->getPrevMeaningfulToken($previousUnsetBraceStart); + if (null === $previousUnset) { + return $index; + } + + if (!$tokens[$previousUnset]->isGivenKind(T_UNSET)) { + return $previousUnset; + } + + return [ + $previousUnset, + $previousUnsetBraceStart, + $previousUnsetBraceEnd, + $previousUnsetSemicolon, + ]; + } + + /** + * @param int $start Index previous of the first token to move + * @param int $end Index of the last token to move + * @param int $to Upper boundary index + * + * @return int Number of tokens inserted + */ + private function moveTokens(Tokens $tokens, int $start, int $end, int $to): int + { + $added = 0; + for ($i = $start + 1; $i < $end; $i += 2) { + if ($tokens[$i]->isWhitespace() && $tokens[$to + 1]->isWhitespace()) { + $tokens[$to + 1] = new Token([T_WHITESPACE, $tokens[$to + 1]->getContent().$tokens[$i]->getContent()]); + } else { + $tokens->insertAt(++$to, clone $tokens[$i]); + ++$end; + ++$added; + } + + $tokens->clearAt($i + 1); + } + + return $added; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php new file mode 100644 index 00000000..76b70a20 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php @@ -0,0 +1,133 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class DeclareEqualNormalizeFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var string + */ + private $callback; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->callback = 'none' === $this->configuration['space'] ? 'removeWhitespaceAroundToken' : 'ensureWhitespaceAroundToken'; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Equal sign in declare statement should be surrounded by spaces or not following configuration.', + [ + new CodeSample(" 'single']), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run after DeclareStrictTypesFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DECLARE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $callback = $this->callback; + for ($index = 0, $count = $tokens->count(); $index < $count - 6; ++$index) { + if (!$tokens[$index]->isGivenKind(T_DECLARE)) { + continue; + } + + $openParenthesisIndex = $tokens->getNextMeaningfulToken($index); + $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesisIndex); + + for ($i = $closeParenthesisIndex; $i > $openParenthesisIndex; --$i) { + if ($tokens[$i]->equals('=')) { + $this->{$callback}($tokens, $i); + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('space', 'Spacing to apply around the equal sign.')) + ->setAllowedValues(['single', 'none']) + ->setDefault('none') + ->getOption(), + ]); + } + + /** + * @param int $index of `=` token + */ + private function ensureWhitespaceAroundToken(Tokens $tokens, int $index): void + { + if ($tokens[$index + 1]->isWhitespace()) { + if (' ' !== $tokens[$index + 1]->getContent()) { + $tokens[$index + 1] = new Token([T_WHITESPACE, ' ']); + } + } else { + $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); + } + + if ($tokens[$index - 1]->isWhitespace()) { + if (' ' !== $tokens[$index - 1]->getContent() && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { + $tokens[$index - 1] = new Token([T_WHITESPACE, ' ']); + } + } else { + $tokens->insertAt($index, new Token([T_WHITESPACE, ' '])); + } + } + + /** + * @param int $index of `=` token + */ + private function removeWhitespaceAroundToken(Tokens $tokens, int $index): void + { + if (!$tokens[$tokens->getPrevNonWhitespace($index)]->isComment()) { + $tokens->removeLeadingWhitespace($index); + } + + $tokens->removeTrailingWhitespace($index); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareParenthesesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareParenthesesFixer.php new file mode 100644 index 00000000..e3879731 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareParenthesesFixer.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +final class DeclareParenthesesFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There must not be spaces around `declare` statement parentheses.', + [new CodeSample("isTokenKindFound(T_DECLARE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(T_DECLARE)) { + continue; + } + + $tokens->removeTrailingWhitespace($index); + + $startParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(']); + $tokens->removeTrailingWhitespace($startParenthesisIndex); + + $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex); + $tokens->removeLeadingWhitespace($endParenthesisIndex); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DirConstantFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DirConstantFixer.php new file mode 100644 index 00000000..a19368e0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DirConstantFixer.php @@ -0,0 +1,129 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Vladimir Reznichenko + */ +final class DirConstantFixer extends AbstractFunctionReferenceFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replaces `dirname(__FILE__)` expression with equivalent `__DIR__` constant.', + [new CodeSample("isAllTokenKindsFound([T_STRING, T_FILE]); + } + + /** + * {@inheritdoc} + * + * Must run before CombineNestedDirnameFixer. + */ + public function getPriority(): int + { + return 40; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $currIndex = 0; + + do { + $boundaries = $this->find('dirname', $tokens, $currIndex, $tokens->count() - 1); + if (null === $boundaries) { + return; + } + + [$functionNameIndex, $openParenthesis, $closeParenthesis] = $boundaries; + + // analysing cursor shift, so nested expressions kept processed + $currIndex = $openParenthesis; + + // ensure __FILE__ is in between (...) + + $fileCandidateRightIndex = $tokens->getPrevMeaningfulToken($closeParenthesis); + $trailingCommaIndex = null; + + if ($tokens[$fileCandidateRightIndex]->equals(',')) { + $trailingCommaIndex = $fileCandidateRightIndex; + $fileCandidateRightIndex = $tokens->getPrevMeaningfulToken($fileCandidateRightIndex); + } + + $fileCandidateRight = $tokens[$fileCandidateRightIndex]; + + if (!$fileCandidateRight->isGivenKind(T_FILE)) { + continue; + } + + $fileCandidateLeftIndex = $tokens->getNextMeaningfulToken($openParenthesis); + $fileCandidateLeft = $tokens[$fileCandidateLeftIndex]; + + if (!$fileCandidateLeft->isGivenKind(T_FILE)) { + continue; + } + + // get rid of root namespace when it used + $namespaceCandidateIndex = $tokens->getPrevMeaningfulToken($functionNameIndex); + $namespaceCandidate = $tokens[$namespaceCandidateIndex]; + + if ($namespaceCandidate->isGivenKind(T_NS_SEPARATOR)) { + $tokens->removeTrailingWhitespace($namespaceCandidateIndex); + $tokens->clearAt($namespaceCandidateIndex); + } + + if (null !== $trailingCommaIndex) { + if (!$tokens[$tokens->getNextNonWhitespace($trailingCommaIndex)]->isComment()) { + $tokens->removeTrailingWhitespace($trailingCommaIndex); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($trailingCommaIndex); + } + + // closing parenthesis removed with leading spaces + if (!$tokens[$tokens->getNextNonWhitespace($closeParenthesis)]->isComment()) { + $tokens->removeLeadingWhitespace($closeParenthesis); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesis); + + // opening parenthesis removed with trailing and leading spaces + if (!$tokens[$tokens->getNextNonWhitespace($openParenthesis)]->isComment()) { + $tokens->removeLeadingWhitespace($openParenthesis); + } + + $tokens->removeTrailingWhitespace($openParenthesis); + $tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesis); + + // replace constant and remove function name + $tokens[$fileCandidateLeftIndex] = new Token([T_DIR, '__DIR__']); + $tokens->clearTokenAndMergeSurroundingWhitespace($functionNameIndex); + } while (null !== $currIndex); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php new file mode 100644 index 00000000..5cf4b852 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php @@ -0,0 +1,169 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Jules Pietri + * @author Kuba Werłos + */ +final class ErrorSuppressionFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const OPTION_MUTE_DEPRECATION_ERROR = 'mute_deprecation_error'; + + /** + * @internal + */ + public const OPTION_NOISE_REMAINING_USAGES = 'noise_remaining_usages'; + + /** + * @internal + */ + public const OPTION_NOISE_REMAINING_USAGES_EXCLUDE = 'noise_remaining_usages_exclude'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Error control operator should be added to deprecation notices and/or removed from other cases.', + [ + new CodeSample(" true] + ), + new CodeSample( + " true, + self::OPTION_NOISE_REMAINING_USAGES_EXCLUDE => ['unlink'], + ] + ), + ], + null, + 'Risky because adding/removing `@` might cause changes to code behaviour or if `trigger_error` function is overridden.' + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder(self::OPTION_MUTE_DEPRECATION_ERROR, 'Whether to add `@` in deprecation notices.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder(self::OPTION_NOISE_REMAINING_USAGES, 'Whether to remove `@` in remaining usages.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder(self::OPTION_NOISE_REMAINING_USAGES_EXCLUDE, 'List of global functions to exclude from removing `@`.')) + ->setAllowedTypes(['array']) + ->setDefault([]) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $excludedFunctions = array_map(static fn (string $function): string => strtolower($function), $this->configuration[self::OPTION_NOISE_REMAINING_USAGES_EXCLUDE]); + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (true === $this->configuration[self::OPTION_NOISE_REMAINING_USAGES] && $token->equals('@')) { + $tokens->clearAt($index); + + continue; + } + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + $functionIndex = $index; + $startIndex = $index; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { + $startIndex = $prevIndex; + $prevIndex = $tokens->getPrevMeaningfulToken($startIndex); + } + + $index = $prevIndex; + + if ($this->isDeprecationErrorCall($tokens, $functionIndex)) { + if (false === $this->configuration[self::OPTION_MUTE_DEPRECATION_ERROR]) { + continue; + } + + if ($tokens[$prevIndex]->equals('@')) { + continue; + } + + $tokens->insertAt($startIndex, new Token('@')); + + continue; + } + + if (!$tokens[$prevIndex]->equals('@')) { + continue; + } + + if (true === $this->configuration[self::OPTION_NOISE_REMAINING_USAGES] && !\in_array($tokens[$functionIndex]->getContent(), $excludedFunctions, true)) { + $tokens->clearAt($index); + } + } + } + + private function isDeprecationErrorCall(Tokens $tokens, int $index): bool + { + if ('trigger_error' !== strtolower($tokens[$index]->getContent())) { + return false; + } + + $endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextTokenOfKind($index, [[T_STRING], '('])); + $prevIndex = $tokens->getPrevMeaningfulToken($endBraceIndex); + + if ($tokens[$prevIndex]->equals(',')) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + } + + return $tokens[$prevIndex]->equals([T_STRING, 'E_USER_DEPRECATED']); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php new file mode 100644 index 00000000..38ef5fe9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php @@ -0,0 +1,82 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + */ +final class ExplicitIndirectVariableFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Add curly braces to indirect variables to make them clear to understand. Requires PHP >= 7.0.', + [ + new CodeSample( + <<<'EOT' + $bar['baz']; + echo $foo->$callback($baz); + + EOT + ), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_VARIABLE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index > 1; --$index) { + $token = $tokens[$index]; + if (!$token->isGivenKind(T_VARIABLE)) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $prevToken = $tokens[$prevIndex]; + if (!$prevToken->equals('$') && !$prevToken->isObjectOperator()) { + continue; + } + + $openingBrace = CT::T_DYNAMIC_VAR_BRACE_OPEN; + $closingBrace = CT::T_DYNAMIC_VAR_BRACE_CLOSE; + if ($prevToken->isObjectOperator()) { + $openingBrace = CT::T_DYNAMIC_PROP_BRACE_OPEN; + $closingBrace = CT::T_DYNAMIC_PROP_BRACE_CLOSE; + } + + $tokens->overrideRange($index, $index, [ + new Token([$openingBrace, '{']), + new Token([T_VARIABLE, $token->getContent()]), + new Token([$closingBrace, '}']), + ]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/FunctionToConstantFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/FunctionToConstantFixer.php new file mode 100644 index 00000000..0c81c54d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/FunctionToConstantFixer.php @@ -0,0 +1,283 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class FunctionToConstantFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private static $availableFunctions; + + /** + * @var array + */ + private array $functionsFixMap; + + public function __construct() + { + if (null === self::$availableFunctions) { + self::$availableFunctions = [ + 'get_called_class' => [ + new Token([T_STATIC, 'static']), + new Token([T_DOUBLE_COLON, '::']), + new Token([CT::T_CLASS_CONSTANT, 'class']), + ], + 'get_class' => [new Token([T_CLASS_C, '__CLASS__'])], + 'get_class_this' => [ + new Token([T_STATIC, 'static']), + new Token([T_DOUBLE_COLON, '::']), + new Token([CT::T_CLASS_CONSTANT, 'class']), + ], + 'php_sapi_name' => [new Token([T_STRING, 'PHP_SAPI'])], + 'phpversion' => [new Token([T_STRING, 'PHP_VERSION'])], + 'pi' => [new Token([T_STRING, 'M_PI'])], + ]; + } + + parent::__construct(); + } + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->functionsFixMap = []; + + foreach ($this->configuration['functions'] as $key) { + $this->functionsFixMap[$key] = self::$availableFunctions[$key]; + } + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace core functions calls returning constants with the constants.', + [ + new CodeSample( + " ['get_called_class', 'get_class_this', 'phpversion']] + ), + ], + null, + 'Risky when any of the configured functions to replace are overridden.' + ); + } + + /** + * {@inheritdoc} + * + * Must run before NativeConstantInvocationFixer, NativeFunctionCasingFixer, NoExtraBlankLinesFixer, NoSinglelineWhitespaceBeforeSemicolonsFixer, NoTrailingWhitespaceFixer, NoWhitespaceInBlankLineFixer, SelfStaticAccessorFixer. + * Must run after NoSpacesAfterFunctionNameFixer, NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer. + */ + public function getPriority(): int + { + return 2; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionAnalyzer = new FunctionsAnalyzer(); + + for ($index = $tokens->count() - 4; $index > 0; --$index) { + $candidate = $this->getReplaceCandidate($tokens, $functionAnalyzer, $index); + if (null === $candidate) { + continue; + } + + $this->fixFunctionCallToConstant( + $tokens, + $index, + $candidate[0], // brace open + $candidate[1], // brace close + $candidate[2] // replacement + ); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $functionNames = array_keys(self::$availableFunctions); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('functions', 'List of function names to fix.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset($functionNames)]) + ->setDefault([ + 'get_called_class', + 'get_class', + 'get_class_this', + 'php_sapi_name', + 'phpversion', + 'pi', + ]) + ->getOption(), + ]); + } + + /** + * @param Token[] $replacements + */ + private function fixFunctionCallToConstant(Tokens $tokens, int $index, int $braceOpenIndex, int $braceCloseIndex, array $replacements): void + { + for ($i = $braceCloseIndex; $i >= $braceOpenIndex; --$i) { + if ($tokens[$i]->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + + if ($replacements[0]->isGivenKind([T_CLASS_C, T_STATIC])) { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $prevToken = $tokens[$prevIndex]; + if ($prevToken->isGivenKind(T_NS_SEPARATOR)) { + $tokens->clearAt($prevIndex); + } + } + + $tokens->clearAt($index); + $tokens->insertAt($index, $replacements); + } + + private function getReplaceCandidate( + Tokens $tokens, + FunctionsAnalyzer $functionAnalyzer, + int $index + ): ?array { + if (!$tokens[$index]->isGivenKind(T_STRING)) { + return null; + } + + $lowerContent = strtolower($tokens[$index]->getContent()); + + if ('get_class' === $lowerContent) { + return $this->fixGetClassCall($tokens, $functionAnalyzer, $index); + } + + if (!isset($this->functionsFixMap[$lowerContent])) { + return null; + } + + if (!$functionAnalyzer->isGlobalFunctionCall($tokens, $index)) { + return null; + } + + // test if function call without parameters + $braceOpenIndex = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$braceOpenIndex]->equals('(')) { + return null; + } + + $braceCloseIndex = $tokens->getNextMeaningfulToken($braceOpenIndex); + if (!$tokens[$braceCloseIndex]->equals(')')) { + return null; + } + + return $this->getReplacementTokenClones($lowerContent, $braceOpenIndex, $braceCloseIndex); + } + + private function fixGetClassCall( + Tokens $tokens, + FunctionsAnalyzer $functionAnalyzer, + int $index + ): ?array { + if (!isset($this->functionsFixMap['get_class']) && !isset($this->functionsFixMap['get_class_this'])) { + return null; + } + + if (!$functionAnalyzer->isGlobalFunctionCall($tokens, $index)) { + return null; + } + + $braceOpenIndex = $tokens->getNextMeaningfulToken($index); + $braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $braceOpenIndex); + + if ($braceCloseIndex === $tokens->getNextMeaningfulToken($braceOpenIndex)) { // no arguments passed + if (isset($this->functionsFixMap['get_class'])) { + return $this->getReplacementTokenClones('get_class', $braceOpenIndex, $braceCloseIndex); + } + } elseif (isset($this->functionsFixMap['get_class_this'])) { + $isThis = false; + + for ($i = $braceOpenIndex + 1; $i < $braceCloseIndex; ++$i) { + if ($tokens[$i]->equalsAny([[T_WHITESPACE], [T_COMMENT], [T_DOC_COMMENT], ')'])) { + continue; + } + + if ($tokens[$i]->isGivenKind(T_VARIABLE) && '$this' === strtolower($tokens[$i]->getContent())) { + $isThis = true; + + continue; + } + + if (false === $isThis && $tokens[$i]->equals('(')) { + continue; + } + + $isThis = false; + + break; + } + + if ($isThis) { + return $this->getReplacementTokenClones('get_class_this', $braceOpenIndex, $braceCloseIndex); + } + } + + return null; + } + + private function getReplacementTokenClones(string $lowerContent, int $braceOpenIndex, int $braceCloseIndex): array + { + $clones = []; + foreach ($this->functionsFixMap[$lowerContent] as $token) { + $clones[] = clone $token; + } + + return [ + $braceOpenIndex, + $braceCloseIndex, + $clones, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/GetClassToClassKeywordFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/GetClassToClassKeywordFixer.php new file mode 100644 index 00000000..d5ceb526 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/GetClassToClassKeywordFixer.php @@ -0,0 +1,158 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author John Paul E. Balandan, CPA + */ +final class GetClassToClassKeywordFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace `get_class` calls on object variables with class keyword syntax.', + [ + new VersionSpecificCodeSample( + "= 8_00_00 && $tokens->isAllTokenKindsFound([T_STRING, T_VARIABLE]); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $indicesToClear = []; + $tokenSlices = []; + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->equals([T_STRING, 'get_class'], false)) { + continue; + } + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + $braceOpenIndex = $tokens->getNextMeaningfulToken($index); + $braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $braceOpenIndex); + + if ($braceCloseIndex === $tokens->getNextMeaningfulToken($braceOpenIndex)) { + continue; // get_class with no arguments + } + + $meaningfulTokensCount = 0; + $variableTokensIndices = []; + + for ($i = $braceOpenIndex + 1; $i < $braceCloseIndex; ++$i) { + if (!$tokens[$i]->equalsAny([[T_WHITESPACE], [T_COMMENT], [T_DOC_COMMENT], '(', ')'])) { + ++$meaningfulTokensCount; + } + + if (!$tokens[$i]->isGivenKind(T_VARIABLE)) { + continue; + } + + if ('$this' === strtolower($tokens[$i]->getContent())) { + continue 2; // get_class($this) + } + + $variableTokensIndices[] = $i; + } + + if ($meaningfulTokensCount > 1 || 1 !== \count($variableTokensIndices)) { + continue; // argument contains more logic, or more arguments, or no variable argument + } + + $indicesToClear[$index] = [$braceOpenIndex, current($variableTokensIndices), $braceCloseIndex]; + } + + foreach ($indicesToClear as $index => $items) { + $tokenSlices[$index] = $this->getReplacementTokenSlices($tokens, $items[1]); + $this->clearGetClassCall($tokens, $index, $items[0], $items[2]); + } + + $tokens->insertSlices($tokenSlices); + } + + /** + * @return list + */ + private function getReplacementTokenSlices(Tokens $tokens, int $variableIndex): array + { + return [ + new Token([T_VARIABLE, $tokens[$variableIndex]->getContent()]), + new Token([T_DOUBLE_COLON, '::']), + new Token([CT::T_CLASS_CONSTANT, 'class']), + ]; + } + + private function clearGetClassCall(Tokens $tokens, int $index, int $braceOpenIndex, int $braceCloseIndex): void + { + for ($i = $braceOpenIndex; $i <= $braceCloseIndex; ++$i) { + if ($tokens[$i]->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { + $tokens->clearAt($prevIndex); + } + + $tokens->clearAt($index); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/IsNullFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/IsNullFixer.php new file mode 100644 index 00000000..a99695d4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/IsNullFixer.php @@ -0,0 +1,169 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Vladimir Reznichenko + */ +final class IsNullFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replaces `is_null($var)` expression with `null === $var`.', + [ + new CodeSample("isTokenKindFound(T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + static $sequenceNeeded = [[T_STRING, 'is_null'], '(']; + $functionsAnalyzer = new FunctionsAnalyzer(); + $currIndex = 0; + + while (true) { + // recalculate "end" because we might have added tokens in previous iteration + $matches = $tokens->findSequence($sequenceNeeded, $currIndex, $tokens->count() - 1, false); + + // stop looping if didn't find any new matches + if (null === $matches) { + break; + } + + // 0 and 1 accordingly are "is_null", "(" tokens + $matches = array_keys($matches); + + // move the cursor just after the sequence + [$isNullIndex, $currIndex] = $matches; + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $matches[0])) { + continue; + } + + $next = $tokens->getNextMeaningfulToken($currIndex); + + if ($tokens[$next]->equals(')')) { + continue; + } + + $prevTokenIndex = $tokens->getPrevMeaningfulToken($matches[0]); + + // handle function references with namespaces + if ($tokens[$prevTokenIndex]->isGivenKind(T_NS_SEPARATOR)) { + $tokens->removeTrailingWhitespace($prevTokenIndex); + $tokens->clearAt($prevTokenIndex); + + $prevTokenIndex = $tokens->getPrevMeaningfulToken($prevTokenIndex); + } + + // check if inversion being used, text comparison is due to not existing constant + $isInvertedNullCheck = false; + + if ($tokens[$prevTokenIndex]->equals('!')) { + $isInvertedNullCheck = true; + + // get rid of inverting for proper transformations + $tokens->removeTrailingWhitespace($prevTokenIndex); + $tokens->clearAt($prevTokenIndex); + } + + // before getting rind of `()` around a parameter, ensure it's not assignment/ternary invariant + $referenceEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $matches[1]); + $isContainingDangerousConstructs = false; + + for ($paramTokenIndex = $matches[1]; $paramTokenIndex <= $referenceEnd; ++$paramTokenIndex) { + if (\in_array($tokens[$paramTokenIndex]->getContent(), ['?', '?:', '=', '??'], true)) { + $isContainingDangerousConstructs = true; + + break; + } + } + + // edge cases: is_null() followed/preceded by ==, ===, !=, !==, <>, (int-or-other-casting) + $parentLeftToken = $tokens[$tokens->getPrevMeaningfulToken($isNullIndex)]; + $parentRightToken = $tokens[$tokens->getNextMeaningfulToken($referenceEnd)]; + $parentOperations = [T_IS_EQUAL, T_IS_NOT_EQUAL, T_IS_IDENTICAL, T_IS_NOT_IDENTICAL]; + $wrapIntoParentheses = $parentLeftToken->isCast() || $parentLeftToken->isGivenKind($parentOperations) || $parentRightToken->isGivenKind($parentOperations); + + // possible trailing comma removed + $prevIndex = $tokens->getPrevMeaningfulToken($referenceEnd); + + if ($tokens[$prevIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + } + + if (!$isContainingDangerousConstructs) { + // closing parenthesis removed with leading spaces + $tokens->removeLeadingWhitespace($referenceEnd); + $tokens->clearAt($referenceEnd); + + // opening parenthesis removed with trailing spaces + $tokens->removeLeadingWhitespace($matches[1]); + $tokens->removeTrailingWhitespace($matches[1]); + $tokens->clearAt($matches[1]); + } + + // sequence which we'll use as a replacement + $replacement = [ + new Token([T_STRING, 'null']), + new Token([T_WHITESPACE, ' ']), + new Token($isInvertedNullCheck ? [T_IS_NOT_IDENTICAL, '!=='] : [T_IS_IDENTICAL, '===']), + new Token([T_WHITESPACE, ' ']), + ]; + + if ($wrapIntoParentheses) { + array_unshift($replacement, new Token('(')); + $tokens->insertAt($referenceEnd + 1, new Token(')')); + } + + $tokens->overrideRange($isNullIndex, $isNullIndex, $replacement); + + // nested is_null calls support + $currIndex = $isNullIndex; + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.php new file mode 100644 index 00000000..15a151a1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.php @@ -0,0 +1,220 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Gert de Pagter + */ +final class NoUnsetOnPropertyFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Properties should be set to `null` instead of using `unset`.', + [new CodeSample("a);\n")], + null, + 'Risky when relying on attributes to be removed using `unset` rather than be set to `null`.'. + ' Changing variables to `null` instead of unsetting means these still show up when looping over class variables'. + ' and reference properties remain unbroken.'. + ' With PHP 7.4, this rule might introduce `null` assignments to properties whose type declaration does not allow it.' + ); + } + + public function isRisky(): bool + { + return true; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_UNSET) + && $tokens->isAnyTokenKindsFound([T_OBJECT_OPERATOR, T_PAAMAYIM_NEKUDOTAYIM]); + } + + /** + * {@inheritdoc} + * + * Must run before CombineConsecutiveUnsetsFixer. + */ + public function getPriority(): int + { + return 25; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (!$tokens[$index]->isGivenKind(T_UNSET)) { + continue; + } + + $unsetsInfo = $this->getUnsetsInfo($tokens, $index); + + if (!$this->isAnyUnsetToTransform($unsetsInfo)) { + continue; + } + + $isLastUnset = true; // "last" as we reverse the array below + + foreach (array_reverse($unsetsInfo) as $unsetInfo) { + $this->updateTokens($tokens, $unsetInfo, $isLastUnset); + $isLastUnset = false; + } + } + } + + /** + * @return array> + */ + private function getUnsetsInfo(Tokens $tokens, int $index): array + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + $unsetStart = $tokens->getNextTokenOfKind($index, ['(']); + $unsetEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $unsetStart); + $isFirst = true; + $unsets = []; + + foreach ($argumentsAnalyzer->getArguments($tokens, $unsetStart, $unsetEnd) as $startIndex => $endIndex) { + $startIndex = $tokens->getNextMeaningfulToken($startIndex - 1); + $endIndex = $tokens->getPrevMeaningfulToken($endIndex + 1); + $unsets[] = [ + 'startIndex' => $startIndex, + 'endIndex' => $endIndex, + 'isToTransform' => $this->isProperty($tokens, $startIndex, $endIndex), + 'isFirst' => $isFirst, + ]; + $isFirst = false; + } + + return $unsets; + } + + private function isProperty(Tokens $tokens, int $index, int $endIndex): bool + { + if ($tokens[$index]->isGivenKind(T_VARIABLE)) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if (null === $nextIndex || !$tokens[$nextIndex]->isGivenKind(T_OBJECT_OPERATOR)) { + return false; + } + + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); + + if (null !== $nextNextIndex && $nextNextIndex < $endIndex) { + return false; + } + + return null !== $nextIndex && $tokens[$nextIndex]->isGivenKind(T_STRING); + } + + if ($tokens[$index]->isGivenKind([T_NS_SEPARATOR, T_STRING])) { + $nextIndex = $tokens->getTokenNotOfKindsSibling($index, 1, [T_DOUBLE_COLON, T_NS_SEPARATOR, T_STRING]); + $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); + + if (null !== $nextNextIndex && $nextNextIndex < $endIndex) { + return false; + } + + return null !== $nextIndex && $tokens[$nextIndex]->isGivenKind(T_VARIABLE); + } + + return false; + } + + /** + * @param array> $unsetsInfo + */ + private function isAnyUnsetToTransform(array $unsetsInfo): bool + { + foreach ($unsetsInfo as $unsetInfo) { + if ($unsetInfo['isToTransform']) { + return true; + } + } + + return false; + } + + /** + * @param array $unsetInfo + */ + private function updateTokens(Tokens $tokens, array $unsetInfo, bool $isLastUnset): void + { + // if entry is first and to be transformed we remove leading "unset(" + if ($unsetInfo['isFirst'] && $unsetInfo['isToTransform']) { + $braceIndex = $tokens->getPrevTokenOfKind($unsetInfo['startIndex'], ['(']); + $unsetIndex = $tokens->getPrevTokenOfKind($braceIndex, [[T_UNSET]]); + $tokens->clearTokenAndMergeSurroundingWhitespace($braceIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($unsetIndex); + } + + // if entry is last and to be transformed we remove trailing ")" + if ($isLastUnset && $unsetInfo['isToTransform']) { + $braceIndex = $tokens->getNextTokenOfKind($unsetInfo['endIndex'], [')']); + $previousIndex = $tokens->getPrevMeaningfulToken($braceIndex); + if ($tokens[$previousIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($previousIndex); // trailing ',' in function call (PHP 7.3) + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($braceIndex); + } + + // if entry is not last we replace comma with semicolon (last entry already has semicolon - from original unset) + if (!$isLastUnset) { + $commaIndex = $tokens->getNextTokenOfKind($unsetInfo['endIndex'], [',']); + $tokens[$commaIndex] = new Token(';'); + } + + // if entry is to be unset and is not last we add trailing ")" + if (!$unsetInfo['isToTransform'] && !$isLastUnset) { + $tokens->insertAt($unsetInfo['endIndex'] + 1, new Token(')')); + } + + // if entry is to be unset and is not first we add leading "unset(" + if (!$unsetInfo['isToTransform'] && !$unsetInfo['isFirst']) { + $tokens->insertAt( + $unsetInfo['startIndex'], + [ + new Token([T_UNSET, 'unset']), + new Token('('), + ] + ); + } + + // and finally + // if entry is to be transformed we add trailing " = null" + if ($unsetInfo['isToTransform']) { + $tokens->insertAt( + $unsetInfo['endIndex'] + 1, + [ + new Token([T_WHITESPACE, ' ']), + new Token('='), + new Token([T_WHITESPACE, ' ']), + new Token([T_STRING, 'null']), + ] + ); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NullableTypeDeclarationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NullableTypeDeclarationFixer.php new file mode 100644 index 00000000..a7b65432 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NullableTypeDeclarationFixer.php @@ -0,0 +1,332 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author John Paul E. Balandan, CPA + */ +final class NullableTypeDeclarationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const OPTION_SYNTAX_UNION = 'union'; + private const OPTION_SYNTAX_QUESTION_MARK = 'question_mark'; + + private int $candidateTokenKind; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Nullable single type declaration should be standardised using configured syntax.', + [ + new VersionSpecificCodeSample( + " self::OPTION_SYNTAX_UNION] + ), + new VersionSpecificCodeSample( + ' self::OPTION_SYNTAX_QUESTION_MARK] + ), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return \PHP_VERSION_ID >= 8_00_00 && $tokens->isTokenKindFound($this->candidateTokenKind); + } + + /** + * {@inheritdoc} + * + * Must run before OrderedTypesFixer, TypesSpacesFixer. + * Must run after NullableTypeDeclarationForDefaultNullValueFixer, SingleSpaceAroundConstructFixer. + */ + public function getPriority(): int + { + return 2; + } + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->candidateTokenKind = self::OPTION_SYNTAX_QUESTION_MARK === $this->configuration['syntax'] + ? CT::T_TYPE_ALTERNATION // `|` -> `?` + : CT::T_NULLABLE_TYPE; // `?` -> `|` + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('syntax', 'Whether to use question mark (`?`) or explicit `null` union for nullable type.')) + ->setAllowedValues([self::OPTION_SYNTAX_UNION, self::OPTION_SYNTAX_QUESTION_MARK]) + ->setDefault(self::OPTION_SYNTAX_QUESTION_MARK) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + foreach (array_reverse($this->getElements($tokens), true) as $index => $type) { + if ('property' === $type) { + $this->normalizePropertyType($tokens, $index); + + continue; + } + + $this->normalizeMethodReturnType($functionsAnalyzer, $tokens, $index); + $this->normalizeMethodArgumentType($functionsAnalyzer, $tokens, $index); + } + } + + /** + * @return array + * + * @phpstan-return array + */ + private function getElements(Tokens $tokens): array + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $elements = array_map( + static fn (array $element): string => 'method' === $element['type'] ? 'function' : $element['type'], + array_filter( + $tokensAnalyzer->getClassyElements(), + static fn (array $element): bool => \in_array($element['type'], ['method', 'property'], true) + ) + ); + + foreach ($tokens as $index => $token) { + if ( + $token->isGivenKind(T_FN) + || ($token->isGivenKind(T_FUNCTION) && !isset($elements[$index])) + ) { + $elements[$index] = 'function'; + } + } + + return $elements; + } + + private function collectTypeAnalysis(Tokens $tokens, int $startIndex, int $endIndex): ?TypeAnalysis + { + $type = ''; + $typeStartIndex = $tokens->getNextMeaningfulToken($startIndex); + $typeEndIndex = $typeStartIndex; + + for ($i = $typeStartIndex; $i < $endIndex; ++$i) { + if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { + continue; + } + + $type .= $tokens[$i]->getContent(); + $typeEndIndex = $i; + } + + return '' !== $type ? new TypeAnalysis($type, $typeStartIndex, $typeEndIndex) : null; + } + + private function isTypeNormalizable(TypeAnalysis $typeAnalysis): bool + { + if (!$typeAnalysis->isNullable()) { + return false; + } + + $type = $typeAnalysis->getName(); + + if (str_contains($type, '&')) { + return false; // skip DNF types + } + + if (!str_contains($type, '|')) { + return true; + } + + return 1 === substr_count($type, '|') && Preg::match('/(?:\|null$|^null\|)/i', $type); + } + + private function normalizePropertyType(Tokens $tokens, int $index): void + { + $propertyEndIndex = $index; + $propertyModifiers = [T_PRIVATE, T_PROTECTED, T_PUBLIC, T_STATIC, T_VAR]; + + if (\defined('T_READONLY')) { + $propertyModifiers[] = T_READONLY; // @TODO: Drop condition when PHP 8.1+ is required + } + + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while (!$tokens[$index]->isGivenKind($propertyModifiers)); + + $propertyType = $this->collectTypeAnalysis($tokens, $index, $propertyEndIndex); + + if (null === $propertyType || !$this->isTypeNormalizable($propertyType)) { + return; + } + + $this->normalizeNullableType($tokens, $propertyType); + } + + private function normalizeMethodArgumentType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void + { + foreach (array_reverse($functionsAnalyzer->getFunctionArguments($tokens, $index), true) as $argumentInfo) { + $argumentType = $argumentInfo->getTypeAnalysis(); + + if (null === $argumentType || !$this->isTypeNormalizable($argumentType)) { + continue; + } + + $this->normalizeNullableType($tokens, $argumentType); + } + } + + private function normalizeMethodReturnType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void + { + $returnType = $functionsAnalyzer->getFunctionReturnType($tokens, $index); + + if (null === $returnType || !$this->isTypeNormalizable($returnType)) { + return; + } + + $this->normalizeNullableType($tokens, $returnType); + } + + private function normalizeNullableType(Tokens $tokens, TypeAnalysis $typeAnalysis): void + { + $type = $typeAnalysis->getName(); + + if (!str_contains($type, '|') && !str_contains($type, '&')) { + $type = ($typeAnalysis->isNullable() ? '?' : '').$type; + } + + $isQuestionMarkSyntax = self::OPTION_SYNTAX_QUESTION_MARK === $this->configuration['syntax']; + + if ($isQuestionMarkSyntax) { + $normalizedType = $this->convertToNullableType($type); + $normalizedTypeAsString = implode('', $normalizedType); + } else { + $normalizedType = $this->convertToExplicitUnionType($type); + $normalizedTypeAsString = implode('|', $normalizedType); + } + + if ($normalizedTypeAsString === $type) { + return; // nothing to fix + } + + $tokens->overrideRange( + $typeAnalysis->getStartIndex(), + $typeAnalysis->getEndIndex(), + $this->createTypeDeclarationTokens($normalizedType, $isQuestionMarkSyntax) + ); + } + + /** + * @return list + */ + private function convertToNullableType(string $type): array + { + if (str_starts_with($type, '?')) { + return [$type]; // no need to convert; already fixed + } + + return ['?', Preg::replace('/(?:\|null$|^null\|)/i', '', $type)]; + } + + /** + * @return list + */ + private function convertToExplicitUnionType(string $type): array + { + if (str_contains($type, '|')) { + return [$type]; // no need to convert; already fixed + } + + return ['null', substr($type, 1)]; + } + + /** + * @param list $types + * + * @return list + */ + private function createTypeDeclarationTokens(array $types, bool $isQuestionMarkSyntax): array + { + static $specialTypes = [ + '?' => [CT::T_NULLABLE_TYPE, '?'], + 'array' => [CT::T_ARRAY_TYPEHINT, 'array'], + 'callable' => [T_CALLABLE, 'callable'], + 'static' => [T_STATIC, 'static'], + ]; + + $count = \count($types); + $newTokens = []; + + foreach ($types as $index => $type) { + if (isset($specialTypes[$type])) { + $newTokens[] = new Token($specialTypes[$type]); + } else { + foreach (explode('\\', $type) as $nsIndex => $value) { + if (0 === $nsIndex && '' === $value) { + continue; + } + + if ($nsIndex > 0) { + $newTokens[] = new Token([T_NS_SEPARATOR, '\\']); + } + + $newTokens[] = new Token([T_STRING, $value]); + } + } + + if ($index <= $count - 2 && !$isQuestionMarkSyntax) { + $newTokens[] = new Token([CT::T_TYPE_ALTERNATION, '|']); + } + } + + return $newTokens; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.php new file mode 100644 index 00000000..229049a3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.php @@ -0,0 +1,198 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; + +/** + * @author Andreas Möller + * + * @deprecated + */ +final class SingleSpaceAfterConstructFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface +{ + /** + * @var array + */ + private static array $tokenMap = [ + 'abstract' => T_ABSTRACT, + 'as' => T_AS, + 'attribute' => CT::T_ATTRIBUTE_CLOSE, + 'break' => T_BREAK, + 'case' => T_CASE, + 'catch' => T_CATCH, + 'class' => T_CLASS, + 'clone' => T_CLONE, + 'comment' => T_COMMENT, + 'const' => T_CONST, + 'const_import' => CT::T_CONST_IMPORT, + 'continue' => T_CONTINUE, + 'do' => T_DO, + 'echo' => T_ECHO, + 'else' => T_ELSE, + 'elseif' => T_ELSEIF, + 'enum' => null, + 'extends' => T_EXTENDS, + 'final' => T_FINAL, + 'finally' => T_FINALLY, + 'for' => T_FOR, + 'foreach' => T_FOREACH, + 'function' => T_FUNCTION, + 'function_import' => CT::T_FUNCTION_IMPORT, + 'global' => T_GLOBAL, + 'goto' => T_GOTO, + 'if' => T_IF, + 'implements' => T_IMPLEMENTS, + 'include' => T_INCLUDE, + 'include_once' => T_INCLUDE_ONCE, + 'instanceof' => T_INSTANCEOF, + 'insteadof' => T_INSTEADOF, + 'interface' => T_INTERFACE, + 'match' => null, + 'named_argument' => CT::T_NAMED_ARGUMENT_COLON, + 'namespace' => T_NAMESPACE, + 'new' => T_NEW, + 'open_tag_with_echo' => T_OPEN_TAG_WITH_ECHO, + 'php_doc' => T_DOC_COMMENT, + 'php_open' => T_OPEN_TAG, + 'print' => T_PRINT, + 'private' => T_PRIVATE, + 'protected' => T_PROTECTED, + 'public' => T_PUBLIC, + 'readonly' => null, + 'require' => T_REQUIRE, + 'require_once' => T_REQUIRE_ONCE, + 'return' => T_RETURN, + 'static' => T_STATIC, + 'switch' => T_SWITCH, + 'throw' => T_THROW, + 'trait' => T_TRAIT, + 'try' => T_TRY, + 'type_colon' => CT::T_TYPE_COLON, + 'use' => T_USE, + 'use_lambda' => CT::T_USE_LAMBDA, + 'use_trait' => CT::T_USE_TRAIT, + 'var' => T_VAR, + 'while' => T_WHILE, + 'yield' => T_YIELD, + 'yield_from' => T_YIELD_FROM, + ]; + + private SingleSpaceAroundConstructFixer $singleSpaceAroundConstructFixer; + + public function __construct() + { + $this->singleSpaceAroundConstructFixer = new SingleSpaceAroundConstructFixer(); + + parent::__construct(); + } + + public function getSuccessorsNames(): array + { + return array_keys($this->proxyFixers); + } + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->singleSpaceAroundConstructFixer->configure([ + 'constructs_contain_a_single_space' => [ + 'yield_from', + ], + 'constructs_preceded_by_a_single_space' => [], + 'constructs_followed_by_a_single_space' => $this->configuration['constructs'], + ]); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Ensures a single space after language constructs.', + [ + new CodeSample( + ' [ + 'echo', + ], + ] + ), + new CodeSample( + ' [ + 'yield_from', + ], + ] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before BracesFixer, FunctionDeclarationFixer. + * Must run after ArraySyntaxFixer, ModernizeStrposFixer. + */ + public function getPriority(): int + { + return parent::getPriority(); + } + + protected function createProxyFixers(): array + { + return [$this->singleSpaceAroundConstructFixer]; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $defaults = self::$tokenMap; + $tokens = array_keys($defaults); + + unset($defaults['type_colon']); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('constructs', 'List of constructs which must be followed by a single space.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset($tokens)]) + ->setDefault(array_keys($defaults)) + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAroundConstructFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAroundConstructFixer.php new file mode 100644 index 00000000..29d395f9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAroundConstructFixer.php @@ -0,0 +1,450 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Andreas Möller + * @author Dariusz Rumiński + */ +final class SingleSpaceAroundConstructFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private static array $tokenMapContainASingleSpace = [ + // for now, only one case - but we are ready to extend it, when we learn about new cases to cover + 'yield_from' => T_YIELD_FROM, + ]; + + /** + * @var array + */ + private static array $tokenMapPrecededByASingleSpace = [ + 'as' => T_AS, + 'use_lambda' => CT::T_USE_LAMBDA, + ]; + + /** + * @var array + */ + private static array $tokenMapFollowedByASingleSpace = [ + 'abstract' => T_ABSTRACT, + 'as' => T_AS, + 'attribute' => CT::T_ATTRIBUTE_CLOSE, + 'break' => T_BREAK, + 'case' => T_CASE, + 'catch' => T_CATCH, + 'class' => T_CLASS, + 'clone' => T_CLONE, + 'comment' => T_COMMENT, + 'const' => T_CONST, + 'const_import' => CT::T_CONST_IMPORT, + 'continue' => T_CONTINUE, + 'do' => T_DO, + 'echo' => T_ECHO, + 'else' => T_ELSE, + 'elseif' => T_ELSEIF, + 'enum' => null, + 'extends' => T_EXTENDS, + 'final' => T_FINAL, + 'finally' => T_FINALLY, + 'for' => T_FOR, + 'foreach' => T_FOREACH, + 'function' => T_FUNCTION, + 'function_import' => CT::T_FUNCTION_IMPORT, + 'global' => T_GLOBAL, + 'goto' => T_GOTO, + 'if' => T_IF, + 'implements' => T_IMPLEMENTS, + 'include' => T_INCLUDE, + 'include_once' => T_INCLUDE_ONCE, + 'instanceof' => T_INSTANCEOF, + 'insteadof' => T_INSTEADOF, + 'interface' => T_INTERFACE, + 'match' => null, + 'named_argument' => CT::T_NAMED_ARGUMENT_COLON, + 'namespace' => T_NAMESPACE, + 'new' => T_NEW, + 'open_tag_with_echo' => T_OPEN_TAG_WITH_ECHO, + 'php_doc' => T_DOC_COMMENT, + 'php_open' => T_OPEN_TAG, + 'print' => T_PRINT, + 'private' => T_PRIVATE, + 'protected' => T_PROTECTED, + 'public' => T_PUBLIC, + 'readonly' => null, + 'require' => T_REQUIRE, + 'require_once' => T_REQUIRE_ONCE, + 'return' => T_RETURN, + 'static' => T_STATIC, + 'switch' => T_SWITCH, + 'throw' => T_THROW, + 'trait' => T_TRAIT, + 'try' => T_TRY, + 'type_colon' => CT::T_TYPE_COLON, + 'use' => T_USE, + 'use_lambda' => CT::T_USE_LAMBDA, + 'use_trait' => CT::T_USE_TRAIT, + 'var' => T_VAR, + 'while' => T_WHILE, + 'yield' => T_YIELD, + 'yield_from' => T_YIELD_FROM, + ]; + + /** + * @var array + */ + private array $fixTokenMapFollowedByASingleSpace = []; + + /** + * @var array + */ + private array $fixTokenMapContainASingleSpace = []; + + /** + * @var array + */ + private array $fixTokenMapPrecededByASingleSpace = []; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + if (\defined('T_MATCH')) { // @TODO: drop condition when PHP 8.0+ is required + self::$tokenMapFollowedByASingleSpace['match'] = T_MATCH; + } + + if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required + self::$tokenMapFollowedByASingleSpace['readonly'] = T_READONLY; + } + + if (\defined('T_ENUM')) { // @TODO: drop condition when PHP 8.1+ is required + self::$tokenMapFollowedByASingleSpace['enum'] = T_ENUM; + } + + $this->fixTokenMapContainASingleSpace = []; + + foreach ($this->configuration['constructs_contain_a_single_space'] as $key) { + if (null !== self::$tokenMapContainASingleSpace[$key]) { + $this->fixTokenMapContainASingleSpace[$key] = self::$tokenMapContainASingleSpace[$key]; + } + } + + $this->fixTokenMapPrecededByASingleSpace = []; + + foreach ($this->configuration['constructs_preceded_by_a_single_space'] as $key) { + if (null !== self::$tokenMapPrecededByASingleSpace[$key]) { + $this->fixTokenMapPrecededByASingleSpace[$key] = self::$tokenMapPrecededByASingleSpace[$key]; + } + } + + $this->fixTokenMapFollowedByASingleSpace = []; + + foreach ($this->configuration['constructs_followed_by_a_single_space'] as $key) { + if (null !== self::$tokenMapFollowedByASingleSpace[$key]) { + $this->fixTokenMapFollowedByASingleSpace[$key] = self::$tokenMapFollowedByASingleSpace[$key]; + } + } + + if (isset($this->fixTokenMapFollowedByASingleSpace['public'])) { + $this->fixTokenMapFollowedByASingleSpace['constructor_public'] = CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC; + } + + if (isset($this->fixTokenMapFollowedByASingleSpace['protected'])) { + $this->fixTokenMapFollowedByASingleSpace['constructor_protected'] = CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED; + } + + if (isset($this->fixTokenMapFollowedByASingleSpace['private'])) { + $this->fixTokenMapFollowedByASingleSpace['constructor_private'] = CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE; + } + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Ensures a single space after language constructs.', + [ + new CodeSample( + ' [ + 'yield_from', + ], + 'constructs_followed_by_a_single_space' => [ + 'yield_from', + ], + ] + ), + + new CodeSample( + ' [ + 'use_lambda', + ], + 'constructs_followed_by_a_single_space' => [ + 'use_lambda', + ], + ] + ), + new CodeSample( + ' [ + 'echo', + ], + ] + ), + new CodeSample( + ' [ + 'yield_from', + ], + ] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before BracesFixer, FunctionDeclarationFixer, NullableTypeDeclarationFixer. + * Must run after ArraySyntaxFixer, ModernizeStrposFixer. + */ + public function getPriority(): int + { + return 36; + } + + public function isCandidate(Tokens $tokens): bool + { + $tokenKinds = [ + ...array_values($this->fixTokenMapContainASingleSpace), + ...array_values($this->fixTokenMapPrecededByASingleSpace), + ...array_values($this->fixTokenMapFollowedByASingleSpace), + ]; + + return $tokens->isAnyTokenKindsFound($tokenKinds) && !$tokens->hasAlternativeSyntax(); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokenKindsContainASingleSpace = array_values($this->fixTokenMapContainASingleSpace); + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind($tokenKindsContainASingleSpace)) { + $token = $tokens[$index]; + + if ( + $token->isGivenKind(T_YIELD_FROM) + && 'yield from' !== strtolower($token->getContent()) + ) { + $tokens[$index] = new Token([T_YIELD_FROM, Preg::replace( + '/\s+/', + ' ', + $token->getContent() + )]); + } + } + } + + $tokenKindsPrecededByASingleSpace = array_values($this->fixTokenMapPrecededByASingleSpace); + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind($tokenKindsPrecededByASingleSpace)) { + $tokens->ensureWhitespaceAtIndex($index - 1, 1, ' '); + } + } + + $tokenKindsFollowedByASingleSpace = array_values($this->fixTokenMapFollowedByASingleSpace); + + for ($index = $tokens->count() - 2; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind($tokenKindsFollowedByASingleSpace)) { + continue; + } + + $whitespaceTokenIndex = $index + 1; + + if ($tokens[$whitespaceTokenIndex]->equalsAny([',', ';', ')', [CT::T_ARRAY_SQUARE_BRACE_CLOSE], [CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE]])) { + continue; + } + + if ( + $token->isGivenKind(T_STATIC) + && !$tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind([T_FN, T_FUNCTION, T_NS_SEPARATOR, T_STRING, T_VARIABLE, CT::T_ARRAY_TYPEHINT, CT::T_NULLABLE_TYPE]) + ) { + continue; + } + + if ($token->isGivenKind(T_OPEN_TAG)) { + if ($tokens[$whitespaceTokenIndex]->equals([T_WHITESPACE]) && !str_contains($tokens[$whitespaceTokenIndex]->getContent(), "\n") && !str_contains($token->getContent(), "\n")) { + $tokens->clearAt($whitespaceTokenIndex); + } + + continue; + } + + if ($token->isGivenKind(T_CLASS) && $tokens[$tokens->getNextMeaningfulToken($index)]->equals('(')) { + continue; + } + + if ($token->isGivenKind([T_EXTENDS, T_IMPLEMENTS]) && $this->isMultilineExtendsOrImplementsWithMoreThanOneAncestor($tokens, $index)) { + continue; + } + + if ($token->isGivenKind(T_RETURN) && $this->isMultiLineReturn($tokens, $index)) { + continue; + } + + if ($token->isGivenKind(T_CONST) && $this->isMultilineConstant($tokens, $index)) { + continue; + } + + if ($token->isComment() || $token->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + if ($tokens[$whitespaceTokenIndex]->equals([T_WHITESPACE]) && str_contains($tokens[$whitespaceTokenIndex]->getContent(), "\n")) { + continue; + } + } + + $tokens->ensureWhitespaceAtIndex($whitespaceTokenIndex, 0, ' '); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $tokenMapContainASingleSpaceKeys = array_keys(self::$tokenMapContainASingleSpace); + $tokenMapPrecededByASingleSpaceKeys = array_keys(self::$tokenMapPrecededByASingleSpace); + $tokenMapFollowedByASingleSpaceKeys = array_keys(self::$tokenMapFollowedByASingleSpace); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('constructs_contain_a_single_space', 'List of constructs which must contain a single space.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset($tokenMapContainASingleSpaceKeys)]) + ->setDefault($tokenMapContainASingleSpaceKeys) + ->getOption(), + (new FixerOptionBuilder('constructs_preceded_by_a_single_space', 'List of constructs which must be preceded by a single space.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset($tokenMapPrecededByASingleSpaceKeys)]) + ->setDefault($tokenMapPrecededByASingleSpaceKeys) + ->getOption(), + (new FixerOptionBuilder('constructs_followed_by_a_single_space', 'List of constructs which must be followed by a single space.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset($tokenMapFollowedByASingleSpaceKeys)]) + ->setDefault($tokenMapFollowedByASingleSpaceKeys) + ->getOption(), + ]); + } + + private function isMultiLineReturn(Tokens $tokens, int $index): bool + { + ++$index; + $tokenFollowingReturn = $tokens[$index]; + + if ( + !$tokenFollowingReturn->isGivenKind(T_WHITESPACE) + || !str_contains($tokenFollowingReturn->getContent(), "\n") + ) { + return false; + } + + $nestedCount = 0; + + for ($indexEnd = \count($tokens) - 1, ++$index; $index < $indexEnd; ++$index) { + if (str_contains($tokens[$index]->getContent(), "\n")) { + return true; + } + + if ($tokens[$index]->equals('{')) { + ++$nestedCount; + } elseif ($tokens[$index]->equals('}')) { + --$nestedCount; + } elseif (0 === $nestedCount && $tokens[$index]->equalsAny([';', [T_CLOSE_TAG]])) { + break; + } + } + + return false; + } + + private function isMultilineExtendsOrImplementsWithMoreThanOneAncestor(Tokens $tokens, int $index): bool + { + $hasMoreThanOneAncestor = false; + + while (++$index) { + $token = $tokens[$index]; + + if ($token->equals(',')) { + $hasMoreThanOneAncestor = true; + + continue; + } + + if ($token->equals('{')) { + return false; + } + + if ($hasMoreThanOneAncestor && str_contains($token->getContent(), "\n")) { + return true; + } + } + + return false; + } + + private function isMultilineConstant(Tokens $tokens, int $index): bool + { + $scopeEnd = $tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]) - 1; + $hasMoreThanOneConstant = null !== $tokens->findSequence([new Token(',')], $index + 1, $scopeEnd); + + return $hasMoreThanOneConstant && $tokens->isPartialCodeMultiline($index, $scopeEnd); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ListNotation/ListSyntaxFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ListNotation/ListSyntaxFixer.php new file mode 100644 index 00000000..f7f06bca --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ListNotation/ListSyntaxFixer.php @@ -0,0 +1,130 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ListNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class ListSyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var null|int + */ + private $candidateTokenKind; + + /** + * @param array{syntax: 'long'|'short'} $configuration + * + * @throws InvalidFixerConfigurationException + */ + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->candidateTokenKind = 'long' === $this->configuration['syntax'] ? CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN : T_LIST; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'List (`array` destructuring) assignment should be declared using the configured syntax. Requires PHP >= 7.1.', + [ + new CodeSample( + " 'long'] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer, TernaryOperatorSpacesFixer. + */ + public function getPriority(): int + { + return 1; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound($this->candidateTokenKind); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + if ($tokens[$index]->isGivenKind($this->candidateTokenKind)) { + if (T_LIST === $this->candidateTokenKind) { + $this->fixToShortSyntax($tokens, $index); + } else { + $this->fixToLongSyntax($tokens, $index); + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('syntax', 'Whether to use the `long` or `short` syntax for array destructuring.')) + ->setAllowedValues(['long', 'short']) + ->setDefault('short') + ->getOption(), + ]); + } + + private function fixToLongSyntax(Tokens $tokens, int $index): void + { + static $typesOfInterest = [ + [CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE], + '[', // [CT::T_ARRAY_SQUARE_BRACE_OPEN], + ]; + + $closeIndex = $tokens->getNextTokenOfKind($index, $typesOfInterest); + if (!$tokens[$closeIndex]->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE)) { + return; + } + + $tokens[$index] = new Token('('); + $tokens[$closeIndex] = new Token(')'); + $tokens->insertAt($index, new Token([T_LIST, 'list'])); + } + + private function fixToShortSyntax(Tokens $tokens, int $index): void + { + $openIndex = $tokens->getNextTokenOfKind($index, ['(']); + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); + + $tokens[$openIndex] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, '[']); + $tokens[$closeIndex] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ']']); + + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php new file mode 100644 index 00000000..7c27bef6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php @@ -0,0 +1,127 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶3. + * + * @author Dariusz Rumiński + */ +final class BlankLineAfterNamespaceFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There MUST be one blank line after the namespace declaration.', + [ + new CodeSample("isTokenKindFound(T_NAMESPACE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $lastIndex = $tokens->count() - 1; + + for ($index = $lastIndex; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(T_NAMESPACE)) { + continue; + } + + $semicolonIndex = $tokens->getNextTokenOfKind($index, [';', '{', [T_CLOSE_TAG]]); + $semicolonToken = $tokens[$semicolonIndex]; + + if (!$semicolonToken->equals(';')) { + continue; + } + + $indexToEnsureBlankLineAfter = $this->getIndexToEnsureBlankLineAfter($tokens, $semicolonIndex); + $indexToEnsureBlankLine = $tokens->getNonEmptySibling($indexToEnsureBlankLineAfter, 1); + + if (null !== $indexToEnsureBlankLine && $tokens[$indexToEnsureBlankLine]->isWhitespace()) { + $tokens[$indexToEnsureBlankLine] = $this->getTokenToInsert($tokens[$indexToEnsureBlankLine]->getContent(), $indexToEnsureBlankLine === $lastIndex); + } else { + $tokens->insertAt($indexToEnsureBlankLineAfter + 1, $this->getTokenToInsert('', $indexToEnsureBlankLineAfter === $lastIndex)); + } + } + } + + private function getIndexToEnsureBlankLineAfter(Tokens $tokens, int $index): int + { + $indexToEnsureBlankLine = $index; + $nextIndex = $tokens->getNonEmptySibling($indexToEnsureBlankLine, 1); + + while (null !== $nextIndex) { + $token = $tokens[$nextIndex]; + + if ($token->isWhitespace()) { + if (Preg::match('/\R/', $token->getContent())) { + break; + } + $nextNextIndex = $tokens->getNonEmptySibling($nextIndex, 1); + + if (!$tokens[$nextNextIndex]->isComment()) { + break; + } + } + + if (!$token->isWhitespace() && !$token->isComment()) { + break; + } + + $indexToEnsureBlankLine = $nextIndex; + $nextIndex = $tokens->getNonEmptySibling($indexToEnsureBlankLine, 1); + } + + return $indexToEnsureBlankLine; + } + + private function getTokenToInsert(string $currentContent, bool $isLastIndex): Token + { + $ending = $this->whitespacesConfig->getLineEnding(); + + $emptyLines = $isLastIndex ? $ending : $ending.$ending; + $indent = Preg::match('/^.*\R( *)$/s', $currentContent, $matches) ? $matches[1] : ''; + + return new Token([T_WHITESPACE, $emptyLines.$indent]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixer.php new file mode 100644 index 00000000..162bc65f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixer.php @@ -0,0 +1,227 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Options; + +/** + * @author Graham Campbell + * @author Greg Korba + */ +final class BlankLinesBeforeNamespaceFixer extends AbstractFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Controls blank lines before a namespace declaration.', + [ + new CodeSample(" 1]), + new CodeSample(" 2]), + new CodeSample(" 2]), + new CodeSample(" 0, 'max_line_breaks' => 0]), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_NAMESPACE); + } + + /** + * {@inheritdoc} + * + * Must run after BlankLineAfterOpeningTagFixer, HeaderCommentFixer. + */ + public function getPriority(): int + { + return -31; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('min_line_breaks', 'Minimum line breaks that should exist before namespace declaration.')) + ->setAllowedTypes(['int']) + ->setDefault(2) + ->setNormalizer(static function (Options $options, $value): int { + if ($value < 0) { + throw new InvalidFixerConfigurationException( + (new self())->getName(), + 'Option `min_line_breaks` cannot be lower than 0.' + ); + } + + return $value; + }) + ->getOption(), + (new FixerOptionBuilder('max_line_breaks', 'Maximum line breaks that should exist before namespace declaration.')) + ->setAllowedTypes(['int']) + ->setDefault(2) + ->setNormalizer(static function (Options $options, $value): int { + if ($value < 0) { + throw new InvalidFixerConfigurationException( + (new self())->getName(), + 'Option `max_line_breaks` cannot be lower than 0.' + ); + } + + if ($value < $options['min_line_breaks']) { + throw new InvalidFixerConfigurationException( + (new self())->getName(), + 'Option `max_line_breaks` cannot have lower value than `min_line_breaks`.' + ); + } + + return $value; + }) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(T_NAMESPACE)) { + $this->fixLinesBeforeNamespace( + $tokens, + $index, + $this->configuration['min_line_breaks'], + $this->configuration['max_line_breaks'] + ); + } + } + } + + /** + * Make sure # of line breaks prefixing namespace is within given range. + * + * @param int $expectedMin min. # of line breaks + * @param int $expectedMax max. # of line breaks + */ + protected function fixLinesBeforeNamespace(Tokens $tokens, int $index, int $expectedMin, int $expectedMax): void + { + // Let's determine the total numbers of new lines before the namespace + // and the opening token + $openingTokenIndex = null; + $precedingNewlines = 0; + $newlineInOpening = false; + $openingToken = null; + + for ($i = 1; $i <= 2; ++$i) { + if (isset($tokens[$index - $i])) { + $token = $tokens[$index - $i]; + + if ($token->isGivenKind(T_OPEN_TAG)) { + $openingToken = $token; + $openingTokenIndex = $index - $i; + $newlineInOpening = str_contains($token->getContent(), "\n"); + + if ($newlineInOpening) { + ++$precedingNewlines; + } + + break; + } + + if (false === $token->isGivenKind(T_WHITESPACE)) { + break; + } + + $precedingNewlines += substr_count($token->getContent(), "\n"); + } + } + + if ($precedingNewlines >= $expectedMin && $precedingNewlines <= $expectedMax) { + return; + } + + $previousIndex = $index - 1; + $previous = $tokens[$previousIndex]; + + if (0 === $expectedMax) { + // Remove all the previous new lines + if ($previous->isWhitespace()) { + $tokens->clearAt($previousIndex); + } + + // Remove new lines in opening token + if ($newlineInOpening) { + $tokens[$openingTokenIndex] = new Token([T_OPEN_TAG, rtrim($openingToken->getContent()).' ']); + } + + return; + } + + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + // Allow only as many line breaks as configured: + // - keep as-is when current preceding line breaks are within configured range + // - use configured max line breaks if currently there is more preceding line breaks + // - use configured min line breaks if currently there is less preceding line breaks + $newlinesForWhitespaceToken = $precedingNewlines >= $expectedMax + ? $expectedMax + : max($precedingNewlines, $expectedMin); + + if (null !== $openingToken) { + // Use the configured line ending for the PHP opening tag + $content = rtrim($openingToken->getContent()); + $newContent = $content.$lineEnding; + $tokens[$openingTokenIndex] = new Token([T_OPEN_TAG, $newContent]); + --$newlinesForWhitespaceToken; + } + + if (0 === $newlinesForWhitespaceToken) { + // We have all the needed new lines in the opening tag + if ($previous->isWhitespace()) { + // Let's remove the previous token containing extra new lines + $tokens->clearAt($previousIndex); + } + + return; + } + + if ($previous->isWhitespace()) { + // Fix the previous whitespace token + $tokens[$previousIndex] = new Token( + [ + T_WHITESPACE, + str_repeat($lineEnding, $newlinesForWhitespaceToken).substr( + $previous->getContent(), + strrpos($previous->getContent(), "\n") + 1 + ), + ] + ); + } else { + // Add a new whitespace token + $tokens->insertAt($index, new Token([T_WHITESPACE, str_repeat($lineEnding, $newlinesForWhitespaceToken)])); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/CleanNamespaceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/CleanNamespaceFixer.php new file mode 100644 index 00000000..f39ed81d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/CleanNamespaceFixer.php @@ -0,0 +1,108 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Tokens; + +final class CleanNamespaceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + $samples = []; + + foreach (['namespace Foo \\ Bar;', 'echo foo /* comment */ \\ bar();'] as $sample) { + $samples[] = new VersionSpecificCodeSample( + "isTokenKindFound(T_NS_SEPARATOR); + } + + /** + * {@inheritdoc} + * + * Must run before PhpUnitDataProviderReturnTypeFixer. + */ + public function getPriority(): int + { + return 3; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $count = $tokens->count(); + + for ($index = 0; $index < $count; ++$index) { + if ($tokens[$index]->isGivenKind(T_NS_SEPARATOR)) { + $previousIndex = $tokens->getPrevMeaningfulToken($index); + + $index = $this->fixNamespace( + $tokens, + $tokens[$previousIndex]->isGivenKind(T_STRING) ? $previousIndex : $index + ); + } + } + } + + /** + * @param int $index start of namespace + */ + private function fixNamespace(Tokens $tokens, int $index): int + { + $tillIndex = $index; + + // go to the end of the namespace + while ($tokens[$tillIndex]->isGivenKind([T_NS_SEPARATOR, T_STRING])) { + $tillIndex = $tokens->getNextMeaningfulToken($tillIndex); + } + + $tillIndex = $tokens->getPrevMeaningfulToken($tillIndex); + + $spaceIndices = []; + + for (; $index <= $tillIndex; ++$index) { + if ($tokens[$index]->isGivenKind(T_WHITESPACE)) { + $spaceIndices[] = $index; + } elseif ($tokens[$index]->isComment()) { + $tokens->clearAt($index); + } + } + + if ($tokens[$index - 1]->isWhitespace()) { + array_pop($spaceIndices); + } + + foreach ($spaceIndices as $i) { + $tokens->clearAt($i); + } + + return $index; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php new file mode 100644 index 00000000..20dc38ea --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php @@ -0,0 +1,76 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + * + * @deprecated Use `blank_lines_before_namespace` with config: ['min_line_breaks' => 0, 'max_line_breaks' => 1] + */ +final class NoBlankLinesBeforeNamespaceFixer extends AbstractProxyFixer implements WhitespacesAwareFixerInterface, DeprecatedFixerInterface +{ + public function getSuccessorsNames(): array + { + return array_keys($this->proxyFixers); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_NAMESPACE); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should be no blank lines before a namespace declaration.', + [ + new CodeSample( + "configure([ + 'min_line_breaks' => 0, + 'max_line_breaks' => 1, + ]); + + return [ + $blankLineBeforeNamespace, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php new file mode 100644 index 00000000..0d866d4a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php @@ -0,0 +1,95 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Bram Gotink + * @author Dariusz Rumiński + */ +final class NoLeadingNamespaceWhitespaceFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_NAMESPACE); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The namespace declaration line shouldn\'t contain leading whitespace.', + [ + new CodeSample( + 'isGivenKind(T_NAMESPACE)) { + continue; + } + + $beforeNamespaceIndex = $index - 1; + $beforeNamespace = $tokens[$beforeNamespaceIndex]; + + if (!$beforeNamespace->isWhitespace()) { + if (!self::endsWithWhitespace($beforeNamespace->getContent())) { + $tokens->insertAt($index, new Token([T_WHITESPACE, $this->whitespacesConfig->getLineEnding()])); + } + + continue; + } + + $lastNewline = strrpos($beforeNamespace->getContent(), "\n"); + + if (false === $lastNewline) { + $beforeBeforeNamespace = $tokens[$index - 2]; + + if (self::endsWithWhitespace($beforeBeforeNamespace->getContent())) { + $tokens->clearAt($beforeNamespaceIndex); + } else { + $tokens[$beforeNamespaceIndex] = new Token([T_WHITESPACE, ' ']); + } + } else { + $tokens[$beforeNamespaceIndex] = new Token([T_WHITESPACE, substr($beforeNamespace->getContent(), 0, $lastNewline + 1)]); + } + } + } + + private static function endsWithWhitespace(string $str): bool + { + if ('' === $str) { + return false; + } + + return '' === trim(substr($str, -1)); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php new file mode 100644 index 00000000..67de6a24 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php @@ -0,0 +1,75 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + * + * @deprecated Use `blank_lines_before_namespace` with config: ['min_line_breaks' => 2, 'max_line_breaks' => 2] (default) + */ +final class SingleBlankLineBeforeNamespaceFixer extends AbstractProxyFixer implements WhitespacesAwareFixerInterface, DeprecatedFixerInterface +{ + public function getSuccessorsNames(): array + { + return array_keys($this->proxyFixers); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should be exactly one blank line before a namespace declaration.', + [ + new CodeSample("isTokenKindFound(T_NAMESPACE); + } + + /** + * {@inheritdoc} + * + * Must run after HeaderCommentFixer. + */ + public function getPriority(): int + { + return parent::getPriority(); + } + + protected function createProxyFixers(): array + { + $blankLineBeforeNamespace = new BlankLinesBeforeNamespaceFixer(); + $blankLineBeforeNamespace->configure([ + 'min_line_breaks' => 2, + 'max_line_breaks' => 2, + ]); + + return [ + $blankLineBeforeNamespace, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Naming/NoHomoglyphNamesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Naming/NoHomoglyphNamesFixer.php new file mode 100644 index 00000000..55c5ffda --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Naming/NoHomoglyphNamesFixer.php @@ -0,0 +1,230 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Naming; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Fred Cox + * @author Dariusz Rumiński + */ +final class NoHomoglyphNamesFixer extends AbstractFixer +{ + /** + * Used the program https://github.com/mcfedr/homoglyph-download + * to generate this list from + * http://homoglyphs.net/?text=abcdefghijklmnopqrstuvwxyz&lang=en&exc7=1&exc8=1&exc13=1&exc14=1. + * + * Symbols replaced include + * - Latin homoglyphs + * - IPA extensions + * - Greek and Coptic + * - Cyrillic + * - Cyrillic Supplement + * - Letterlike Symbols + * - Latin Numbers + * - Fullwidth Latin + * + * This is not the complete list of unicode homographs, but limited + * to those you are more likely to have typed/copied by accident + * + * @var array + */ + private static array $replacements = [ + 'O' => '0', + '0' => '0', + 'I' => '1', + '1' => '1', + '2' => '2', + '3' => '3', + '4' => '4', + '5' => '5', + '6' => '6', + '7' => '7', + '8' => '8', + '9' => '9', + 'Α' => 'A', + 'А' => 'A', + 'A' => 'A', + 'ʙ' => 'B', + 'Β' => 'B', + 'В' => 'B', + 'B' => 'B', + 'Ϲ' => 'C', + 'С' => 'C', + 'Ⅽ' => 'C', + 'C' => 'C', + 'Ⅾ' => 'D', + 'D' => 'D', + 'Ε' => 'E', + 'Е' => 'E', + 'E' => 'E', + 'Ϝ' => 'F', + 'F' => 'F', + 'ɢ' => 'G', + 'Ԍ' => 'G', + 'G' => 'G', + 'ʜ' => 'H', + 'Η' => 'H', + 'Н' => 'H', + 'H' => 'H', + 'l' => 'I', + 'Ι' => 'I', + 'І' => 'I', + 'Ⅰ' => 'I', + 'I' => 'I', + 'Ј' => 'J', + 'J' => 'J', + 'Κ' => 'K', + 'К' => 'K', + 'K' => 'K', + 'K' => 'K', + 'ʟ' => 'L', + 'Ⅼ' => 'L', + 'L' => 'L', + 'Μ' => 'M', + 'М' => 'M', + 'Ⅿ' => 'M', + 'M' => 'M', + 'ɴ' => 'N', + 'Ν' => 'N', + 'N' => 'N', + 'Ο' => 'O', + 'О' => 'O', + 'O' => 'O', + 'Ρ' => 'P', + 'Р' => 'P', + 'P' => 'P', + 'Q' => 'Q', + 'ʀ' => 'R', + 'R' => 'R', + 'Ѕ' => 'S', + 'S' => 'S', + 'Τ' => 'T', + 'Т' => 'T', + 'T' => 'T', + 'U' => 'U', + 'Ѵ' => 'V', + 'Ⅴ' => 'V', + 'V' => 'V', + 'W' => 'W', + 'Χ' => 'X', + 'Х' => 'X', + 'Ⅹ' => 'X', + 'X' => 'X', + 'ʏ' => 'Y', + 'Υ' => 'Y', + 'Ү' => 'Y', + 'Y' => 'Y', + 'Ζ' => 'Z', + 'Z' => 'Z', + '_' => '_', + 'ɑ' => 'a', + 'а' => 'a', + 'a' => 'a', + 'Ь' => 'b', + 'b' => 'b', + 'ϲ' => 'c', + 'с' => 'c', + 'ⅽ' => 'c', + 'c' => 'c', + 'ԁ' => 'd', + 'ⅾ' => 'd', + 'd' => 'd', + 'е' => 'e', + 'e' => 'e', + 'f' => 'f', + 'ɡ' => 'g', + 'g' => 'g', + 'һ' => 'h', + 'h' => 'h', + 'ɩ' => 'i', + 'і' => 'i', + 'ⅰ' => 'i', + 'i' => 'i', + 'ј' => 'j', + 'j' => 'j', + 'k' => 'k', + 'ⅼ' => 'l', + 'l' => 'l', + 'ⅿ' => 'm', + 'm' => 'm', + 'n' => 'n', + 'ο' => 'o', + 'о' => 'o', + 'o' => 'o', + 'р' => 'p', + 'p' => 'p', + 'q' => 'q', + 'r' => 'r', + 'ѕ' => 's', + 's' => 's', + 't' => 't', + 'u' => 'u', + 'ν' => 'v', + 'ѵ' => 'v', + 'ⅴ' => 'v', + 'v' => 'v', + 'ѡ' => 'w', + 'w' => 'w', + 'х' => 'x', + 'ⅹ' => 'x', + 'x' => 'x', + 'у' => 'y', + 'y' => 'y', + 'z' => 'z', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace accidental usage of homoglyphs (non ascii characters) in names.', + [new CodeSample("isAnyTokenKindsFound([T_VARIABLE, T_STRING]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind([T_VARIABLE, T_STRING])) { + continue; + } + + $replaced = Preg::replaceCallback('/[^[:ascii:]]/u', static fn (array $matches): string => self::$replacements[$matches[0]] ?? $matches[0], $token->getContent(), -1, $count); + + if ($count) { + $tokens->offsetSet($index, new Token([$token->getId(), $replaced])); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/AssignNullCoalescingToCoalesceEqualFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/AssignNullCoalescingToCoalesceEqualFixer.php new file mode 100644 index 00000000..b1c37606 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/AssignNullCoalescingToCoalesceEqualFixer.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\Fixer\AbstractShortOperatorFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class AssignNullCoalescingToCoalesceEqualFixer extends AbstractShortOperatorFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Use the null coalescing assignment operator `??=` where possible.', + [ + new CodeSample( + "isTokenKindFound(T_COALESCE); + } + + protected function isOperatorTokenCandidate(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->isGivenKind(T_COALESCE)) { + return false; + } + + // make sure after '??' does not contain '? :' + + $nextIndex = $tokens->getNextTokenOfKind($index, ['?', ';', [T_CLOSE_TAG]]); + + return !$tokens[$nextIndex]->equals('?'); + } + + protected function getReplacementToken(Token $token): Token + { + return new Token([T_COALESCE_EQUAL, '??=']); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/BinaryOperatorSpacesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/BinaryOperatorSpacesFixer.php new file mode 100644 index 00000000..3f95b189 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/BinaryOperatorSpacesFixer.php @@ -0,0 +1,938 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @author Dariusz Rumiński + */ +final class BinaryOperatorSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const SINGLE_SPACE = 'single_space'; + + /** + * @internal + */ + public const AT_LEAST_SINGLE_SPACE = 'at_least_single_space'; + + /** + * @internal + */ + public const NO_SPACE = 'no_space'; + + /** + * @internal + */ + public const ALIGN = 'align'; + + /** + * @internal + */ + public const ALIGN_BY_SCOPE = 'align_by_scope'; + + /** + * @internal + */ + public const ALIGN_SINGLE_SPACE = 'align_single_space'; + + /** + * @internal + */ + public const ALIGN_SINGLE_SPACE_BY_SCOPE = 'align_single_space_by_scope'; + + /** + * @internal + */ + public const ALIGN_SINGLE_SPACE_MINIMAL = 'align_single_space_minimal'; + + /** + * @internal + */ + public const ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE = 'align_single_space_minimal_by_scope'; + + /** + * @internal + * + * @const Placeholder used as anchor for right alignment. + */ + public const ALIGN_PLACEHOLDER = "\x2 ALIGNABLE%d \x3"; + + /** + * @var string[] + */ + private const SUPPORTED_OPERATORS = [ + '=', + '*', + '/', + '%', + '<', + '>', + '|', + '^', + '+', + '-', + '&', + '&=', + '&&', + '||', + '.=', + '/=', + '=>', + '==', + '>=', + '===', + '!=', + '<>', + '!==', + '<=', + 'and', + 'or', + 'xor', + '-=', + '%=', + '*=', + '|=', + '+=', + '<<', + '<<=', + '>>', + '>>=', + '^=', + '**', + '**=', + '<=>', + '??', + '??=', + ]; + + /** + * Keep track of the deepest level ever achieved while + * parsing the code. Used later to replace alignment + * placeholders with spaces. + */ + private int $deepestLevel; + + /** + * Level counter of the current nest level. + * So one level alignments are not mixed with + * other level ones. + */ + private int $currentLevel; + + /** + * @var array + */ + private static array $allowedValues = [ + self::ALIGN, + self::ALIGN_BY_SCOPE, + self::ALIGN_SINGLE_SPACE, + self::ALIGN_SINGLE_SPACE_MINIMAL, + self::ALIGN_SINGLE_SPACE_BY_SCOPE, + self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE, + self::SINGLE_SPACE, + self::NO_SPACE, + self::AT_LEAST_SINGLE_SPACE, + null, + ]; + + private TokensAnalyzer $tokensAnalyzer; + + /** + * @var array + */ + private array $alignOperatorTokens = []; + + /** + * @var array + */ + private array $operators = []; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->operators = $this->resolveOperatorsFromConfig(); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Binary operators should be surrounded by space as configured.', + [ + new CodeSample( + " ['=' => 'align', 'xor' => null]] + ), + new CodeSample( + ' ['+=' => 'align_single_space']] + ), + new CodeSample( + ' ['===' => 'align_single_space_minimal']] + ), + new CodeSample( + ' ['|' => 'no_space']] + ), + new CodeSample( + ' 1, + "baaaaaaaaaaar" => 11, +]; +', + ['operators' => ['=>' => 'single_space']] + ), + new CodeSample( + ' 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, +]; +', + ['operators' => ['=>' => 'align']] + ), + new CodeSample( + ' 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, +]; +', + ['operators' => ['=>' => 'align_by_scope']] + ), + new CodeSample( + ' 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, +]; +', + ['operators' => ['=>' => 'align_single_space']] + ), + new CodeSample( + ' 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, +]; +', + ['operators' => ['=>' => 'align_single_space_by_scope']] + ), + new CodeSample( + ' 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, +]; +', + ['operators' => ['=>' => 'align_single_space_minimal']] + ), + new CodeSample( + ' 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, +]; +', + ['operators' => ['=>' => 'align_single_space_minimal_by_scope']] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run after ArrayIndentationFixer, ArraySyntaxFixer, AssignNullCoalescingToCoalesceEqualFixer, ListSyntaxFixer, LongToShorthandOperatorFixer, ModernizeStrposFixer, NoMultilineWhitespaceAroundDoubleArrowFixer, NoUnsetCastFixer, PowToExponentiationFixer, StandardizeNotEqualsFixer, StrictComparisonFixer. + */ + public function getPriority(): int + { + return -32; + } + + public function isCandidate(Tokens $tokens): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + + // last and first tokens cannot be an operator + for ($index = $tokens->count() - 2; $index > 0; --$index) { + if (!$this->tokensAnalyzer->isBinaryOperator($index)) { + continue; + } + + if ('=' === $tokens[$index]->getContent()) { + $isDeclare = $this->isEqualPartOfDeclareStatement($tokens, $index); + if (false === $isDeclare) { + $this->fixWhiteSpaceAroundOperator($tokens, $index); + } else { + $index = $isDeclare; // skip `declare(foo ==bar)`, see `declare_equal_normalize` + } + } else { + $this->fixWhiteSpaceAroundOperator($tokens, $index); + } + + // previous of binary operator is now never an operator / previous of declare statement cannot be an operator + --$index; + } + + if (\count($this->alignOperatorTokens) > 0) { + $this->fixAlignment($tokens, $this->alignOperatorTokens); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('default', 'Default fix strategy.')) + ->setDefault(self::SINGLE_SPACE) + ->setAllowedValues(self::$allowedValues) + ->getOption(), + (new FixerOptionBuilder('operators', 'Dictionary of `binary operator` => `fix strategy` values that differ from the default strategy. Supported are: '.Utils::naturalLanguageJoinWithBackticks(self::SUPPORTED_OPERATORS).'.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([static function (array $option): bool { + foreach ($option as $operator => $value) { + if (!\in_array($operator, self::SUPPORTED_OPERATORS, true)) { + throw new InvalidOptionsException( + sprintf( + 'Unexpected "operators" key, expected any of %s, got "%s".', + Utils::naturalLanguageJoin(self::SUPPORTED_OPERATORS), + \gettype($operator).'#'.$operator + ) + ); + } + + if (!\in_array($value, self::$allowedValues, true)) { + throw new InvalidOptionsException( + sprintf( + 'Unexpected value for operator "%s", expected any of %s, got "%s".', + $operator, + Utils::naturalLanguageJoin(array_map( + static fn ($value): string => Utils::toString($value), + self::$allowedValues + )), + \is_object($value) ? \get_class($value) : (null === $value ? 'null' : \gettype($value).'#'.$value) + ) + ); + } + } + + return true; + }]) + ->setDefault([]) + ->getOption(), + ]); + } + + private function fixWhiteSpaceAroundOperator(Tokens $tokens, int $index): void + { + $tokenContent = strtolower($tokens[$index]->getContent()); + + if (!\array_key_exists($tokenContent, $this->operators)) { + return; // not configured to be changed + } + + if (self::SINGLE_SPACE === $this->operators[$tokenContent]) { + $this->fixWhiteSpaceAroundOperatorToSingleSpace($tokens, $index); + + return; + } + + if (self::AT_LEAST_SINGLE_SPACE === $this->operators[$tokenContent]) { + $this->fixWhiteSpaceAroundOperatorToAtLeastSingleSpace($tokens, $index); + + return; + } + + if (self::NO_SPACE === $this->operators[$tokenContent]) { + $this->fixWhiteSpaceAroundOperatorToNoSpace($tokens, $index); + + return; + } + + // schedule for alignment + $this->alignOperatorTokens[$tokenContent] = $this->operators[$tokenContent]; + + if ( + self::ALIGN === $this->operators[$tokenContent] + || self::ALIGN_BY_SCOPE === $this->operators[$tokenContent] + ) { + return; + } + + // fix white space after operator + if ($tokens[$index + 1]->isWhitespace()) { + if ( + self::ALIGN_SINGLE_SPACE_MINIMAL === $this->operators[$tokenContent] + || self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE === $this->operators[$tokenContent] + ) { + $tokens[$index + 1] = new Token([T_WHITESPACE, ' ']); + } + + return; + } + + $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); + } + + private function fixWhiteSpaceAroundOperatorToSingleSpace(Tokens $tokens, int $index): void + { + // fix white space after operator + if ($tokens[$index + 1]->isWhitespace()) { + $content = $tokens[$index + 1]->getContent(); + if (' ' !== $content && !str_contains($content, "\n") && !$tokens[$tokens->getNextNonWhitespace($index + 1)]->isComment()) { + $tokens[$index + 1] = new Token([T_WHITESPACE, ' ']); + } + } else { + $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); + } + + // fix white space before operator + if ($tokens[$index - 1]->isWhitespace()) { + $content = $tokens[$index - 1]->getContent(); + if (' ' !== $content && !str_contains($content, "\n") && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { + $tokens[$index - 1] = new Token([T_WHITESPACE, ' ']); + } + } else { + $tokens->insertAt($index, new Token([T_WHITESPACE, ' '])); + } + } + + private function fixWhiteSpaceAroundOperatorToAtLeastSingleSpace(Tokens $tokens, int $index): void + { + // fix white space after operator + if (!$tokens[$index + 1]->isWhitespace()) { + $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); + } + + // fix white space before operator + if (!$tokens[$index - 1]->isWhitespace()) { + $tokens->insertAt($index, new Token([T_WHITESPACE, ' '])); + } + } + + private function fixWhiteSpaceAroundOperatorToNoSpace(Tokens $tokens, int $index): void + { + // fix white space after operator + if ($tokens[$index + 1]->isWhitespace()) { + $content = $tokens[$index + 1]->getContent(); + if (!str_contains($content, "\n") && !$tokens[$tokens->getNextNonWhitespace($index + 1)]->isComment()) { + $tokens->clearAt($index + 1); + } + } + + // fix white space before operator + if ($tokens[$index - 1]->isWhitespace()) { + $content = $tokens[$index - 1]->getContent(); + if (!str_contains($content, "\n") && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { + $tokens->clearAt($index - 1); + } + } + } + + /** + * @return false|int index of T_DECLARE where the `=` belongs to or `false` + */ + private function isEqualPartOfDeclareStatement(Tokens $tokens, int $index) + { + $prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevMeaningfulIndex]->isGivenKind(T_STRING)) { + $prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulIndex); + if ($tokens[$prevMeaningfulIndex]->equals('(')) { + $prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulIndex); + if ($tokens[$prevMeaningfulIndex]->isGivenKind(T_DECLARE)) { + return $prevMeaningfulIndex; + } + } + } + + return false; + } + + /** + * @return array + */ + private function resolveOperatorsFromConfig(): array + { + $operators = []; + + if (null !== $this->configuration['default']) { + foreach (self::SUPPORTED_OPERATORS as $operator) { + $operators[$operator] = $this->configuration['default']; + } + } + + foreach ($this->configuration['operators'] as $operator => $value) { + if (null === $value) { + unset($operators[$operator]); + } else { + $operators[$operator] = $value; + } + } + + return $operators; + } + + // Alignment logic related methods + + /** + * @param array $toAlign + */ + private function fixAlignment(Tokens $tokens, array $toAlign): void + { + $this->deepestLevel = 0; + $this->currentLevel = 0; + + foreach ($toAlign as $tokenContent => $alignStrategy) { + // This fixer works partially on Tokens and partially on string representation of code. + // During the process of fixing internal state of single Token may be affected by injecting ALIGN_PLACEHOLDER to its content. + // The placeholder will be resolved by `replacePlaceholders` method by removing placeholder or changing it into spaces. + // That way of fixing the code causes disturbances in marking Token as changed - if code is perfectly valid then placeholder + // still be injected and removed, which will cause the `changed` flag to be set. + // To handle that unwanted behavior we work on clone of Tokens collection and then override original collection with fixed collection. + $tokensClone = clone $tokens; + + if ('=>' === $tokenContent) { + $this->injectAlignmentPlaceholdersForArrow($tokensClone, 0, \count($tokens)); + } else { + $this->injectAlignmentPlaceholdersDefault($tokensClone, 0, \count($tokens), $tokenContent); + } + + // for all tokens that should be aligned but do not have anything to align with, fix spacing if needed + if ( + self::ALIGN_SINGLE_SPACE === $alignStrategy + || self::ALIGN_SINGLE_SPACE_MINIMAL === $alignStrategy + || self::ALIGN_SINGLE_SPACE_BY_SCOPE === $alignStrategy + || self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE === $alignStrategy + ) { + if ('=>' === $tokenContent) { + for ($index = $tokens->count() - 2; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind(T_DOUBLE_ARROW)) { // always binary operator, never part of declare statement + $this->fixWhiteSpaceBeforeOperator($tokensClone, $index, $alignStrategy); + } + } + } elseif ('=' === $tokenContent) { + for ($index = $tokens->count() - 2; $index > 0; --$index) { + if ('=' === $tokens[$index]->getContent() && !$this->isEqualPartOfDeclareStatement($tokens, $index) && $this->tokensAnalyzer->isBinaryOperator($index)) { + $this->fixWhiteSpaceBeforeOperator($tokensClone, $index, $alignStrategy); + } + } + } else { + for ($index = $tokens->count() - 2; $index > 0; --$index) { + $content = $tokens[$index]->getContent(); + if (strtolower($content) === $tokenContent && $this->tokensAnalyzer->isBinaryOperator($index)) { // never part of declare statement + $this->fixWhiteSpaceBeforeOperator($tokensClone, $index, $alignStrategy); + } + } + } + } + + $tokens->setCode($this->replacePlaceholders($tokensClone, $alignStrategy, $tokenContent)); + } + } + + private function injectAlignmentPlaceholdersDefault(Tokens $tokens, int $startAt, int $endAt, string $tokenContent): void + { + $newLineFoundSinceLastPlaceholder = true; + + for ($index = $startAt; $index < $endAt; ++$index) { + $token = $tokens[$index]; + $content = $token->getContent(); + + if (str_contains($content, "\n")) { + $newLineFoundSinceLastPlaceholder = true; + } + + if ( + strtolower($content) === $tokenContent + && $this->tokensAnalyzer->isBinaryOperator($index) + && ('=' !== $content || !$this->isEqualPartOfDeclareStatement($tokens, $index)) + && $newLineFoundSinceLastPlaceholder + ) { + $tokens[$index] = new Token(sprintf(self::ALIGN_PLACEHOLDER, $this->currentLevel).$content); + $newLineFoundSinceLastPlaceholder = false; + + continue; + } + + if ($token->isGivenKind(T_FN)) { + $from = $tokens->getNextMeaningfulToken($index); + $until = $this->tokensAnalyzer->getLastTokenIndexOfArrowFunction($index); + $this->injectAlignmentPlaceholders($tokens, $from + 1, $until - 1, $tokenContent); + $index = $until; + + continue; + } + + if ($token->isGivenKind([T_FUNCTION, T_CLASS])) { + $index = $tokens->getNextTokenOfKind($index, ['{', ';', '(']); + // We don't align `=` on multi-line definition of function parameters with default values + if ($tokens[$index]->equals('(')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + + continue; + } + + if ($tokens[$index]->equals(';')) { + continue; + } + + // Update the token to the `{` one in order to apply the following logic + $token = $tokens[$index]; + } + + if ($token->equals('{')) { + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + $this->injectAlignmentPlaceholders($tokens, $index + 1, $until - 1, $tokenContent); + $index = $until; + + continue; + } + + if ($token->equals('(')) { + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $this->injectAlignmentPlaceholders($tokens, $index + 1, $until - 1, $tokenContent); + $index = $until; + + continue; + } + + if ($token->equals('[')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index); + + continue; + } + + if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); + $this->injectAlignmentPlaceholders($tokens, $index + 1, $until - 1, $tokenContent); + $index = $until; + + continue; + } + } + } + + private function injectAlignmentPlaceholders(Tokens $tokens, int $from, int $until, string $tokenContent): void + { + // Only inject placeholders for multi-line code + if ($tokens->isPartialCodeMultiline($from, $until)) { + ++$this->deepestLevel; + $currentLevel = $this->currentLevel; + $this->currentLevel = $this->deepestLevel; + $this->injectAlignmentPlaceholdersDefault($tokens, $from, $until, $tokenContent); + $this->currentLevel = $currentLevel; + } + } + + private function injectAlignmentPlaceholdersForArrow(Tokens $tokens, int $startAt, int $endAt): void + { + $newLineFoundSinceLastPlaceholder = true; + $yieldFoundSinceLastPlaceholder = false; + + for ($index = $startAt; $index < $endAt; ++$index) { + /** @var Token $token */ + $token = $tokens[$index]; + $content = $token->getContent(); + + if (str_contains($content, "\n")) { + $newLineFoundSinceLastPlaceholder = true; + } + + if ($token->isGivenKind(T_YIELD)) { + $yieldFoundSinceLastPlaceholder = true; + } + + if ($token->isGivenKind(T_FN)) { + $yieldFoundSinceLastPlaceholder = false; + $from = $tokens->getNextMeaningfulToken($index); + $until = $this->tokensAnalyzer->getLastTokenIndexOfArrowFunction($index); + $this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1); + $index = $until; + + continue; + } + + if ($token->isGivenKind(T_ARRAY)) { // don't use "$tokens->isArray()" here, short arrays are handled in the next case + $yieldFoundSinceLastPlaceholder = false; + $from = $tokens->getNextMeaningfulToken($index); + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $from); + $index = $until; + + $this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1); + + continue; + } + + if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { + $yieldFoundSinceLastPlaceholder = false; + $from = $index; + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $from); + $index = $until; + + $this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1); + + continue; + } + + // no need to analyze for `isBinaryOperator` (always true), nor if part of declare statement (not valid PHP) + // there is also no need to analyse the second arrow of a line + if ($token->isGivenKind(T_DOUBLE_ARROW) && $newLineFoundSinceLastPlaceholder) { + if ($yieldFoundSinceLastPlaceholder) { + ++$this->deepestLevel; + ++$this->currentLevel; + } + $tokenContent = sprintf(self::ALIGN_PLACEHOLDER, $this->currentLevel).$token->getContent(); + + $nextToken = $tokens[$index + 1]; + if (!$nextToken->isWhitespace()) { + $tokenContent .= ' '; + } elseif ($nextToken->isWhitespace(" \t")) { + $tokens[$index + 1] = new Token([T_WHITESPACE, ' ']); + } + + $tokens[$index] = new Token([T_DOUBLE_ARROW, $tokenContent]); + $newLineFoundSinceLastPlaceholder = false; + $yieldFoundSinceLastPlaceholder = false; + + continue; + } + + if ($token->equals(';')) { + ++$this->deepestLevel; + ++$this->currentLevel; + + continue; + } + + if ($token->equals(',')) { + for ($i = $index; $i < $endAt - 1; ++$i) { + if (str_contains($tokens[$i - 1]->getContent(), "\n")) { + $newLineFoundSinceLastPlaceholder = true; + + break; + } + + if ($tokens[$i + 1]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { + $arrayStartIndex = $tokens[$i + 1]->isGivenKind(T_ARRAY) + ? $tokens->getNextMeaningfulToken($i + 1) + : $i + 1; + $blockType = Tokens::detectBlockType($tokens[$arrayStartIndex]); + $arrayEndIndex = $tokens->findBlockEnd($blockType['type'], $arrayStartIndex); + + if ($tokens->isPartialCodeMultiline($arrayStartIndex, $arrayEndIndex)) { + break; + } + } + + ++$index; + } + } + + if ($token->equals('{')) { + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + $this->injectArrayAlignmentPlaceholders($tokens, $index + 1, $until - 1); + $index = $until; + + continue; + } + + if ($token->equals('(')) { + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $this->injectArrayAlignmentPlaceholders($tokens, $index + 1, $until - 1); + $index = $until; + + continue; + } + } + } + + private function injectArrayAlignmentPlaceholders(Tokens $tokens, int $from, int $until): void + { + // Only inject placeholders for multi-line arrays + if ($tokens->isPartialCodeMultiline($from, $until)) { + ++$this->deepestLevel; + $currentLevel = $this->currentLevel; + $this->currentLevel = $this->deepestLevel; + $this->injectAlignmentPlaceholdersForArrow($tokens, $from, $until); + $this->currentLevel = $currentLevel; + } + } + + private function fixWhiteSpaceBeforeOperator(Tokens $tokens, int $index, string $alignStrategy): void + { + // fix white space after operator is not needed as BinaryOperatorSpacesFixer took care of this (if strategy is _not_ ALIGN) + if (!$tokens[$index - 1]->isWhitespace()) { + $tokens->insertAt($index, new Token([T_WHITESPACE, ' '])); + + return; + } + + if ( + self::ALIGN_SINGLE_SPACE_MINIMAL !== $alignStrategy && self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE !== $alignStrategy + || $tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment() + ) { + return; + } + + $content = $tokens[$index - 1]->getContent(); + if (' ' !== $content && !str_contains($content, "\n")) { + $tokens[$index - 1] = new Token([T_WHITESPACE, ' ']); + } + } + + /** + * Look for group of placeholders and provide vertical alignment. + */ + private function replacePlaceholders(Tokens $tokens, string $alignStrategy, string $tokenContent): string + { + $tmpCode = $tokens->generateCode(); + + for ($j = 0; $j <= $this->deepestLevel; ++$j) { + $placeholder = sprintf(self::ALIGN_PLACEHOLDER, $j); + + if (!str_contains($tmpCode, $placeholder)) { + continue; + } + + $lines = explode("\n", $tmpCode); + $groups = []; + $groupIndex = 0; + $groups[$groupIndex] = []; + + foreach ($lines as $index => $line) { + if (substr_count($line, $placeholder) > 0) { + $groups[$groupIndex][] = $index; + } elseif ( + self::ALIGN_BY_SCOPE !== $alignStrategy + && self::ALIGN_SINGLE_SPACE_BY_SCOPE !== $alignStrategy + && self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE !== $alignStrategy + ) { + ++$groupIndex; + $groups[$groupIndex] = []; + } + } + + foreach ($groups as $group) { + if (\count($group) < 1) { + continue; + } + + if (self::ALIGN !== $alignStrategy) { + // move placeholders to match strategy + foreach ($group as $index) { + $currentPosition = strpos($lines[$index], $placeholder); + $before = substr($lines[$index], 0, $currentPosition); + + if ( + self::ALIGN_SINGLE_SPACE === $alignStrategy + || self::ALIGN_SINGLE_SPACE_BY_SCOPE === $alignStrategy + ) { + if (!str_ends_with($before, ' ')) { // if last char of before-content is not ' '; add it + $before .= ' '; + } + } elseif ( + self::ALIGN_SINGLE_SPACE_MINIMAL === $alignStrategy + || self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE === $alignStrategy + ) { + if (!Preg::match('/^\h+$/', $before)) { // if indent; do not move, leave to other fixer + $before = rtrim($before).' '; + } + } + + $lines[$index] = $before.substr($lines[$index], $currentPosition); + } + } + + $rightmostSymbol = 0; + foreach ($group as $index) { + $rightmostSymbol = max($rightmostSymbol, mb_strpos($lines[$index], $placeholder)); + } + + foreach ($group as $index) { + $line = $lines[$index]; + $currentSymbol = mb_strpos($line, $placeholder); + $delta = abs($rightmostSymbol - $currentSymbol); + + if ($delta > 0) { + $line = str_replace($placeholder, str_repeat(' ', $delta).$placeholder, $line); + $lines[$index] = $line; + } + } + } + + $tmpCode = str_replace($placeholder, '', implode("\n", $lines)); + } + + return $tmpCode; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ConcatSpaceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ConcatSpaceFixer.php new file mode 100644 index 00000000..8c452604 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ConcatSpaceFixer.php @@ -0,0 +1,160 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class ConcatSpaceFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var null|string + */ + private $fixCallback; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + if ('one' === $this->configuration['spacing']) { + $this->fixCallback = 'fixConcatenationToSingleSpace'; + } else { + $this->fixCallback = 'fixConcatenationToNoSpace'; + } + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Concatenation should be spaced according to configuration.', + [ + new CodeSample( + " 'none'] + ), + new CodeSample( + " 'one'] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run after NoUnneededControlParenthesesFixer, SingleLineThrowFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound('.'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $callBack = $this->fixCallback; + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if ($tokens[$index]->equals('.')) { + $this->{$callBack}($tokens, $index); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('spacing', 'Spacing to apply around concatenation operator.')) + ->setAllowedValues(['one', 'none']) + ->setDefault('none') + ->getOption(), + ]); + } + + /** + * @param int $index index of concatenation '.' token + */ + private function fixConcatenationToNoSpace(Tokens $tokens, int $index): void + { + $prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)]; + + if (!$prevNonWhitespaceToken->isGivenKind([T_LNUMBER, T_COMMENT, T_DOC_COMMENT]) || str_starts_with($prevNonWhitespaceToken->getContent(), '/*')) { + $tokens->removeLeadingWhitespace($index, " \t"); + } + + if (!$tokens[$tokens->getNextNonWhitespace($index)]->isGivenKind([T_LNUMBER, T_COMMENT, T_DOC_COMMENT])) { + $tokens->removeTrailingWhitespace($index, " \t"); + } + } + + /** + * @param int $index index of concatenation '.' token + */ + private function fixConcatenationToSingleSpace(Tokens $tokens, int $index): void + { + $this->fixWhiteSpaceAroundConcatToken($tokens, $index, 1); + $this->fixWhiteSpaceAroundConcatToken($tokens, $index, -1); + } + + /** + * @param int $index index of concatenation '.' token + * @param int $offset 1 or -1 + */ + private function fixWhiteSpaceAroundConcatToken(Tokens $tokens, int $index, int $offset): void + { + if (-1 !== $offset && 1 !== $offset) { + throw new \InvalidArgumentException(sprintf( + 'Expected `-1|1` for "$offset", got "%s"', + $offset + )); + } + + $offsetIndex = $index + $offset; + + if (!$tokens[$offsetIndex]->isWhitespace()) { + $tokens->insertAt($index + (1 === $offset ? 1 : 0), new Token([T_WHITESPACE, ' '])); + + return; + } + + if (str_contains($tokens[$offsetIndex]->getContent(), "\n")) { + return; + } + + if ($tokens[$index + $offset * 2]->isComment()) { + return; + } + + $tokens[$offsetIndex] = new Token([T_WHITESPACE, ' ']); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/IncrementStyleFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/IncrementStyleFixer.php new file mode 100644 index 00000000..4d2d9b8a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/IncrementStyleFixer.php @@ -0,0 +1,166 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\Fixer\AbstractIncrementOperatorFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Gregor Harlan + * @author Kuba Werłos + */ +final class IncrementStyleFixer extends AbstractIncrementOperatorFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const STYLE_PRE = 'pre'; + + /** + * @internal + */ + public const STYLE_POST = 'post'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Pre- or post-increment and decrement operators should be used if possible.', + [ + new CodeSample(" self::STYLE_POST] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer. + * Must run after StandardizeIncrementFixer. + */ + public function getPriority(): int + { + return 15; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([T_INC, T_DEC]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('style', 'Whether to use pre- or post-increment and decrement operators.')) + ->setAllowedValues([self::STYLE_PRE, self::STYLE_POST]) + ->setDefault(self::STYLE_PRE) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind([T_INC, T_DEC])) { + continue; + } + + if (self::STYLE_PRE === $this->configuration['style'] && $tokensAnalyzer->isUnarySuccessorOperator($index)) { + $nextToken = $tokens[$tokens->getNextMeaningfulToken($index)]; + + if (!$nextToken->equalsAny([';', ')'])) { + continue; + } + + $startIndex = $this->findStart($tokens, $index); + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($startIndex)]; + + if ($prevToken->equalsAny([';', '{', '}', [T_OPEN_TAG], ')'])) { + $tokens->clearAt($index); + $tokens->insertAt($startIndex, clone $token); + } + } elseif (self::STYLE_POST === $this->configuration['style'] && $tokensAnalyzer->isUnaryPredecessorOperator($index)) { + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + + if (!$prevToken->equalsAny([';', '{', '}', [T_OPEN_TAG], ')'])) { + continue; + } + + $endIndex = $this->findEnd($tokens, $index); + $nextToken = $tokens[$tokens->getNextMeaningfulToken($endIndex)]; + + if ($nextToken->equalsAny([';', ')'])) { + $tokens->clearAt($index); + $tokens->insertAt($tokens->getNextNonWhitespace($endIndex), clone $token); + } + } + } + } + + private function findEnd(Tokens $tokens, int $index): int + { + $nextIndex = $tokens->getNextMeaningfulToken($index); + $nextToken = $tokens[$nextIndex]; + + while ($nextToken->equalsAny([ + '$', + '(', + '[', + [CT::T_DYNAMIC_PROP_BRACE_OPEN], + [CT::T_DYNAMIC_VAR_BRACE_OPEN], + [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN], + [T_NS_SEPARATOR], + [T_STATIC], + [T_STRING], + [T_VARIABLE], + ])) { + $blockType = Tokens::detectBlockType($nextToken); + + if (null !== $blockType) { + $nextIndex = $tokens->findBlockEnd($blockType['type'], $nextIndex); + } + + $index = $nextIndex; + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + $nextToken = $tokens[$nextIndex]; + } + + if ($nextToken->isObjectOperator()) { + return $this->findEnd($tokens, $nextIndex); + } + + if ($nextToken->isGivenKind(T_PAAMAYIM_NEKUDOTAYIM)) { + return $this->findEnd($tokens, $tokens->getNextMeaningfulToken($nextIndex)); + } + + return $index; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LogicalOperatorsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LogicalOperatorsFixer.php new file mode 100644 index 00000000..5e05aac6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LogicalOperatorsFixer.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Haralan Dobrev + */ +final class LogicalOperatorsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Use `&&` and `||` logical operators instead of `and` and `or`.', + [ + new CodeSample( + 'isAnyTokenKindsFound([T_LOGICAL_AND, T_LOGICAL_OR]); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(T_LOGICAL_AND)) { + $tokens[$index] = new Token([T_BOOLEAN_AND, '&&']); + } elseif ($token->isGivenKind(T_LOGICAL_OR)) { + $tokens[$index] = new Token([T_BOOLEAN_OR, '||']); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LongToShorthandOperatorFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LongToShorthandOperatorFixer.php new file mode 100644 index 00000000..ca57caa4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LongToShorthandOperatorFixer.php @@ -0,0 +1,138 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\Fixer\AbstractShortOperatorFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +final class LongToShorthandOperatorFixer extends AbstractShortOperatorFixer +{ + /** + * @var array + */ + private static array $operators = [ + '+' => [T_PLUS_EQUAL, '+='], + '-' => [T_MINUS_EQUAL, '-='], + '*' => [T_MUL_EQUAL, '*='], + '/' => [T_DIV_EQUAL, '/='], + '&' => [T_AND_EQUAL, '&='], + '.' => [T_CONCAT_EQUAL, '.='], + '%' => [T_MOD_EQUAL, '%='], + '|' => [T_OR_EQUAL, '|='], + '^' => [T_XOR_EQUAL, '^='], + ]; + + /** + * @var string[] + */ + private array $operatorTypes; + + private TokensAnalyzer $tokensAnalyzer; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Shorthand notation for operators should be used if possible.', + [ + new CodeSample("isAnyTokenKindsFound(array_keys(self::$operators))) { + return true; + } + + // @TODO: drop condition when PHP 8.0 is required and the "&" issues went away + return \defined('T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->operatorTypes = array_keys(self::$operators); + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + + parent::applyFix($file, $tokens); + } + + protected function isOperatorTokenCandidate(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->equalsAny($this->operatorTypes)) { + return false; + } + + while (null !== $index) { + $index = $tokens->getNextMeaningfulToken($index); + $otherToken = $tokens[$index]; + + if ($otherToken->equalsAny([';', [T_CLOSE_TAG]])) { + return true; + } + + // fast precedence check + if ($otherToken->equals('?') || $otherToken->isGivenKind(T_INSTANCEOF)) { + return false; + } + + $blockType = Tokens::detectBlockType($otherToken); + + if (null !== $blockType) { + if (false === $blockType['isStart']) { + return true; + } + + $index = $tokens->findBlockEnd($blockType['type'], $index); + + continue; + } + + // precedence check + if ($this->tokensAnalyzer->isBinaryOperator($index)) { + return false; + } + } + + return false; // unreachable, but keeps SCA happy + } + + protected function getReplacementToken(Token $token): Token + { + return new Token(self::$operators[$token->getContent()]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithBracesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithBracesFixer.php new file mode 100644 index 00000000..1fad4c76 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithBracesFixer.php @@ -0,0 +1,87 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @author Dariusz Rumiński + * + * @deprecated + */ +final class NewWithBracesFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface +{ + private NewWithParenthesesFixer $newWithParenthesesFixer; + + public function __construct() + { + $this->newWithParenthesesFixer = new NewWithParenthesesFixer(); + + parent::__construct(); + } + + public function getDefinition(): FixerDefinitionInterface + { + $fixerDefinition = $this->newWithParenthesesFixer->getDefinition(); + + return new FixerDefinition( + 'All instances created with `new` keyword must (not) be followed by braces.', + $fixerDefinition->getCodeSamples(), + $fixerDefinition->getDescription(), + $fixerDefinition->getRiskyDescription(), + ); + } + + /** + * {@inheritdoc} + * + * Must run before ClassDefinitionFixer. + */ + public function getPriority(): int + { + return $this->newWithParenthesesFixer->getPriority(); + } + + public function configure(array $configuration): void + { + $this->newWithParenthesesFixer->configure($configuration); + + parent::configure($configuration); + } + + public function getSuccessorsNames(): array + { + return [ + $this->newWithParenthesesFixer->getName(), + ]; + } + + protected function createProxyFixers(): array + { + return [ + $this->newWithParenthesesFixer, + ]; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return $this->newWithParenthesesFixer->createConfigurationDefinition(); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithParenthesesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithParenthesesFixer.php new file mode 100644 index 00000000..9c9d7aab --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithParenthesesFixer.php @@ -0,0 +1,200 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class NewWithParenthesesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'All instances created with `new` keyword must (not) be followed by parentheses.', + [ + new CodeSample(" false] + ), + new CodeSample( + " false] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before ClassDefinitionFixer. + */ + public function getPriority(): int + { + return 37; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_NEW); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + static $nextTokenKinds = null; + + if (null === $nextTokenKinds) { + $nextTokenKinds = [ + '?', + ';', + ',', + '(', + ')', + '[', + ']', + ':', + '<', + '>', + '+', + '-', + '*', + '/', + '%', + '&', + '^', + '|', + [T_CLASS], + [T_IS_SMALLER_OR_EQUAL], + [T_IS_GREATER_OR_EQUAL], + [T_IS_EQUAL], + [T_IS_NOT_EQUAL], + [T_IS_IDENTICAL], + [T_IS_NOT_IDENTICAL], + [T_CLOSE_TAG], + [T_LOGICAL_AND], + [T_LOGICAL_OR], + [T_LOGICAL_XOR], + [T_BOOLEAN_AND], + [T_BOOLEAN_OR], + [T_SL], + [T_SR], + [T_INSTANCEOF], + [T_AS], + [T_DOUBLE_ARROW], + [T_POW], + [T_SPACESHIP], + [CT::T_ARRAY_SQUARE_BRACE_OPEN], + [CT::T_ARRAY_SQUARE_BRACE_CLOSE], + [CT::T_BRACE_CLASS_INSTANTIATION_OPEN], + [CT::T_BRACE_CLASS_INSTANTIATION_CLOSE], + ]; + + if (\defined('T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG')) { // @TODO: drop condition when PHP 8.1+ is required + $nextTokenKinds[] = [T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG]; + $nextTokenKinds[] = [T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG]; + } + } + + for ($index = $tokens->count() - 3; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(T_NEW)) { + continue; + } + + $nextIndex = $tokens->getNextTokenOfKind($index, $nextTokenKinds); + + // new anonymous class definition + if ($tokens[$nextIndex]->isGivenKind(T_CLASS)) { + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + + if ($this->configuration['anonymous_class']) { + $this->ensureParenthesesAt($tokens, $nextIndex); + } else { + $this->ensureNoParenthesesAt($tokens, $nextIndex); + } + + continue; + } + + // entrance into array index syntax - need to look for exit + + while ($tokens[$nextIndex]->equals('[') || $tokens[$nextIndex]->isGivenKind(CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN)) { + $nextIndex = $tokens->findBlockEnd(Tokens::detectBlockType($tokens[$nextIndex])['type'], $nextIndex); + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + } + + if ($this->configuration['named_class']) { + $this->ensureParenthesesAt($tokens, $nextIndex); + } else { + $this->ensureNoParenthesesAt($tokens, $nextIndex); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('named_class', 'Whether named classes should be followed by parentheses.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('anonymous_class', 'Whether anonymous classes should be followed by parentheses.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + private function ensureParenthesesAt(Tokens $tokens, int $index): void + { + $token = $tokens[$index]; + + if (!$token->equals('(') && !$token->isObjectOperator()) { + $tokens->insertAt( + $tokens->getPrevMeaningfulToken($index) + 1, + [new Token('('), new Token(')')] + ); + } + } + + private function ensureNoParenthesesAt(Tokens $tokens, int $index): void + { + if (!$tokens[$index]->equals('(')) { + return; + } + + $closingIndex = $tokens->getNextMeaningfulToken($index); + + // constructor has arguments - parentheses can not be removed + if (!$tokens[$closingIndex]->equals(')')) { + return; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($closingIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoSpaceAroundDoubleColonFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoSpaceAroundDoubleColonFixer.php new file mode 100644 index 00000000..ddf0c2df --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoSpaceAroundDoubleColonFixer.php @@ -0,0 +1,63 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +final class NoSpaceAroundDoubleColonFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There must be no space around double colons (also called Scope Resolution Operator or Paamayim Nekudotayim).', + [new CodeSample("isTokenKindFound(T_DOUBLE_COLON); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 2; $index > 1; --$index) { + if ($tokens[$index]->isGivenKind(T_DOUBLE_COLON)) { + $this->removeSpace($tokens, $index, 1); + $this->removeSpace($tokens, $index, -1); + } + } + } + + /** + * @param -1|1 $direction + */ + private function removeSpace(Tokens $tokens, int $index, int $direction): void + { + if (!$tokens[$index + $direction]->isWhitespace()) { + return; + } + + if ($tokens[$tokens->getNonWhitespaceSibling($index, $direction)]->isComment()) { + return; + } + + $tokens->clearAt($index + $direction); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessConcatOperatorFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessConcatOperatorFixer.php new file mode 100644 index 00000000..a3a04067 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessConcatOperatorFixer.php @@ -0,0 +1,339 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class NoUselessConcatOperatorFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const STR_DOUBLE_QUOTE = 0; + private const STR_DOUBLE_QUOTE_VAR = 1; + private const STR_SINGLE_QUOTE = 2; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be useless concat operations.', + [ + new CodeSample(" true]), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before DateTimeCreateFromFormatCallFixer, EregToPregFixer, PhpUnitDedicateAssertInternalTypeFixer, RegularCallableCallFixer, SetTypeToCastFixer. + * Must run after NoBinaryStringFixer, SingleQuoteFixer. + */ + public function getPriority(): int + { + return 5; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound('.') && $tokens->isAnyTokenKindsFound([T_CONSTANT_ENCAPSED_STRING, '"']); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->equals('.')) { + continue; + } + + $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index); + + if ($this->containsLinebreak($tokens, $index, $nextMeaningfulTokenIndex)) { + continue; + } + + $secondOperand = $this->getConcatOperandType($tokens, $nextMeaningfulTokenIndex, 1); + + if (null === $secondOperand) { + continue; + } + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); + + if ($this->containsLinebreak($tokens, $prevMeaningfulTokenIndex, $index)) { + continue; + } + + $firstOperand = $this->getConcatOperandType($tokens, $prevMeaningfulTokenIndex, -1); + + if (null === $firstOperand) { + continue; + } + + $this->fixConcatOperation($tokens, $firstOperand, $index, $secondOperand); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('juggle_simple_strings', 'Allow for simple string quote juggling if it results in more concat-operations merges.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * @param array{ + * start: int, + * end: int, + * type: self::STR_*, + * } $firstOperand + * @param array{ + * start: int, + * end: int, + * type: self::STR_*, + * } $secondOperand + */ + private function fixConcatOperation(Tokens $tokens, array $firstOperand, int $concatIndex, array $secondOperand): void + { + // if both operands are of the same type then these operands can always be merged + + if ( + (self::STR_DOUBLE_QUOTE === $firstOperand['type'] && self::STR_DOUBLE_QUOTE === $secondOperand['type']) + || (self::STR_SINGLE_QUOTE === $firstOperand['type'] && self::STR_SINGLE_QUOTE === $secondOperand['type']) + ) { + $this->mergeConstantEscapedStringOperands($tokens, $firstOperand, $concatIndex, $secondOperand); + + return; + } + + if (self::STR_DOUBLE_QUOTE_VAR === $firstOperand['type'] && self::STR_DOUBLE_QUOTE_VAR === $secondOperand['type']) { + $this->mergeConstantEscapedStringVarOperands($tokens, $firstOperand, $concatIndex, $secondOperand); + + return; + } + + // if any is double and the other is not, check for simple other, than merge with " + + $operands = [ + [$firstOperand, $secondOperand], + [$secondOperand, $firstOperand], + ]; + + foreach ($operands as $operandPair) { + [$operand1, $operand2] = $operandPair; + + if (self::STR_DOUBLE_QUOTE_VAR === $operand1['type'] && self::STR_DOUBLE_QUOTE === $operand2['type']) { + $this->mergeConstantEscapedStringVarOperands($tokens, $firstOperand, $concatIndex, $secondOperand); + + return; + } + + if (!$this->configuration['juggle_simple_strings']) { + continue; + } + + if (self::STR_DOUBLE_QUOTE === $operand1['type'] && self::STR_SINGLE_QUOTE === $operand2['type']) { + $operantContent = $tokens[$operand2['start']]->getContent(); + + if ($this->isSimpleQuotedStringContent($operantContent)) { + $this->mergeConstantEscapedStringOperands($tokens, $firstOperand, $concatIndex, $secondOperand); + } + + return; + } + + if (self::STR_DOUBLE_QUOTE_VAR === $operand1['type'] && self::STR_SINGLE_QUOTE === $operand2['type']) { + $operantContent = $tokens[$operand2['start']]->getContent(); + + if ($this->isSimpleQuotedStringContent($operantContent)) { + $this->mergeConstantEscapedStringVarOperands($tokens, $firstOperand, $concatIndex, $secondOperand); + } + + return; + } + } + } + + /** + * @param -1|1 $direction + * + * @return null|array{ + * start: int, + * end: int, + * type: self::STR_*, + * } + */ + private function getConcatOperandType(Tokens $tokens, int $index, int $direction): ?array + { + if ($tokens[$index]->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) { + $firstChar = $tokens[$index]->getContent(); + + if ('b' === $firstChar[0] || 'B' === $firstChar[0]) { + return null; // we don't care about these, priorities are set to do deal with these cases + } + + return [ + 'start' => $index, + 'end' => $index, + 'type' => '"' === $firstChar[0] ? self::STR_DOUBLE_QUOTE : self::STR_SINGLE_QUOTE, + ]; + } + + if ($tokens[$index]->equals('"')) { + $end = $tokens->getTokenOfKindSibling($index, $direction, ['"']); + + return [ + 'start' => 1 === $direction ? $index : $end, + 'end' => 1 === $direction ? $end : $index, + 'type' => self::STR_DOUBLE_QUOTE_VAR, + ]; + } + + return null; + } + + /** + * @param array{ + * start: int, + * end: int, + * type: self::STR_*, + * } $firstOperand + * @param array{ + * start: int, + * end: int, + * type: self::STR_*, + * } $secondOperand + */ + private function mergeConstantEscapedStringOperands( + Tokens $tokens, + array $firstOperand, + int $concatOperatorIndex, + array $secondOperand + ): void { + $quote = self::STR_DOUBLE_QUOTE === $firstOperand['type'] || self::STR_DOUBLE_QUOTE === $secondOperand['type'] ? '"' : "'"; + $firstOperandTokenContent = $tokens[$firstOperand['start']]->getContent(); + $secondOperandTokenContent = $tokens[$secondOperand['start']]->getContent(); + + $tokens[$firstOperand['start']] = new Token( + [ + T_CONSTANT_ENCAPSED_STRING, + $quote.substr($firstOperandTokenContent, 1, -1).substr($secondOperandTokenContent, 1, -1).$quote, + ], + ); + + $tokens->clearTokenAndMergeSurroundingWhitespace($secondOperand['start']); + $this->clearConcatAndAround($tokens, $concatOperatorIndex); + } + + /** + * @param array{ + * start: int, + * end: int, + * type: self::STR_*, + * } $firstOperand + * @param array{ + * start: int, + * end: int, + * type: self::STR_*, + * } $secondOperand + */ + private function mergeConstantEscapedStringVarOperands( + Tokens $tokens, + array $firstOperand, + int $concatOperatorIndex, + array $secondOperand + ): void { + // build uo the new content + $newContent = ''; + + foreach ([$firstOperand, $secondOperand] as $operant) { + $operandContent = ''; + + for ($i = $operant['start']; $i <= $operant['end'];) { + $operandContent .= $tokens[$i]->getContent(); + $i = $tokens->getNextMeaningfulToken($i); + } + + $newContent .= substr($operandContent, 1, -1); + } + + // remove tokens making up the concat statement + + for ($i = $secondOperand['end']; $i >= $secondOperand['start'];) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + $i = $tokens->getPrevMeaningfulToken($i); + } + + $this->clearConcatAndAround($tokens, $concatOperatorIndex); + + for ($i = $firstOperand['end']; $i > $firstOperand['start'];) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + $i = $tokens->getPrevMeaningfulToken($i); + } + + // insert new tokens based on the new content + + $newTokens = Tokens::fromCode('overrideRange($firstOperand['start'], $firstOperand['start'], $insertTokens); + } + + private function clearConcatAndAround(Tokens $tokens, int $concatOperatorIndex): void + { + if ($tokens[$concatOperatorIndex + 1]->isWhitespace()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($concatOperatorIndex + 1); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($concatOperatorIndex); + + if ($tokens[$concatOperatorIndex - 1]->isWhitespace()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($concatOperatorIndex - 1); + } + } + + private function isSimpleQuotedStringContent(string $candidate): bool + { + return !Preg::match('#[\$"\'\\\]#', substr($candidate, 1, -1)); + } + + private function containsLinebreak(Tokens $tokens, int $startIndex, int $endIndex): bool + { + for ($i = $endIndex; $i > $startIndex; --$i) { + if (Preg::match('/\R/', $tokens[$i]->getContent())) { + return true; + } + } + + return false; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessNullsafeOperatorFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessNullsafeOperatorFixer.php new file mode 100644 index 00000000..2754e152 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessNullsafeOperatorFixer.php @@ -0,0 +1,73 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class NoUselessNullsafeOperatorFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be useless Null-safe operator `?->` used.', + [ + new VersionSpecificCodeSample( + 'parentMethod(); + } +} +', + new VersionSpecification(8_00_00) + ), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return \PHP_VERSION_ID >= 8_00_00 && $tokens->isAllTokenKindsFound([T_VARIABLE, T_NULLSAFE_OBJECT_OPERATOR]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (!$tokens[$index]->isGivenKind(T_NULLSAFE_OBJECT_OPERATOR)) { + continue; + } + + $nullsafeObjectOperatorIndex = $index; + $index = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$index]->isGivenKind(T_VARIABLE)) { + continue; + } + + if ('$this' !== strtolower($tokens[$index]->getContent())) { + continue; + } + + $tokens[$nullsafeObjectOperatorIndex] = new Token([T_OBJECT_OPERATOR, '->']); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSpaceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSpaceFixer.php new file mode 100644 index 00000000..f40dcc22 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSpaceFixer.php @@ -0,0 +1,75 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Javier Spagnoletti + */ +final class NotOperatorWithSpaceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Logical NOT operators (`!`) should have leading and trailing whitespaces.', + [new CodeSample( + 'isTokenKindFound('!'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if ($token->equals('!')) { + if (!$tokens[$index + 1]->isWhitespace()) { + $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); + } + + if (!$tokens[$index - 1]->isWhitespace()) { + $tokens->insertAt($index, new Token([T_WHITESPACE, ' '])); + } + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php new file mode 100644 index 00000000..bf228b52 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php @@ -0,0 +1,68 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Javier Spagnoletti + */ +final class NotOperatorWithSuccessorSpaceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Logical NOT operators (`!`) should have one trailing whitespace.', + [new CodeSample( + 'isTokenKindFound('!'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if ($token->equals('!')) { + $tokens->ensureWhitespaceAtIndex($index + 1, 0, ' '); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php new file mode 100644 index 00000000..fe6e7ac9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php @@ -0,0 +1,62 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + */ +final class ObjectOperatorWithoutWhitespaceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be space before or after object operators `->` and `?->`.', + [new CodeSample(" b;\n")] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getObjectOperatorKinds()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + // [Structure] there should not be space before or after "->" or "?->" + foreach ($tokens as $index => $token) { + if (!$token->isObjectOperator()) { + continue; + } + + // clear whitespace before -> + if ($tokens[$index - 1]->isWhitespace(" \t") && !$tokens[$index - 2]->isComment()) { + $tokens->clearAt($index - 1); + } + + // clear whitespace after -> + if ($tokens[$index + 1]->isWhitespace(" \t") && !$tokens[$index + 2]->isComment()) { + $tokens->clearAt($index + 1); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/OperatorLinebreakFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/OperatorLinebreakFixer.php new file mode 100644 index 00000000..370e6f4d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/OperatorLinebreakFixer.php @@ -0,0 +1,276 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\ReferenceAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\SwitchAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + */ +final class OperatorLinebreakFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const BOOLEAN_OPERATORS = [[T_BOOLEAN_AND], [T_BOOLEAN_OR], [T_LOGICAL_AND], [T_LOGICAL_OR], [T_LOGICAL_XOR]]; + + private string $position = 'beginning'; + + /** + * @var array|string> + */ + private array $operators = []; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Operators - when multiline - must always be at the beginning or at the end of the line.', + [ + new CodeSample(' 'end'] + ), + ] + ); + } + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->position = $this->configuration['position']; + $this->operators = self::BOOLEAN_OPERATORS; + + if (false === $this->configuration['only_booleans']) { + $this->operators = array_merge($this->operators, self::getNonBooleanOperators()); + } + } + + public function isCandidate(Tokens $tokens): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('only_booleans', 'Whether to limit operators to only boolean ones.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('position', 'Whether to place operators at the beginning or at the end of the line.')) + ->setAllowedValues(['beginning', 'end']) + ->setDefault($this->position) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $referenceAnalyzer = new ReferenceAnalyzer(); + $gotoLabelAnalyzer = new GotoLabelAnalyzer(); + $alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer(); + + $index = $tokens->count(); + while ($index > 1) { + --$index; + + if (!$tokens[$index]->equalsAny($this->operators, false)) { + continue; + } + + if ($gotoLabelAnalyzer->belongsToGoToLabel($tokens, $index)) { + continue; + } + + if ($referenceAnalyzer->isReference($tokens, $index)) { + continue; + } + + if ($alternativeSyntaxAnalyzer->belongsToAlternativeSyntax($tokens, $index)) { + continue; + } + + if (SwitchAnalyzer::belongsToSwitch($tokens, $index)) { + continue; + } + + $operatorIndices = [$index]; + if ($tokens[$index]->equals(':')) { + /** @var int $prevIndex */ + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->equals('?')) { + $operatorIndices = [$prevIndex, $index]; + $index = $prevIndex; + } + } + + $this->fixOperatorLinebreak($tokens, $operatorIndices); + } + } + + /** + * @param int[] $operatorIndices + */ + private function fixOperatorLinebreak(Tokens $tokens, array $operatorIndices): void + { + /** @var int $prevIndex */ + $prevIndex = $tokens->getPrevMeaningfulToken(min($operatorIndices)); + $indexStart = $prevIndex + 1; + + /** @var int $nextIndex */ + $nextIndex = $tokens->getNextMeaningfulToken(max($operatorIndices)); + $indexEnd = $nextIndex - 1; + + if (!$this->isMultiline($tokens, $indexStart, $indexEnd)) { + return; // operator is not surrounded by multiline whitespaces, do not touch it + } + + if ('beginning' === $this->position) { + if (!$this->isMultiline($tokens, max($operatorIndices), $indexEnd)) { + return; // operator already is placed correctly + } + $this->fixMoveToTheBeginning($tokens, $operatorIndices); + + return; + } + + if (!$this->isMultiline($tokens, $indexStart, min($operatorIndices))) { + return; // operator already is placed correctly + } + $this->fixMoveToTheEnd($tokens, $operatorIndices); + } + + /** + * @param int[] $operatorIndices + */ + private function fixMoveToTheBeginning(Tokens $tokens, array $operatorIndices): void + { + /** @var int $prevIndex */ + $prevIndex = $tokens->getNonEmptySibling(min($operatorIndices), -1); + + /** @var int $nextIndex */ + $nextIndex = $tokens->getNextMeaningfulToken(max($operatorIndices)); + + for ($i = $nextIndex - 1; $i > max($operatorIndices); --$i) { + if ($tokens[$i]->isWhitespace() && Preg::match('/\R/u', $tokens[$i]->getContent())) { + $isWhitespaceBefore = $tokens[$prevIndex]->isWhitespace(); + $inserts = $this->getReplacementsAndClear($tokens, $operatorIndices, -1); + if ($isWhitespaceBefore) { + $inserts[] = new Token([T_WHITESPACE, ' ']); + } + $tokens->insertAt($nextIndex, $inserts); + + break; + } + } + } + + /** + * @param int[] $operatorIndices + */ + private function fixMoveToTheEnd(Tokens $tokens, array $operatorIndices): void + { + /** @var int $prevIndex */ + $prevIndex = $tokens->getPrevMeaningfulToken(min($operatorIndices)); + + /** @var int $nextIndex */ + $nextIndex = $tokens->getNonEmptySibling(max($operatorIndices), 1); + + for ($i = $prevIndex + 1; $i < max($operatorIndices); ++$i) { + if ($tokens[$i]->isWhitespace() && Preg::match('/\R/u', $tokens[$i]->getContent())) { + $isWhitespaceAfter = $tokens[$nextIndex]->isWhitespace(); + $inserts = $this->getReplacementsAndClear($tokens, $operatorIndices, 1); + if ($isWhitespaceAfter) { + array_unshift($inserts, new Token([T_WHITESPACE, ' '])); + } + $tokens->insertAt($prevIndex + 1, $inserts); + + break; + } + } + } + + /** + * @param int[] $indices + * + * @return Token[] + */ + private function getReplacementsAndClear(Tokens $tokens, array $indices, int $direction): array + { + return array_map( + static function (int $index) use ($tokens, $direction): Token { + $clone = $tokens[$index]; + + if ($tokens[$index + $direction]->isWhitespace()) { + $tokens->clearAt($index + $direction); + } + + $tokens->clearAt($index); + + return $clone; + }, + $indices + ); + } + + private function isMultiline(Tokens $tokens, int $indexStart, int $indexEnd): bool + { + for ($index = $indexStart; $index <= $indexEnd; ++$index) { + if (str_contains($tokens[$index]->getContent(), "\n")) { + return true; + } + } + + return false; + } + + private static function getNonBooleanOperators(): array + { + return array_merge( + [ + '%', '&', '*', '+', '-', '.', '/', ':', '<', '=', '>', '?', '^', '|', + [T_AND_EQUAL], [T_CONCAT_EQUAL], [T_DIV_EQUAL], [T_DOUBLE_ARROW], [T_IS_EQUAL], [T_IS_GREATER_OR_EQUAL], + [T_IS_IDENTICAL], [T_IS_NOT_EQUAL], [T_IS_NOT_IDENTICAL], [T_IS_SMALLER_OR_EQUAL], [T_MINUS_EQUAL], + [T_MOD_EQUAL], [T_MUL_EQUAL], [T_OR_EQUAL], [T_PAAMAYIM_NEKUDOTAYIM], [T_PLUS_EQUAL], [T_POW], + [T_POW_EQUAL], [T_SL], [T_SL_EQUAL], [T_SR], [T_SR_EQUAL], [T_XOR_EQUAL], + [T_COALESCE], [T_SPACESHIP], + ], + array_map(static fn (int $id): array => [$id], Token::getObjectOperatorKinds()), + ); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeIncrementFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeIncrementFixer.php new file mode 100644 index 00000000..1aaae169 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeIncrementFixer.php @@ -0,0 +1,122 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\Fixer\AbstractIncrementOperatorFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author ntzm + */ +final class StandardizeIncrementFixer extends AbstractIncrementOperatorFixer +{ + private const EXPRESSION_END_TOKENS = [ + ';', + ')', + ']', + ',', + ':', + [CT::T_DYNAMIC_PROP_BRACE_CLOSE], + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + [T_CLOSE_TAG], + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Increment and decrement operators should be used if possible.', + [ + new CodeSample("isAnyTokenKindsFound([T_PLUS_EQUAL, T_MINUS_EQUAL]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index > 0; --$index) { + $expressionEnd = $tokens[$index]; + if (!$expressionEnd->equalsAny(self::EXPRESSION_END_TOKENS)) { + continue; + } + + $numberIndex = $tokens->getPrevMeaningfulToken($index); + $number = $tokens[$numberIndex]; + if (!$number->isGivenKind(T_LNUMBER) || '1' !== $number->getContent()) { + continue; + } + + $operatorIndex = $tokens->getPrevMeaningfulToken($numberIndex); + $operator = $tokens[$operatorIndex]; + if (!$operator->isGivenKind([T_PLUS_EQUAL, T_MINUS_EQUAL])) { + continue; + } + + $startIndex = $this->findStart($tokens, $operatorIndex); + + $this->clearRangeLeaveComments( + $tokens, + $tokens->getPrevMeaningfulToken($operatorIndex) + 1, + $numberIndex + ); + + $tokens->insertAt( + $startIndex, + new Token($operator->isGivenKind(T_PLUS_EQUAL) ? [T_INC, '++'] : [T_DEC, '--']) + ); + } + } + + /** + * Clear tokens in the given range unless they are comments. + */ + private function clearRangeLeaveComments(Tokens $tokens, int $indexStart, int $indexEnd): void + { + for ($i = $indexStart; $i <= $indexEnd; ++$i) { + $token = $tokens[$i]; + + if ($token->isComment()) { + continue; + } + + if ($token->isWhitespace("\n\r")) { + continue; + } + + $tokens->clearAt($i); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeNotEqualsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeNotEqualsFixer.php new file mode 100644 index 00000000..2dab6092 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeNotEqualsFixer.php @@ -0,0 +1,60 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class StandardizeNotEqualsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace all `<>` with `!=`.', + [new CodeSample(" \$c;\n")] + ); + } + + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_IS_NOT_EQUAL); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(T_IS_NOT_EQUAL)) { + $tokens[$index] = new Token([T_IS_NOT_EQUAL, '!=']); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryOperatorSpacesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryOperatorSpacesFixer.php new file mode 100644 index 00000000..a0b80a73 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryOperatorSpacesFixer.php @@ -0,0 +1,131 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\SwitchAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class TernaryOperatorSpacesFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Standardize spaces around ternary operator.', + [new CodeSample("isAllTokenKindsFound(['?', ':']); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer(); + $gotoLabelAnalyzer = new GotoLabelAnalyzer(); + $ternaryOperatorIndices = []; + + foreach ($tokens as $index => $token) { + if (!$token->equalsAny(['?', ':'])) { + continue; + } + + if (SwitchAnalyzer::belongsToSwitch($tokens, $index)) { + continue; + } + + if ($alternativeSyntaxAnalyzer->belongsToAlternativeSyntax($tokens, $index)) { + continue; + } + + if ($gotoLabelAnalyzer->belongsToGoToLabel($tokens, $index)) { + continue; + } + + $ternaryOperatorIndices[] = $index; + } + + foreach (array_reverse($ternaryOperatorIndices) as $index) { + $token = $tokens[$index]; + + if ($token->equals('?')) { + $nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($index); + + if ($tokens[$nextNonWhitespaceIndex]->equals(':')) { + // for `$a ?: $b` remove spaces between `?` and `:` + $tokens->ensureWhitespaceAtIndex($index + 1, 0, ''); + } else { + // for `$a ? $b : $c` ensure space after `?` + $this->ensureWhitespaceExistence($tokens, $index + 1, true); + } + + // for `$a ? $b : $c` ensure space before `?` + $this->ensureWhitespaceExistence($tokens, $index - 1, false); + + continue; + } + + if ($token->equals(':')) { + // for `$a ? $b : $c` ensure space after `:` + $this->ensureWhitespaceExistence($tokens, $index + 1, true); + + $prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)]; + + if (!$prevNonWhitespaceToken->equals('?')) { + // for `$a ? $b : $c` ensure space before `:` + $this->ensureWhitespaceExistence($tokens, $index - 1, false); + } + } + } + } + + private function ensureWhitespaceExistence(Tokens $tokens, int $index, bool $after): void + { + if ($tokens[$index]->isWhitespace()) { + if ( + !str_contains($tokens[$index]->getContent(), "\n") + && !$tokens[$index - 1]->isComment() + ) { + $tokens[$index] = new Token([T_WHITESPACE, ' ']); + } + + return; + } + + $index += $after ? 0 : 1; + $tokens->insertAt($index, new Token([T_WHITESPACE, ' '])); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToElvisOperatorFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToElvisOperatorFixer.php new file mode 100644 index 00000000..4cbae0a1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToElvisOperatorFixer.php @@ -0,0 +1,217 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\RangeAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +final class TernaryToElvisOperatorFixer extends AbstractFixer +{ + /** + * Lower precedence and other valid preceding tokens. + * + * Ordered by most common types first. + * + * @var list + */ + private const VALID_BEFORE_ENDTYPES = [ + '=', + [T_OPEN_TAG], + [T_OPEN_TAG_WITH_ECHO], + '(', + ',', + ';', + '[', + '{', + '}', + [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN], + [T_AND_EQUAL], // &= + [T_CONCAT_EQUAL], // .= + [T_DIV_EQUAL], // /= + [T_MINUS_EQUAL], // -= + [T_MOD_EQUAL], // %= + [T_MUL_EQUAL], // *= + [T_OR_EQUAL], // |= + [T_PLUS_EQUAL], // += + [T_POW_EQUAL], // **= + [T_SL_EQUAL], // <<= + [T_SR_EQUAL], // >>= + [T_XOR_EQUAL], // ^= + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Use the Elvis operator `?:` where possible.', + [ + new CodeSample( + "isTokenKindFound('?'); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $blockEdgeDefinitions = Tokens::getBlockEdgeDefinitions(); + + for ($index = \count($tokens) - 5; $index > 1; --$index) { + if (!$tokens[$index]->equals('?')) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$nextIndex]->equals(':')) { + continue; // Elvis is alive! + } + + // get and check what is before the `?` operator + + $beforeOperator = $this->getBeforeOperator($tokens, $index, $blockEdgeDefinitions); + + if (null === $beforeOperator) { + continue; // contains something we cannot fix because of priorities + } + + // get what is after the `?` token + + $afterOperator = $this->getAfterOperator($tokens, $index); + + // if before and after the `?` operator are the same (in meaningful matter), clear after + + if (RangeAnalyzer::rangeEqualsRange($tokens, $beforeOperator, $afterOperator)) { + $this->clearMeaningfulFromRange($tokens, $afterOperator); + } + } + } + + /** + * @return null|array{start: int, end: int} null if contains ++/-- operator + */ + private function getBeforeOperator(Tokens $tokens, int $index, array $blockEdgeDefinitions): ?array + { + $index = $tokens->getPrevMeaningfulToken($index); + $before = ['end' => $index]; + + while (!$tokens[$index]->equalsAny(self::VALID_BEFORE_ENDTYPES)) { + if ($tokens[$index]->isGivenKind([T_INC, T_DEC])) { + return null; + } + + $blockType = Tokens::detectBlockType($tokens[$index]); + + if (null === $blockType || $blockType['isStart']) { + $before['start'] = $index; + $index = $tokens->getPrevMeaningfulToken($index); + + continue; + } + + $blockType = $blockEdgeDefinitions[$blockType['type']]; + $openCount = 1; + + do { + $index = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind([T_INC, T_DEC])) { + return null; + } + + if ($tokens[$index]->equals($blockType['start'])) { + ++$openCount; + + continue; + } + + if ($tokens[$index]->equals($blockType['end'])) { + --$openCount; + } + } while (1 >= $openCount); + + $before['start'] = $index; + $index = $tokens->getPrevMeaningfulToken($index); + } + + if (!isset($before['start'])) { + return null; + } + + return $before; + } + + /** + * @return array{start: int, end: int} + */ + private function getAfterOperator(Tokens $tokens, int $index): array + { + $index = $tokens->getNextMeaningfulToken($index); + $after = ['start' => $index]; + + while (!$tokens[$index]->equals(':')) { + $blockType = Tokens::detectBlockType($tokens[$index]); + + if (null !== $blockType) { + $index = $tokens->findBlockEnd($blockType['type'], $index); + } + + $after['end'] = $index; + $index = $tokens->getNextMeaningfulToken($index); + } + + return $after; + } + + /** + * @param array{start: int, end: int} $range + */ + private function clearMeaningfulFromRange(Tokens $tokens, array $range): void + { + // $range['end'] must be meaningful! + for ($i = $range['end']; $i >= $range['start']; $i = $tokens->getPrevMeaningfulToken($i)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToNullCoalescingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToNullCoalescingFixer.php new file mode 100644 index 00000000..83cf9337 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToNullCoalescingFixer.php @@ -0,0 +1,224 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + */ +final class TernaryToNullCoalescingFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Use `null` coalescing operator `??` where possible. Requires PHP >= 7.0.', + [ + new CodeSample( + "isTokenKindFound(T_ISSET); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $issetIndices = array_keys($tokens->findGivenKind(T_ISSET)); + + while ($issetIndex = array_pop($issetIndices)) { + $this->fixIsset($tokens, $issetIndex); + } + } + + /** + * @param int $index of `T_ISSET` token + */ + private function fixIsset(Tokens $tokens, int $index): void + { + $prevTokenIndex = $tokens->getPrevMeaningfulToken($index); + + if ($this->isHigherPrecedenceAssociativityOperator($tokens[$prevTokenIndex])) { + return; + } + + $startBraceIndex = $tokens->getNextTokenOfKind($index, ['(']); + $endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startBraceIndex); + + $ternaryQuestionMarkIndex = $tokens->getNextMeaningfulToken($endBraceIndex); + + if (!$tokens[$ternaryQuestionMarkIndex]->equals('?')) { + return; // we are not in a ternary operator + } + + // search what is inside the isset() + $issetTokens = $this->getMeaningfulSequence($tokens, $startBraceIndex, $endBraceIndex); + + if ($this->hasChangingContent($issetTokens)) { + return; // some weird stuff inside the isset + } + + $issetCode = $issetTokens->generateCode(); + + if ('$this' === $issetCode) { + return; // null coalescing operator does not with $this + } + + // search what is inside the middle argument of ternary operator + $ternaryColonIndex = $tokens->getNextTokenOfKind($ternaryQuestionMarkIndex, [':']); + $ternaryFirstOperandTokens = $this->getMeaningfulSequence($tokens, $ternaryQuestionMarkIndex, $ternaryColonIndex); + + if ($issetCode !== $ternaryFirstOperandTokens->generateCode()) { + return; // regardless of non-meaningful tokens, the operands are different + } + + $ternaryFirstOperandIndex = $tokens->getNextMeaningfulToken($ternaryQuestionMarkIndex); + + // preserve comments and spaces + $comments = []; + $commentStarted = false; + + for ($loopIndex = $index; $loopIndex < $ternaryFirstOperandIndex; ++$loopIndex) { + if ($tokens[$loopIndex]->isComment()) { + $comments[] = $tokens[$loopIndex]; + $commentStarted = true; + } elseif ($commentStarted) { + if ($tokens[$loopIndex]->isWhitespace()) { + $comments[] = $tokens[$loopIndex]; + } + + $commentStarted = false; + } + } + + $tokens[$ternaryColonIndex] = new Token([T_COALESCE, '??']); + $tokens->overrideRange($index, $ternaryFirstOperandIndex - 1, $comments); + } + + /** + * Get the sequence of meaningful tokens and returns a new Tokens instance. + * + * @param int $start start index + * @param int $end end index + */ + private function getMeaningfulSequence(Tokens $tokens, int $start, int $end): Tokens + { + $sequence = []; + $index = $start; + + while ($index < $end) { + $index = $tokens->getNextMeaningfulToken($index); + + if ($index >= $end || null === $index) { + break; + } + + $sequence[] = $tokens[$index]; + } + + return Tokens::fromArray($sequence); + } + + /** + * Check if the requested token is an operator computed + * before the ternary operator along with the `isset()`. + */ + private function isHigherPrecedenceAssociativityOperator(Token $token): bool + { + static $operatorsPerId = [ + T_ARRAY_CAST => true, + T_BOOLEAN_AND => true, + T_BOOLEAN_OR => true, + T_BOOL_CAST => true, + T_COALESCE => true, + T_DEC => true, + T_DOUBLE_CAST => true, + T_INC => true, + T_INT_CAST => true, + T_IS_EQUAL => true, + T_IS_GREATER_OR_EQUAL => true, + T_IS_IDENTICAL => true, + T_IS_NOT_EQUAL => true, + T_IS_NOT_IDENTICAL => true, + T_IS_SMALLER_OR_EQUAL => true, + T_OBJECT_CAST => true, + T_POW => true, + T_SL => true, + T_SPACESHIP => true, + T_SR => true, + T_STRING_CAST => true, + T_UNSET_CAST => true, + ]; + + static $operatorsPerContent = [ + '!', + '%', + '&', + '*', + '+', + '-', + '/', + ':', + '^', + '|', + '~', + '.', + ]; + + return isset($operatorsPerId[$token->getId()]) || $token->equalsAny($operatorsPerContent); + } + + /** + * Check if the `isset()` content may change if called multiple times. + * + * @param Tokens $tokens The original token list + */ + private function hasChangingContent(Tokens $tokens): bool + { + static $operatorsPerId = [ + T_DEC, + T_INC, + T_YIELD, + T_YIELD_FROM, + ]; + + foreach ($tokens as $token) { + if ($token->isGivenKind($operatorsPerId) || $token->equals('(')) { + return true; + } + } + + return false; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/UnaryOperatorSpacesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/UnaryOperatorSpacesFixer.php new file mode 100644 index 00000000..05953717 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/UnaryOperatorSpacesFixer.php @@ -0,0 +1,74 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * Fixer for rules defined in PSR12 ¶6.1. + * + * @author Gregor Harlan + */ +final class UnaryOperatorSpacesFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Unary operators should be placed adjacent to their operands.', + [new CodeSample("count() - 1; $index >= 0; --$index) { + if ($tokensAnalyzer->isUnarySuccessorOperator($index)) { + if (!$tokens[$tokens->getPrevNonWhitespace($index)]->isComment()) { + $tokens->removeLeadingWhitespace($index); + } + + continue; + } + + if ($tokensAnalyzer->isUnaryPredecessorOperator($index)) { + $tokens->removeTrailingWhitespace($index); + + continue; + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php new file mode 100644 index 00000000..8c8dbad7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php @@ -0,0 +1,93 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpTag; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Ceeram + */ +final class BlankLineAfterOpeningTagFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Ensure there is no code on the same line as the PHP open tag and it is followed by a blank line.', + [new CodeSample("isTokenKindFound(T_OPEN_TAG); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + // ignore files with short open tag and ignore non-monolithic files + if (!$tokens[0]->isGivenKind(T_OPEN_TAG) || !$tokens->isMonolithicPhp()) { + return; + } + + $newlineFound = false; + + /** @var Token $token */ + foreach ($tokens as $token) { + if ($token->isWhitespace() && str_contains($token->getContent(), "\n")) { + $newlineFound = true; + + break; + } + } + + // ignore one-line files + if (!$newlineFound) { + return; + } + + $token = $tokens[0]; + + if (!str_contains($token->getContent(), "\n")) { + $tokens[0] = new Token([$token->getId(), rtrim($token->getContent()).$lineEnding]); + } + + if (!str_contains($tokens[1]->getContent(), "\n")) { + if ($tokens[1]->isWhitespace()) { + $tokens[1] = new Token([T_WHITESPACE, $lineEnding.$tokens[1]->getContent()]); + } else { + $tokens->insertAt(1, new Token([T_WHITESPACE, $lineEnding])); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/EchoTagSyntaxFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/EchoTagSyntaxFixer.php new file mode 100644 index 00000000..ed09a485 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/EchoTagSyntaxFixer.php @@ -0,0 +1,256 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpTag; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Michele Locati + */ +final class EchoTagSyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @internal */ + public const OPTION_FORMAT = 'format'; + + /** @internal */ + public const OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY = 'shorten_simple_statements_only'; + + /** @internal */ + public const OPTION_LONG_FUNCTION = 'long_function'; + + /** @internal */ + public const FORMAT_SHORT = 'short'; + + /** @internal */ + public const FORMAT_LONG = 'long'; + + /** @internal */ + public const LONG_FUNCTION_ECHO = 'echo'; + + /** @internal */ + public const LONG_FUNCTION_PRINT = 'print'; + + private const SUPPORTED_FORMAT_OPTIONS = [ + self::FORMAT_LONG, + self::FORMAT_SHORT, + ]; + + private const SUPPORTED_LONGFUNCTION_OPTIONS = [ + self::LONG_FUNCTION_ECHO, + self::LONG_FUNCTION_PRINT, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + $sample = <<<'EOT' + + + + + + EOT; + + return new FixerDefinition( + 'Replaces short-echo ` self::FORMAT_LONG]), + new CodeSample($sample, [self::OPTION_FORMAT => self::FORMAT_LONG, self::OPTION_LONG_FUNCTION => self::LONG_FUNCTION_PRINT]), + new CodeSample($sample, [self::OPTION_FORMAT => self::FORMAT_SHORT]), + new CodeSample($sample, [self::OPTION_FORMAT => self::FORMAT_SHORT, self::OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY => false]), + ], + null + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoMixedEchoPrintFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + if (self::FORMAT_SHORT === $this->configuration[self::OPTION_FORMAT]) { + return $tokens->isAnyTokenKindsFound([T_ECHO, T_PRINT]); + } + + return $tokens->isTokenKindFound(T_OPEN_TAG_WITH_ECHO); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder(self::OPTION_FORMAT, 'The desired language construct.')) + ->setAllowedValues(self::SUPPORTED_FORMAT_OPTIONS) + ->setDefault(self::FORMAT_LONG) + ->getOption(), + (new FixerOptionBuilder(self::OPTION_LONG_FUNCTION, 'The function to be used to expand the short echo tags.')) + ->setAllowedValues(self::SUPPORTED_LONGFUNCTION_OPTIONS) + ->setDefault(self::LONG_FUNCTION_ECHO) + ->getOption(), + (new FixerOptionBuilder(self::OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY, 'Render short-echo tags only in case of simple code.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if (self::FORMAT_SHORT === $this->configuration[self::OPTION_FORMAT]) { + $this->longToShort($tokens); + } else { + $this->shortToLong($tokens); + } + } + + private function longToShort(Tokens $tokens): void + { + $count = $tokens->count(); + + for ($index = 0; $index < $count; ++$index) { + if (!$tokens[$index]->isGivenKind(T_OPEN_TAG)) { + continue; + } + + $nextMeaningful = $tokens->getNextMeaningfulToken($index); + + if (null === $nextMeaningful) { + return; + } + + if (!$tokens[$nextMeaningful]->isGivenKind([T_ECHO, T_PRINT])) { + $index = $nextMeaningful; + + continue; + } + + if (true === $this->configuration[self::OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY] && $this->isComplexCode($tokens, $nextMeaningful + 1)) { + $index = $nextMeaningful; + + continue; + } + + $newTokens = $this->buildLongToShortTokens($tokens, $index, $nextMeaningful); + $tokens->overrideRange($index, $nextMeaningful, $newTokens); + $count = $tokens->count(); + } + } + + private function shortToLong(Tokens $tokens): void + { + if (self::LONG_FUNCTION_PRINT === $this->configuration[self::OPTION_LONG_FUNCTION]) { + $echoToken = [T_PRINT, 'print']; + } else { + $echoToken = [T_ECHO, 'echo']; + } + + $index = -1; + + while (true) { + $index = $tokens->getNextTokenOfKind($index, [[T_OPEN_TAG_WITH_ECHO]]); + + if (null === $index) { + return; + } + + $replace = [new Token([T_OPEN_TAG, 'isWhitespace()) { + $replace[] = new Token([T_WHITESPACE, ' ']); + } + + $tokens->overrideRange($index, $index, $replace); + ++$index; + } + } + + /** + * Check if $tokens, starting at $index, contains "complex code", that is, the content + * of the echo tag contains more than a simple "echo something". + * + * This is done by a very quick test: if the tag contains non-whitespace tokens after + * a semicolon, we consider it as "complex". + * + * @example `` is false (not complex) + * @example `` is false (not "complex") + * @example `` is true ("complex") + */ + private function isComplexCode(Tokens $tokens, int $index): bool + { + $semicolonFound = false; + + for ($count = $tokens->count(); $index < $count; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(T_CLOSE_TAG)) { + return false; + } + + if (';' === $token->getContent()) { + $semicolonFound = true; + } elseif ($semicolonFound && !$token->isWhitespace()) { + return true; + } + } + + return false; + } + + /** + * Builds the list of tokens that replace a long echo sequence. + * + * @return Token[] + */ + private function buildLongToShortTokens(Tokens $tokens, int $openTagIndex, int $echoTagIndex): array + { + $result = [new Token([T_OPEN_TAG_WITH_ECHO, 'getNextNonWhitespace($openTagIndex); + + if ($start === $echoTagIndex) { + // No non-whitespace tokens between $openTagIndex and $echoTagIndex + return $result; + } + + // Find the last non-whitespace index before $echoTagIndex + $end = $echoTagIndex - 1; + + while ($tokens[$end]->isWhitespace()) { + --$end; + } + + // Copy the non-whitespace tokens between $openTagIndex and $echoTagIndex + for ($index = $start; $index <= $end; ++$index) { + $result[] = clone $tokens[$index]; + } + + return $result; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/FullOpeningTagFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/FullOpeningTagFixer.php new file mode 100644 index 00000000..61186ccd --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/FullOpeningTagFixer.php @@ -0,0 +1,123 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpTag; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR1 ¶2.1. + * + * @author Dariusz Rumiński + */ +final class FullOpeningTagFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHP code must use the long `generateCode(); + + // replace all echo ' echo ' $token) { + if ($token->isGivenKind(T_OPEN_TAG)) { + $tokenContent = $token->getContent(); + $possibleOpenContent = substr($content, $tokensOldContentLength, 5); + + if (false === $possibleOpenContent || 'isGivenKind([T_COMMENT, T_DOC_COMMENT, T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE, T_STRING])) { + $tokenContent = ''; + $tokenContentLength = 0; + $parts = explode('getContent()); + $iLast = \count($parts) - 1; + + foreach ($parts as $i => $part) { + $tokenContent .= $part; + $tokenContentLength += \strlen($part); + + if ($i !== $iLast) { + $originalTokenContent = substr($content, $tokensOldContentLength + $tokenContentLength, 5); + if ('getId(), $tokenContent]); + $token = $newTokens[$index]; + } + + $tokensOldContentLength += \strlen($token->getContent()); + } + + $tokens->overrideRange(0, $tokens->count() - 1, $newTokens); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php new file mode 100644 index 00000000..5be68fab --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpTag; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Ceeram + */ +final class LinebreakAfterOpeningTagFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Ensure there is no code on the same line as the PHP open tag.', + [new CodeSample("isTokenKindFound(T_OPEN_TAG); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + // ignore files with short open tag and ignore non-monolithic files + if (!$tokens[0]->isGivenKind(T_OPEN_TAG) || !$tokens->isMonolithicPhp()) { + return; + } + + // ignore if linebreak already present + if (str_contains($tokens[0]->getContent(), "\n")) { + return; + } + + $newlineFound = false; + foreach ($tokens as $token) { + if ($token->isWhitespace() && str_contains($token->getContent(), "\n")) { + $newlineFound = true; + + break; + } + } + + // ignore one-line files + if (!$newlineFound) { + return; + } + + $tokens[0] = new Token([T_OPEN_TAG, rtrim($tokens[0]->getContent()).$this->whitespacesConfig->getLineEnding()]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/NoClosingTagFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/NoClosingTagFixer.php new file mode 100644 index 00000000..c6e611b3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/NoClosingTagFixer.php @@ -0,0 +1,63 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpTag; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶2.2. + * + * @author Dariusz Rumiński + */ +final class NoClosingTagFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The closing `?>` tag MUST be omitted from files containing only PHP.', + [new CodeSample("\n")] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_CLOSE_TAG); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if (\count($tokens) < 2 || !$tokens->isMonolithicPhp() || !$tokens->isTokenKindFound(T_CLOSE_TAG)) { + return; + } + + $closeTags = $tokens->findGivenKind(T_CLOSE_TAG); + $index = key($closeTags); + + if (isset($tokens[$index - 1]) && $tokens[$index - 1]->isWhitespace()) { + $tokens->clearAt($index - 1); + } + $tokens->clearAt($index); + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->equalsAny([';', '}', [T_OPEN_TAG]])) { + $tokens->insertAt($prevIndex + 1, new Token(';')); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitConstructFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitConstructFixer.php new file mode 100644 index 00000000..a3b8cf7e --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitConstructFixer.php @@ -0,0 +1,198 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class PhpUnitConstructFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private static array $assertionFixers = [ + 'assertSame' => 'fixAssertPositive', + 'assertEquals' => 'fixAssertPositive', + 'assertNotEquals' => 'fixAssertNegative', + 'assertNotSame' => 'fixAssertNegative', + ]; + + public function isRisky(): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPUnit assertion method calls like `->assertSame(true, $foo)` should be written with dedicated method like `->assertTrue($foo)`.', + [ + new CodeSample( + 'assertEquals(false, $b); + $this->assertSame(true, $a); + $this->assertNotEquals(null, $c); + $this->assertNotSame(null, $d); + } +} +' + ), + new CodeSample( + 'assertEquals(false, $b); + $this->assertSame(true, $a); + $this->assertNotEquals(null, $c); + $this->assertNotSame(null, $d); + } +} +', + ['assertions' => ['assertSame', 'assertNotSame']] + ), + ], + null, + 'Fixer could be risky if one is overriding PHPUnit\'s native methods.' + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpUnitDedicateAssertFixer. + */ + public function getPriority(): int + { + return -8; + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + // no assertions to be fixed - fast return + if ([] === $this->configuration['assertions']) { + return; + } + + foreach ($this->configuration['assertions'] as $assertionMethod) { + $assertionFixer = self::$assertionFixers[$assertionMethod]; + + for ($index = $startIndex; $index < $endIndex; ++$index) { + $index = $this->{$assertionFixer}($tokens, $index, $assertionMethod); + + if (null === $index) { + break; + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('assertions', 'List of assertion methods to fix.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset(array_keys(self::$assertionFixers))]) + ->setDefault([ + 'assertEquals', + 'assertSame', + 'assertNotEquals', + 'assertNotSame', + ]) + ->getOption(), + ]); + } + + private function fixAssertNegative(Tokens $tokens, int $index, string $method): ?int + { + static $map = [ + 'false' => 'assertNotFalse', + 'null' => 'assertNotNull', + 'true' => 'assertNotTrue', + ]; + + return $this->fixAssert($map, $tokens, $index, $method); + } + + private function fixAssertPositive(Tokens $tokens, int $index, string $method): ?int + { + static $map = [ + 'false' => 'assertFalse', + 'null' => 'assertNull', + 'true' => 'assertTrue', + ]; + + return $this->fixAssert($map, $tokens, $index, $method); + } + + /** + * @param array $map + */ + private function fixAssert(array $map, Tokens $tokens, int $index, string $method): ?int + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + $sequence = $tokens->findSequence( + [ + [T_STRING, $method], + '(', + ], + $index + ); + + if (null === $sequence) { + return null; + } + + $sequenceIndices = array_keys($sequence); + + if (!$functionsAnalyzer->isTheSameClassCall($tokens, $sequenceIndices[0])) { + return null; + } + + $sequenceIndices[2] = $tokens->getNextMeaningfulToken($sequenceIndices[1]); + $firstParameterToken = $tokens[$sequenceIndices[2]]; + + if (!$firstParameterToken->isNativeConstant()) { + return $sequenceIndices[2]; + } + + $sequenceIndices[3] = $tokens->getNextMeaningfulToken($sequenceIndices[2]); + + // return if first method argument is an expression, not value + if (!$tokens[$sequenceIndices[3]]->equals(',')) { + return $sequenceIndices[3]; + } + + $tokens[$sequenceIndices[0]] = new Token([T_STRING, $map[strtolower($firstParameterToken->getContent())]]); + $tokens->clearRange($sequenceIndices[2], $tokens->getNextNonWhitespace($sequenceIndices[3]) - 1); + + return $sequenceIndices[3]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderNameFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderNameFixer.php new file mode 100644 index 00000000..c42123b8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderNameFixer.php @@ -0,0 +1,172 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\DataProviderAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + */ +final class PhpUnitDataProviderNameFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Data provider names must match the name of the test.', + [ + new CodeSample( + ' 'data_', + 'suffix' => '', + ] + ), + new CodeSample( + ' 'provides', + 'suffix' => 'Data', + ] + ), + ], + null, + 'Fixer could be risky if one is calling data provider by name as function.' + ); + } + + public function getConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('prefix', 'Prefix that replaces "test".')) + ->setAllowedTypes(['string']) + ->setDefault('provide') + ->getOption(), + (new FixerOptionBuilder('suffix', 'Suffix to be present at the end.')) + ->setAllowedTypes(['string']) + ->setDefault('Cases') + ->getOption(), + ]); + } + + public function getPriority(): int + { + return 0; + } + + public function isRisky(): bool + { + return true; + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $dataProviderAnalyzer = new DataProviderAnalyzer(); + foreach ($dataProviderAnalyzer->getDataProviders($tokens, $startIndex, $endIndex) as $dataProviderAnalysis) { + if (\count($dataProviderAnalysis->getUsageIndices()) > 1) { + continue; + } + + $usageIndex = $dataProviderAnalysis->getUsageIndices()[0]; + if (substr_count($tokens[$usageIndex]->getContent(), '@dataProvider') > 1) { + continue; + } + + $testNameIndex = $tokens->getNextTokenOfKind($usageIndex, [[T_STRING]]); + + $dataProviderNewName = $this->getProviderNameForTestName($tokens[$testNameIndex]->getContent()); + if (null !== $tokens->findSequence([[T_FUNCTION], [T_STRING, $dataProviderNewName]], $startIndex, $endIndex)) { + continue; + } + + $tokens[$dataProviderAnalysis->getNameIndex()] = new Token([T_STRING, $dataProviderNewName]); + + $newCommentContent = Preg::replace( + sprintf('/(@dataProvider\s+)%s/', $dataProviderAnalysis->getName()), + sprintf('$1%s', $dataProviderNewName), + $tokens[$usageIndex]->getContent(), + ); + + $tokens[$usageIndex] = new Token([T_DOC_COMMENT, $newCommentContent]); + } + } + + private function getProviderNameForTestName(string $name): string + { + $name = Preg::replace('/^test_*/i', '', $name); + + if ('' === $this->configuration['prefix']) { + $name = lcfirst($name); + } elseif ('_' !== substr($this->configuration['prefix'], -1)) { + $name = ucfirst($name); + } + + return $this->configuration['prefix'].$name.$this->configuration['suffix']; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderReturnTypeFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderReturnTypeFixer.php new file mode 100644 index 00000000..4c077585 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderReturnTypeFixer.php @@ -0,0 +1,120 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\DataProviderAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + */ +final class PhpUnitDataProviderReturnTypeFixer extends AbstractPhpUnitFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The return type of PHPUnit data provider must be `iterable`.', + [ + new CodeSample( + 'getDataProviders($tokens, $startIndex, $endIndex)) as $dataProviderAnalysis) { + $typeAnalysis = $functionsAnalyzer->getFunctionReturnType($tokens, $dataProviderAnalysis->getNameIndex()); + + if (null === $typeAnalysis) { + $argumentsStart = $tokens->getNextTokenOfKind($dataProviderAnalysis->getNameIndex(), ['(']); + $argumentsEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $argumentsStart); + + $tokens->insertAt( + $argumentsEnd + 1, + [ + new Token([CT::T_TYPE_COLON, ':']), + new Token([T_WHITESPACE, ' ']), + new Token([T_STRING, 'iterable']), + ], + ); + + continue; + } + + if ('iterable' === $typeAnalysis->getName()) { + continue; + } + + $typeStartIndex = $tokens->getNextMeaningfulToken($typeAnalysis->getStartIndex() - 1); + $typeEndIndex = $typeAnalysis->getEndIndex(); + + // @TODO: drop condition and it's body when PHP 8+ is required + if ($tokens->generatePartialCode($typeStartIndex, $typeEndIndex) !== $typeAnalysis->getName()) { + continue; + } + + $tokens->overrideRange($typeStartIndex, $typeEndIndex, [new Token([T_STRING, 'iterable'])]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderStaticFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderStaticFixer.php new file mode 100644 index 00000000..3d4786b7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderStaticFixer.php @@ -0,0 +1,131 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\DataProviderAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Kuba Werłos + */ +final class PhpUnitDataProviderStaticFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Data providers must be static.', + [ + new CodeSample( + 'getData1(); } + public function provideSomethingCases2() { self::getData2(); } +} +', + ['force' => true] + ), + new CodeSample( + 'getData1(); } + public function provideSomething2Cases() { self::getData2(); } +} +', + ['force' => false] + ), + ], + null, + 'Fixer could be risky if one is calling data provider function dynamically.' + ); + } + + public function isRisky(): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder( + 'force', + 'Whether to make the data providers static even if they have a dynamic class call' + .' (may introduce fatal error "using $this when not in object context",' + .' and you may have to adjust the code manually by converting dynamic calls to static ones).' + )) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $dataProviderAnalyzer = new DataProviderAnalyzer(); + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $inserts = []; + foreach ($dataProviderAnalyzer->getDataProviders($tokens, $startIndex, $endIndex) as $dataProviderDefinitionIndex) { + $methodStartIndex = $tokens->getNextTokenOfKind($dataProviderDefinitionIndex->getNameIndex(), ['{']); + if (null !== $methodStartIndex) { + $methodEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $methodStartIndex); + + if (!$this->configuration['force'] && null !== $tokens->findSequence([[T_VARIABLE, '$this']], $methodStartIndex, $methodEndIndex)) { + continue; + } + } + $functionIndex = $tokens->getPrevTokenOfKind($dataProviderDefinitionIndex->getNameIndex(), [[T_FUNCTION]]); + + $methodAttributes = $tokensAnalyzer->getMethodAttributes($functionIndex); + if (false !== $methodAttributes['static']) { + continue; + } + + $inserts[$functionIndex] = [new Token([T_STATIC, 'static']), new Token([T_WHITESPACE, ' '])]; + } + $tokens->insertSlices($inserts); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php new file mode 100644 index 00000000..ed599f5f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php @@ -0,0 +1,628 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class PhpUnitDedicateAssertFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** + * @var array|true> + */ + private static array $fixMap = [ + 'array_key_exists' => [ + 'positive' => 'assertArrayHasKey', + 'negative' => 'assertArrayNotHasKey', + 'argument_count' => 2, + ], + 'empty' => [ + 'positive' => 'assertEmpty', + 'negative' => 'assertNotEmpty', + ], + 'file_exists' => [ + 'positive' => 'assertFileExists', + 'negative' => 'assertFileNotExists', + ], + 'is_array' => true, + 'is_bool' => true, + 'is_callable' => true, + 'is_dir' => [ + 'positive' => 'assertDirectoryExists', + 'negative' => 'assertDirectoryNotExists', + ], + 'is_double' => true, + 'is_float' => true, + 'is_infinite' => [ + 'positive' => 'assertInfinite', + 'negative' => 'assertFinite', + ], + 'is_int' => true, + 'is_integer' => true, + 'is_long' => true, + 'is_nan' => [ + 'positive' => 'assertNan', + 'negative' => false, + ], + 'is_null' => [ + 'positive' => 'assertNull', + 'negative' => 'assertNotNull', + ], + 'is_numeric' => true, + 'is_object' => true, + 'is_readable' => [ + 'positive' => 'assertIsReadable', + 'negative' => 'assertNotIsReadable', + ], + 'is_real' => true, + 'is_resource' => true, + 'is_scalar' => true, + 'is_string' => true, + 'is_writable' => [ + 'positive' => 'assertIsWritable', + 'negative' => 'assertNotIsWritable', + ], + 'str_contains' => [ // since 7.5 + 'positive' => 'assertStringContainsString', + 'negative' => 'assertStringNotContainsString', + 'argument_count' => 2, + 'swap_arguments' => true, + ], + 'str_ends_with' => [ // since 3.4 + 'positive' => 'assertStringEndsWith', + 'negative' => 'assertStringEndsNotWith', + 'argument_count' => 2, + 'swap_arguments' => true, + ], + 'str_starts_with' => [ // since 3.4 + 'positive' => 'assertStringStartsWith', + 'negative' => 'assertStringStartsNotWith', + 'argument_count' => 2, + 'swap_arguments' => true, + ], + ]; + + /** + * @var string[] + */ + private array $functions = []; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + // assertions added in 3.0: assertArrayNotHasKey assertArrayHasKey assertFileNotExists assertFileExists assertNotNull, assertNull + $this->functions = [ + 'array_key_exists', + 'file_exists', + 'is_null', + 'str_ends_with', + 'str_starts_with', + ]; + + if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_3_5)) { + // assertions added in 3.5: assertInternalType assertNotEmpty assertEmpty + $this->functions = array_merge($this->functions, [ + 'empty', + 'is_array', + 'is_bool', + 'is_boolean', + 'is_callable', + 'is_double', + 'is_float', + 'is_int', + 'is_integer', + 'is_long', + 'is_numeric', + 'is_object', + 'is_real', + 'is_scalar', + 'is_string', + ]); + } + + if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_0)) { + // assertions added in 5.0: assertFinite assertInfinite assertNan + $this->functions = array_merge($this->functions, [ + 'is_infinite', + 'is_nan', + ]); + } + + if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_6)) { + // assertions added in 5.6: assertDirectoryExists assertDirectoryNotExists assertIsReadable assertNotIsReadable assertIsWritable assertNotIsWritable + $this->functions = array_merge($this->functions, [ + 'is_dir', + 'is_readable', + 'is_writable', + ]); + } + + if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_7_5)) { + $this->functions = array_merge($this->functions, [ + 'str_contains', + ]); + } + } + + public function isRisky(): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPUnit assertions like `assertInternalType`, `assertFileExists`, should be used over `assertTrue`.', + [ + new CodeSample( + 'assertTrue(is_float( $a), "my message"); + $this->assertTrue(is_nan($a)); + } +} +' + ), + new CodeSample( + 'assertTrue(is_dir($a)); + $this->assertTrue(is_writable($a)); + $this->assertTrue(is_readable($a)); + } +} +', + ['target' => PhpUnitTargetVersion::VERSION_5_6] + ), + ], + null, + 'Fixer could be risky if one is overriding PHPUnit\'s native methods.' + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoUnusedImportsFixer, PhpUnitDedicateAssertInternalTypeFixer. + * Must run after ModernizeStrposFixer, NoAliasFunctionsFixer, PhpUnitConstructFixer. + */ + public function getPriority(): int + { + return -9; + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + foreach ($this->getPreviousAssertCall($tokens, $startIndex, $endIndex) as $assertCall) { + // test and fix for assertTrue/False to dedicated asserts + if ('asserttrue' === $assertCall['loweredName'] || 'assertfalse' === $assertCall['loweredName']) { + $this->fixAssertTrueFalse($tokens, $argumentsAnalyzer, $assertCall); + + continue; + } + + if ( + 'assertsame' === $assertCall['loweredName'] + || 'assertnotsame' === $assertCall['loweredName'] + || 'assertequals' === $assertCall['loweredName'] + || 'assertnotequals' === $assertCall['loweredName'] + ) { + $this->fixAssertSameEquals($tokens, $assertCall); + + continue; + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([ + PhpUnitTargetVersion::VERSION_3_0, + PhpUnitTargetVersion::VERSION_3_5, + PhpUnitTargetVersion::VERSION_5_0, + PhpUnitTargetVersion::VERSION_5_6, + PhpUnitTargetVersion::VERSION_NEWEST, + ]) + ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) + ->getOption(), + ]); + } + + /** + * @param array{ + * index: int, + * loweredName: string, + * openBraceIndex: int, + * closeBraceIndex: int, + * } $assertCall + */ + private function fixAssertTrueFalse(Tokens $tokens, ArgumentsAnalyzer $argumentsAnalyzer, array $assertCall): void + { + $testDefaultNamespaceTokenIndex = null; + $testIndex = $tokens->getNextMeaningfulToken($assertCall['openBraceIndex']); + + if (!$tokens[$testIndex]->isGivenKind([T_EMPTY, T_STRING])) { + if ($this->fixAssertTrueFalseInstanceof($tokens, $assertCall, $testIndex)) { + return; + } + + if (!$tokens[$testIndex]->isGivenKind(T_NS_SEPARATOR)) { + return; + } + + $testDefaultNamespaceTokenIndex = $testIndex; + $testIndex = $tokens->getNextMeaningfulToken($testIndex); + } + + $testOpenIndex = $tokens->getNextMeaningfulToken($testIndex); + + if (!$tokens[$testOpenIndex]->equals('(')) { + return; + } + + $testCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $testOpenIndex); + $assertCallCloseIndex = $tokens->getNextMeaningfulToken($testCloseIndex); + + if (!$tokens[$assertCallCloseIndex]->equalsAny([')', ','])) { + return; + } + + $content = strtolower($tokens[$testIndex]->getContent()); + + if (!\in_array($content, $this->functions, true)) { + return; + } + + $arguments = $argumentsAnalyzer->getArguments($tokens, $testOpenIndex, $testCloseIndex); + $isPositive = 'asserttrue' === $assertCall['loweredName']; + + if (\is_array(self::$fixMap[$content])) { + $expectedCount = self::$fixMap[$content]['argument_count'] ?? 1; + + if ($expectedCount !== \count($arguments)) { + return; + } + + $isPositive = $isPositive ? 'positive' : 'negative'; + + if (false === self::$fixMap[$content][$isPositive]) { + return; + } + + $tokens[$assertCall['index']] = new Token([T_STRING, self::$fixMap[$content][$isPositive]]); + $this->removeFunctionCall($tokens, $testDefaultNamespaceTokenIndex, $testIndex, $testOpenIndex, $testCloseIndex); + + if (self::$fixMap[$content]['swap_arguments'] ?? false) { + if (2 !== $expectedCount) { + throw new \RuntimeException('Can only swap two arguments, please update map or logic.'); + } + + $this->swapArguments($tokens, $arguments); + } + + return; + } + + if (1 !== \count($arguments)) { + return; + } + + $type = substr($content, 3); + + $tokens[$assertCall['index']] = new Token([T_STRING, $isPositive ? 'assertInternalType' : 'assertNotInternalType']); + $tokens[$testIndex] = new Token([T_CONSTANT_ENCAPSED_STRING, "'".$type."'"]); + $tokens[$testOpenIndex] = new Token(','); + + $tokens->clearTokenAndMergeSurroundingWhitespace($testCloseIndex); + $commaIndex = $tokens->getPrevMeaningfulToken($testCloseIndex); + + if ($tokens[$commaIndex]->equals(',')) { + $tokens->removeTrailingWhitespace($commaIndex); + $tokens->clearAt($commaIndex); + } + + if (!$tokens[$testOpenIndex + 1]->isWhitespace()) { + $tokens->insertAt($testOpenIndex + 1, new Token([T_WHITESPACE, ' '])); + } + + if (null !== $testDefaultNamespaceTokenIndex) { + $tokens->clearTokenAndMergeSurroundingWhitespace($testDefaultNamespaceTokenIndex); + } + } + + /** + * @param array{ + * index: int, + * loweredName: string, + * openBraceIndex: int, + * closeBraceIndex: int, + * } $assertCall + */ + private function fixAssertTrueFalseInstanceof(Tokens $tokens, array $assertCall, int $testIndex): bool + { + if ($tokens[$testIndex]->equals('!')) { + $variableIndex = $tokens->getNextMeaningfulToken($testIndex); + $positive = false; + } else { + $variableIndex = $testIndex; + $positive = true; + } + + if (!$tokens[$variableIndex]->isGivenKind(T_VARIABLE)) { + return false; + } + + $instanceOfIndex = $tokens->getNextMeaningfulToken($variableIndex); + + if (!$tokens[$instanceOfIndex]->isGivenKind(T_INSTANCEOF)) { + return false; + } + + $classEndIndex = $instanceOfIndex; + $classPartTokens = []; + + do { + $classEndIndex = $tokens->getNextMeaningfulToken($classEndIndex); + $classPartTokens[] = $tokens[$classEndIndex]; + } while ($tokens[$classEndIndex]->isGivenKind([T_STRING, T_NS_SEPARATOR, T_VARIABLE])); + + if ($tokens[$classEndIndex]->equalsAny([',', ')'])) { // do the fixing + array_pop($classPartTokens); + $isInstanceOfVar = reset($classPartTokens)->isGivenKind(T_VARIABLE); + $insertIndex = $testIndex - 1; + $newTokens = []; + + foreach ($classPartTokens as $token) { + $newTokens[++$insertIndex] = clone $token; + } + + if (!$isInstanceOfVar) { + $newTokens[++$insertIndex] = new Token([T_DOUBLE_COLON, '::']); + $newTokens[++$insertIndex] = new Token([CT::T_CLASS_CONSTANT, 'class']); + } + + $newTokens[++$insertIndex] = new Token(','); + $newTokens[++$insertIndex] = new Token([T_WHITESPACE, ' ']); + $newTokens[++$insertIndex] = clone $tokens[$variableIndex]; + + for ($i = $classEndIndex - 1; $i >= $testIndex; --$i) { + if (!$tokens[$i]->isComment()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } + + $tokens->insertSlices($newTokens); + $tokens[$assertCall['index']] = new Token([T_STRING, $positive ? 'assertInstanceOf' : 'assertNotInstanceOf']); + } + + return true; + } + + /** + * @param array{ + * index: int, + * loweredName: string, + * openBraceIndex: int, + * closeBraceIndex: int, + * } $assertCall + */ + private function fixAssertSameEquals(Tokens $tokens, array $assertCall): void + { + // @ $this->/self::assertEquals/Same([$nextIndex]) + $expectedIndex = $tokens->getNextMeaningfulToken($assertCall['openBraceIndex']); + + // do not fix + // let $a = [1,2]; $b = "2"; + // "$this->assertEquals("2", count($a)); $this->assertEquals($b, count($a)); $this->assertEquals(2.1, count($a));" + + if ($tokens[$expectedIndex]->isGivenKind([T_VARIABLE])) { + if (!$tokens[$tokens->getNextMeaningfulToken($expectedIndex)]->equals(',')) { + return; + } + } elseif (!$tokens[$expectedIndex]->isGivenKind([T_LNUMBER, T_VARIABLE])) { + return; + } + + // @ $this->/self::assertEquals/Same([$nextIndex,$commaIndex]) + $commaIndex = $tokens->getNextMeaningfulToken($expectedIndex); + + if (!$tokens[$commaIndex]->equals(',')) { + return; + } + + // @ $this->/self::assertEquals/Same([$nextIndex,$commaIndex,$countCallIndex]) + $countCallIndex = $tokens->getNextMeaningfulToken($commaIndex); + + if ($tokens[$countCallIndex]->isGivenKind(T_NS_SEPARATOR)) { + $defaultNamespaceTokenIndex = $countCallIndex; + $countCallIndex = $tokens->getNextMeaningfulToken($countCallIndex); + } else { + $defaultNamespaceTokenIndex = null; + } + + if (!$tokens[$countCallIndex]->isGivenKind(T_STRING)) { + return; + } + + $lowerContent = strtolower($tokens[$countCallIndex]->getContent()); + + if ('count' !== $lowerContent && 'sizeof' !== $lowerContent) { + return; // not a call to "count" or "sizeOf" + } + + // @ $this->/self::assertEquals/Same([$nextIndex,$commaIndex,[$defaultNamespaceTokenIndex,]$countCallIndex,$countCallOpenBraceIndex]) + $countCallOpenBraceIndex = $tokens->getNextMeaningfulToken($countCallIndex); + + if (!$tokens[$countCallOpenBraceIndex]->equals('(')) { + return; + } + + $countCallCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $countCallOpenBraceIndex); + $afterCountCallCloseBraceIndex = $tokens->getNextMeaningfulToken($countCallCloseBraceIndex); + + if (!$tokens[$afterCountCallCloseBraceIndex]->equalsAny([')', ','])) { + return; + } + + $this->removeFunctionCall( + $tokens, + $defaultNamespaceTokenIndex, + $countCallIndex, + $countCallOpenBraceIndex, + $countCallCloseBraceIndex + ); + + $tokens[$assertCall['index']] = new Token([ + T_STRING, + false === strpos($assertCall['loweredName'], 'not', 6) ? 'assertCount' : 'assertNotCount', + ]); + } + + /** + * @return iterable + */ + private function getPreviousAssertCall(Tokens $tokens, int $startIndex, int $endIndex): iterable + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + for ($index = $endIndex; $index > $startIndex; --$index) { + $index = $tokens->getPrevTokenOfKind($index, [[T_STRING]]); + + if (null === $index) { + return; + } + + // test if "assert" something call + $loweredContent = strtolower($tokens[$index]->getContent()); + + if (!str_starts_with($loweredContent, 'assert')) { + continue; + } + + // test candidate for simple calls like: ([\]+'some fixable call'(...)) + $openBraceIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$openBraceIndex]->equals('(')) { + continue; + } + + if (!$functionsAnalyzer->isTheSameClassCall($tokens, $index)) { + continue; + } + + yield [ + 'index' => $index, + 'loweredName' => $loweredContent, + 'openBraceIndex' => $openBraceIndex, + 'closeBraceIndex' => $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openBraceIndex), + ]; + } + } + + private function removeFunctionCall(Tokens $tokens, ?int $callNSIndex, int $callIndex, int $openIndex, int $closeIndex): void + { + $tokens->clearTokenAndMergeSurroundingWhitespace($callIndex); + + if (null !== $callNSIndex) { + $tokens->clearTokenAndMergeSurroundingWhitespace($callNSIndex); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($openIndex); + $commaIndex = $tokens->getPrevMeaningfulToken($closeIndex); + + if ($tokens[$commaIndex]->equals(',')) { + $tokens->removeTrailingWhitespace($commaIndex); + $tokens->clearAt($commaIndex); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex); + } + + /** + * @param array $argumentsIndices + */ + private function swapArguments(Tokens $tokens, array $argumentsIndices): void + { + [$firstArgumentIndex, $secondArgumentIndex] = array_keys($argumentsIndices); + + $firstArgumentEndIndex = $argumentsIndices[$firstArgumentIndex]; + $secondArgumentEndIndex = $argumentsIndices[$secondArgumentIndex]; + + $firstClone = $this->cloneAndClearTokens($tokens, $firstArgumentIndex, $firstArgumentEndIndex); + $secondClone = $this->cloneAndClearTokens($tokens, $secondArgumentIndex, $secondArgumentEndIndex); + + if (!$firstClone[0]->isWhitespace()) { + array_unshift($firstClone, new Token([T_WHITESPACE, ' '])); + } + + $tokens->insertAt($secondArgumentIndex, $firstClone); + + if ($secondClone[0]->isWhitespace()) { + array_shift($secondClone); + } + + $tokens->insertAt($firstArgumentIndex, $secondClone); + } + + /** + * @return list + */ + private function cloneAndClearTokens(Tokens $tokens, int $start, int $end): array + { + $clone = []; + + for ($i = $start; $i <= $end; ++$i) { + if ('' === $tokens[$i]->getContent()) { + continue; + } + + $clone[] = clone $tokens[$i]; + $tokens->clearAt($i); + } + + return $clone; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php new file mode 100644 index 00000000..b6e955ea --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php @@ -0,0 +1,191 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Filippo Tessarotto + */ +final class PhpUnitDedicateAssertInternalTypeFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private array $typeToDedicatedAssertMap = [ + 'array' => 'assertIsArray', + 'boolean' => 'assertIsBool', + 'bool' => 'assertIsBool', + 'double' => 'assertIsFloat', + 'float' => 'assertIsFloat', + 'integer' => 'assertIsInt', + 'int' => 'assertIsInt', + 'null' => 'assertNull', + 'numeric' => 'assertIsNumeric', + 'object' => 'assertIsObject', + 'real' => 'assertIsFloat', + 'resource' => 'assertIsResource', + 'string' => 'assertIsString', + 'scalar' => 'assertIsScalar', + 'callable' => 'assertIsCallable', + 'iterable' => 'assertIsIterable', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPUnit assertions like `assertIsArray` should be used over `assertInternalType`.', + [ + new CodeSample( + 'assertInternalType("array", $var); + $this->assertInternalType("boolean", $var); + } +} +' + ), + new CodeSample( + 'assertInternalType("array", $var); + $this->assertInternalType("boolean", $var); + } +} +', + ['target' => PhpUnitTargetVersion::VERSION_7_5] + ), + ], + null, + 'Risky when PHPUnit methods are overridden or when project has PHPUnit incompatibilities.' + ); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run after NoBinaryStringFixer, NoUselessConcatOperatorFixer, PhpUnitDedicateAssertFixer. + */ + public function getPriority(): int + { + return -16; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([PhpUnitTargetVersion::VERSION_7_5, PhpUnitTargetVersion::VERSION_NEWEST]) + ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $anonymousClassIndices = []; + $tokenAnalyzer = new TokensAnalyzer($tokens); + + for ($index = $startIndex; $index < $endIndex; ++$index) { + if (!$tokens[$index]->isGivenKind(T_CLASS) || !$tokenAnalyzer->isAnonymousClass($index)) { + continue; + } + + $openingBraceIndex = $tokens->getNextTokenOfKind($index, ['{']); + $closingBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openingBraceIndex); + + $anonymousClassIndices[$closingBraceIndex] = $openingBraceIndex; + } + + for ($index = $endIndex - 1; $index > $startIndex; --$index) { + if (isset($anonymousClassIndices[$index])) { + $index = $anonymousClassIndices[$index]; + + continue; + } + + if (!$tokens[$index]->isGivenKind(T_STRING)) { + continue; + } + + $functionName = strtolower($tokens[$index]->getContent()); + + if ('assertinternaltype' !== $functionName && 'assertnotinternaltype' !== $functionName) { + continue; + } + + $bracketTokenIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$bracketTokenIndex]->equals('(')) { + continue; + } + + $expectedTypeTokenIndex = $tokens->getNextMeaningfulToken($bracketTokenIndex); + $expectedTypeToken = $tokens[$expectedTypeTokenIndex]; + + if (!$expectedTypeToken->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) { + continue; + } + + $expectedType = trim($expectedTypeToken->getContent(), '\'"'); + + if (!isset($this->typeToDedicatedAssertMap[$expectedType])) { + continue; + } + + $commaTokenIndex = $tokens->getNextMeaningfulToken($expectedTypeTokenIndex); + + if (!$tokens[$commaTokenIndex]->equals(',')) { + continue; + } + + $newAssertion = $this->typeToDedicatedAssertMap[$expectedType]; + + if ('assertnotinternaltype' === $functionName) { + $newAssertion = str_replace('Is', 'IsNot', $newAssertion); + $newAssertion = str_replace('Null', 'NotNull', $newAssertion); + } + + $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($commaTokenIndex); + + $tokens->overrideRange($index, $nextMeaningfulTokenIndex - 1, [ + new Token([T_STRING, $newAssertion]), + new Token('('), + ]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitExpectationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitExpectationFixer.php new file mode 100644 index 00000000..ca8464d2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitExpectationFixer.php @@ -0,0 +1,274 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class PhpUnitExpectationFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @var array + */ + private array $methodMap = []; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->methodMap = [ + 'setExpectedException' => 'expectExceptionMessage', + ]; + + if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_6)) { + $this->methodMap['setExpectedExceptionRegExp'] = 'expectExceptionMessageRegExp'; + } + + if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_8_4)) { + $this->methodMap['setExpectedExceptionRegExp'] = 'expectExceptionMessageMatches'; + $this->methodMap['expectExceptionMessageRegExp'] = 'expectExceptionMessageMatches'; + } + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Usages of `->setExpectedException*` methods MUST be replaced by `->expectException*` methods.', + [ + new CodeSample( + 'setExpectedException("RuntimeException", "Msg", 123); + foo(); + } + + public function testBar() + { + $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123); + bar(); + } +} +' + ), + new CodeSample( + 'setExpectedException("RuntimeException", null, 123); + foo(); + } + + public function testBar() + { + $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123); + bar(); + } +} +', + ['target' => PhpUnitTargetVersion::VERSION_8_4] + ), + new CodeSample( + 'setExpectedException("RuntimeException", null, 123); + foo(); + } + + public function testBar() + { + $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123); + bar(); + } +} +', + ['target' => PhpUnitTargetVersion::VERSION_5_6] + ), + new CodeSample( + 'setExpectedException("RuntimeException", "Msg", 123); + foo(); + } + + public function testBar() + { + $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123); + bar(); + } +} +', + ['target' => PhpUnitTargetVersion::VERSION_5_2] + ), + ], + null, + 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.' + ); + } + + /** + * {@inheritdoc} + * + * Must run after PhpUnitNoExpectationAnnotationFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isRisky(): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([PhpUnitTargetVersion::VERSION_5_2, PhpUnitTargetVersion::VERSION_5_6, PhpUnitTargetVersion::VERSION_8_4, PhpUnitTargetVersion::VERSION_NEWEST]) + ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + foreach (Token::getObjectOperatorKinds() as $objectOperator) { + $this->applyPhpUnitClassFixWithObjectOperator($tokens, $startIndex, $endIndex, $objectOperator); + } + } + + private function applyPhpUnitClassFixWithObjectOperator(Tokens $tokens, int $startIndex, int $endIndex, int $objectOperator): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + $oldMethodSequence = [ + [T_VARIABLE, '$this'], + [$objectOperator], + [T_STRING], + ]; + + for ($index = $startIndex; $startIndex < $endIndex; ++$index) { + $match = $tokens->findSequence($oldMethodSequence, $index); + + if (null === $match) { + return; + } + + [$thisIndex, , $index] = array_keys($match); + + if (!isset($this->methodMap[$tokens[$index]->getContent()])) { + continue; + } + + $openIndex = $tokens->getNextTokenOfKind($index, ['(']); + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); + $commaIndex = $tokens->getPrevMeaningfulToken($closeIndex); + if ($tokens[$commaIndex]->equals(',')) { + $tokens->removeTrailingWhitespace($commaIndex); + $tokens->clearAt($commaIndex); + } + + $arguments = $argumentsAnalyzer->getArguments($tokens, $openIndex, $closeIndex); + $argumentsCnt = \count($arguments); + + $argumentsReplacements = ['expectException', $this->methodMap[$tokens[$index]->getContent()], 'expectExceptionCode']; + + $indent = $this->whitespacesConfig->getLineEnding().WhitespacesAnalyzer::detectIndent($tokens, $thisIndex); + + $isMultilineWhitespace = false; + + for ($cnt = $argumentsCnt - 1; $cnt >= 1; --$cnt) { + $argStart = array_keys($arguments)[$cnt]; + $argBefore = $tokens->getPrevMeaningfulToken($argStart); + + if ('expectExceptionMessage' === $argumentsReplacements[$cnt]) { + $paramIndicatorIndex = $tokens->getNextMeaningfulToken($argBefore); + $afterParamIndicatorIndex = $tokens->getNextMeaningfulToken($paramIndicatorIndex); + + if ( + $tokens[$paramIndicatorIndex]->equals([T_STRING, 'null'], false) + && $tokens[$afterParamIndicatorIndex]->equals(')') + ) { + if ($tokens[$argBefore + 1]->isWhitespace()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($argBefore + 1); + } + $tokens->clearTokenAndMergeSurroundingWhitespace($argBefore); + $tokens->clearTokenAndMergeSurroundingWhitespace($paramIndicatorIndex); + + continue; + } + } + + $isMultilineWhitespace = $isMultilineWhitespace || ($tokens[$argStart]->isWhitespace() && !$tokens[$argStart]->isWhitespace(" \t")); + $tokensOverrideArgStart = [ + new Token([T_WHITESPACE, $indent]), + new Token([T_VARIABLE, '$this']), + new Token([T_OBJECT_OPERATOR, '->']), + new Token([T_STRING, $argumentsReplacements[$cnt]]), + new Token('('), + ]; + $tokensOverrideArgBefore = [ + new Token(')'), + new Token(';'), + ]; + + if ($isMultilineWhitespace) { + $tokensOverrideArgStart[] = new Token([T_WHITESPACE, $indent.$this->whitespacesConfig->getIndent()]); + array_unshift($tokensOverrideArgBefore, new Token([T_WHITESPACE, $indent])); + } + + if ($tokens[$argStart]->isWhitespace()) { + $tokens->overrideRange($argStart, $argStart, $tokensOverrideArgStart); + } else { + $tokens->insertAt($argStart, $tokensOverrideArgStart); + } + + $tokens->overrideRange($argBefore, $argBefore, $tokensOverrideArgBefore); + } + + $methodName = 'expectException'; + if ('expectExceptionMessageRegExp' === $tokens[$index]->getContent()) { + $methodName = $this->methodMap[$tokens[$index]->getContent()]; + } + $tokens[$index] = new Token([T_STRING, $methodName]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php new file mode 100644 index 00000000..65ae1ada --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php @@ -0,0 +1,86 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Roland Franssen + */ +final class PhpUnitFqcnAnnotationFixer extends AbstractPhpUnitFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPUnit annotations should be a FQCNs including a root namespace.', + [new CodeSample( + 'getPrevTokenOfKind($startIndex, [[T_DOC_COMMENT]]); + + if (null !== $prevDocCommentIndex) { + $startIndex = $prevDocCommentIndex; + } + + $this->fixPhpUnitClass($tokens, $startIndex, $endIndex); + } + + private function fixPhpUnitClass(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($index = $startIndex; $index < $endIndex; ++$index) { + if ($tokens[$index]->isGivenKind(T_DOC_COMMENT)) { + $tokens[$index] = new Token([T_DOC_COMMENT, Preg::replace( + '~^(\s*\*\s*@(?:expectedException|covers|coversDefaultClass|uses)\h+)(?!(?:self|static)::)(\w.*)$~m', + '$1\\\\$2', + $tokens[$index]->getContent() + )]); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php new file mode 100644 index 00000000..6d89deb5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php @@ -0,0 +1,103 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Gert de Pagter + */ +final class PhpUnitInternalClassFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'All PHPUnit test classes should be marked as internal.', + [ + new CodeSample(" ['final']] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before FinalInternalClassFixer, PhpdocSeparationFixer. + */ + public function getPriority(): int + { + return 68; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $types = ['normal', 'final', 'abstract']; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('types', 'What types of classes to mark as internal.')) + ->setAllowedValues([new AllowedValueSubset($types)]) + ->setAllowedTypes(['array']) + ->setDefault(['normal', 'final']) + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $classIndex = $tokens->getPrevTokenOfKind($startIndex, [[T_CLASS]]); + + if (!$this->isAllowedByConfiguration($tokens, $classIndex)) { + return; + } + + $this->ensureIsDockBlockWithAnnotation( + $tokens, + $classIndex, + 'internal', + ['internal'] + ); + } + + private function isAllowedByConfiguration(Tokens $tokens, int $index): bool + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $modifiers = $tokensAnalyzer->getClassyModifiers($index); + + if (isset($modifiers['final'])) { + return \in_array('final', $this->configuration['types'], true); + } + + if (isset($modifiers['abstract'])) { + return \in_array('abstract', $this->configuration['types'], true); + } + + return \in_array('normal', $this->configuration['types'], true); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.php new file mode 100644 index 00000000..04a3e5f7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.php @@ -0,0 +1,196 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; + +/** + * @author Filippo Tessarotto + */ +final class PhpUnitMethodCasingFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const CAMEL_CASE = 'camel_case'; + + /** + * @internal + */ + public const SNAKE_CASE = 'snake_case'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Enforce camel (or snake) case for PHPUnit test methods, following configuration.', + [ + new CodeSample( + ' self::SNAKE_CASE] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run after PhpUnitTestAnnotationFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('case', 'Apply camel or snake case to test methods.')) + ->setAllowedValues([self::CAMEL_CASE, self::SNAKE_CASE]) + ->setDefault(self::CAMEL_CASE) + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($index = $endIndex - 1; $index > $startIndex; --$index) { + if (!$this->isTestMethod($tokens, $index)) { + continue; + } + + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + $functionName = $tokens[$functionNameIndex]->getContent(); + $newFunctionName = $this->updateMethodCasing($functionName); + + if ($newFunctionName !== $functionName) { + $tokens[$functionNameIndex] = new Token([T_STRING, $newFunctionName]); + } + + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + + if ($this->isPHPDoc($tokens, $docBlockIndex)) { + $this->updateDocBlock($tokens, $docBlockIndex); + } + } + } + + private function updateMethodCasing(string $functionName): string + { + $parts = explode('::', $functionName); + + $functionNamePart = array_pop($parts); + + if (self::CAMEL_CASE === $this->configuration['case']) { + $newFunctionNamePart = $functionNamePart; + $newFunctionNamePart = ucwords($newFunctionNamePart, '_'); + $newFunctionNamePart = str_replace('_', '', $newFunctionNamePart); + $newFunctionNamePart = lcfirst($newFunctionNamePart); + } else { + $newFunctionNamePart = Utils::camelCaseToUnderscore($functionNamePart); + } + + $parts[] = $newFunctionNamePart; + + return implode('::', $parts); + } + + private function isTestMethod(Tokens $tokens, int $index): bool + { + // Check if we are dealing with a (non-abstract, non-lambda) function + if (!$this->isMethod($tokens, $index)) { + return false; + } + + // if the function name starts with test it's a test + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + $functionName = $tokens[$functionNameIndex]->getContent(); + + if (str_starts_with($functionName, 'test')) { + return true; + } + + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + + return + $this->isPHPDoc($tokens, $docBlockIndex) // If the function doesn't have test in its name, and no doc block, it's not a test + && str_contains($tokens[$docBlockIndex]->getContent(), '@test'); + } + + private function isMethod(Tokens $tokens, int $index): bool + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + return $tokens[$index]->isGivenKind(T_FUNCTION) && !$tokensAnalyzer->isLambda($index); + } + + private function updateDocBlock(Tokens $tokens, int $docBlockIndex): void + { + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + $lines = $doc->getLines(); + + $docBlockNeedsUpdate = false; + for ($inc = 0; $inc < \count($lines); ++$inc) { + $lineContent = $lines[$inc]->getContent(); + if (!str_contains($lineContent, '@depends')) { + continue; + } + + $newLineContent = Preg::replaceCallback('/(@depends\s+)(.+)(\b)/', fn (array $matches): string => sprintf( + '%s%s%s', + $matches[1], + $this->updateMethodCasing($matches[2]), + $matches[3] + ), $lineContent); + + if ($newLineContent !== $lineContent) { + $lines[$inc] = new Line($newLineContent); + $docBlockNeedsUpdate = true; + } + } + + if ($docBlockNeedsUpdate) { + $lines = implode('', $lines); + $tokens[$docBlockIndex] = new Token([T_DOC_COMMENT, $lines]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockFixer.php new file mode 100644 index 00000000..a3d3484c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockFixer.php @@ -0,0 +1,127 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class PhpUnitMockFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** + * @var bool + */ + private $fixCreatePartialMock; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Usages of `->getMock` and `->getMockWithoutInvokingTheOriginalConstructor` methods MUST be replaced by `->createMock` or `->createPartialMock` methods.', + [ + new CodeSample( + 'getMockWithoutInvokingTheOriginalConstructor("Foo"); + $mock1 = $this->getMock("Foo"); + $mock1 = $this->getMock("Bar", ["aaa"]); + $mock1 = $this->getMock("Baz", ["aaa"], ["argument"]); // version with more than 2 params is not supported + } +} +' + ), + new CodeSample( + 'getMock("Foo"); + $mock1 = $this->getMock("Bar", ["aaa"]); // version with multiple params is not supported + } +} +', + ['target' => PhpUnitTargetVersion::VERSION_5_4] + ), + ], + null, + 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.' + ); + } + + public function isRisky(): bool + { + return true; + } + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->fixCreatePartialMock = PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_5); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + for ($index = $startIndex; $index < $endIndex; ++$index) { + if (!$tokens[$index]->isObjectOperator()) { + continue; + } + + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->equals([T_STRING, 'getMockWithoutInvokingTheOriginalConstructor'], false)) { + $tokens[$index] = new Token([T_STRING, 'createMock']); + } elseif ($tokens[$index]->equals([T_STRING, 'getMock'], false)) { + $openingParenthesis = $tokens->getNextMeaningfulToken($index); + $closingParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingParenthesis); + + $argumentsCount = $argumentsAnalyzer->countArguments($tokens, $openingParenthesis, $closingParenthesis); + + if (1 === $argumentsCount) { + $tokens[$index] = new Token([T_STRING, 'createMock']); + } elseif (2 === $argumentsCount && true === $this->fixCreatePartialMock) { + $tokens[$index] = new Token([T_STRING, 'createPartialMock']); + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([PhpUnitTargetVersion::VERSION_5_4, PhpUnitTargetVersion::VERSION_5_5, PhpUnitTargetVersion::VERSION_NEWEST]) + ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php new file mode 100644 index 00000000..e429a7ae --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php @@ -0,0 +1,127 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Michał Adamski + * @author Kuba Werłos + */ +final class PhpUnitMockShortWillReturnFixer extends AbstractPhpUnitFixer +{ + private const RETURN_METHODS_MAP = [ + 'returnargument' => 'willReturnArgument', + 'returncallback' => 'willReturnCallback', + 'returnself' => 'willReturnSelf', + 'returnvalue' => 'willReturn', + 'returnvaluemap' => 'willReturnMap', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Usage of PHPUnit\'s mock e.g. `->will($this->returnValue(..))` must be replaced by its shorter equivalent such as `->willReturn(...)`.', + [ + new CodeSample('createMock(Some::class); + $someMock->method("some")->will($this->returnSelf()); + $someMock->method("some")->will($this->returnValue("example")); + $someMock->method("some")->will($this->returnArgument(2)); + $someMock->method("some")->will($this->returnCallback("str_rot13")); + $someMock->method("some")->will($this->returnValueMap(["a","b","c"])); + } +} +'), + ], + null, + 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.' + ); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + for ($index = $startIndex; $index < $endIndex; ++$index) { + if (!$tokens[$index]->isObjectOperator()) { + continue; + } + + $functionToReplaceIndex = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$functionToReplaceIndex]->equals([T_STRING, 'will'], false)) { + continue; + } + + $functionToReplaceOpeningBraceIndex = $tokens->getNextMeaningfulToken($functionToReplaceIndex); + + if (!$tokens[$functionToReplaceOpeningBraceIndex]->equals('(')) { + continue; + } + + $classReferenceIndex = $tokens->getNextMeaningfulToken($functionToReplaceOpeningBraceIndex); + $objectOperatorIndex = $tokens->getNextMeaningfulToken($classReferenceIndex); + $functionToRemoveIndex = $tokens->getNextMeaningfulToken($objectOperatorIndex); + + if (!$functionsAnalyzer->isTheSameClassCall($tokens, $functionToRemoveIndex)) { + continue; + } + + if (!\array_key_exists(strtolower($tokens[$functionToRemoveIndex]->getContent()), self::RETURN_METHODS_MAP)) { + continue; + } + + $openingBraceIndex = $tokens->getNextMeaningfulToken($functionToRemoveIndex); + + if (!$tokens[$openingBraceIndex]->equals('(')) { + continue; + } + + if ($tokens[$tokens->getNextMeaningfulToken($openingBraceIndex)]->isGivenKind(CT::T_FIRST_CLASS_CALLABLE)) { + continue; + } + + $closingBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingBraceIndex); + + $tokens[$functionToReplaceIndex] = new Token([T_STRING, self::RETURN_METHODS_MAP[strtolower($tokens[$functionToRemoveIndex]->getContent())]]); + $tokens->clearTokenAndMergeSurroundingWhitespace($classReferenceIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($objectOperatorIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($functionToRemoveIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($openingBraceIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($closingBraceIndex); + + $commaAfterClosingBraceIndex = $tokens->getNextMeaningfulToken($closingBraceIndex); + if ($tokens[$commaAfterClosingBraceIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($commaAfterClosingBraceIndex); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNamespacedFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNamespacedFixer.php new file mode 100644 index 00000000..4221fe92 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNamespacedFixer.php @@ -0,0 +1,227 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\ClassyAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class PhpUnitNamespacedFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var string + */ + private $originalClassRegEx; + + /** + * Class Mappings. + * + * * [original classname => new classname] Some classes which match the + * original class regular expression do not have a same-compound name- + * space class and need a dedicated translation table. This trans- + * lation table is defined in @see configure. + * + * @var array|string[] Class Mappings + */ + private $classMap; + + public function getDefinition(): FixerDefinitionInterface + { + $codeSample = ' PhpUnitTargetVersion::VERSION_4_8]), + ], + "PHPUnit v6 has finally fully switched to namespaces.\n" + ."You could start preparing the upgrade by switching from non-namespaced TestCase to namespaced one.\n" + .'Forward compatibility layer (`\PHPUnit\Framework\TestCase` class) was backported to PHPUnit v4.8.35 and PHPUnit v5.4.0.'."\n" + .'Extended forward compatibility layer (`PHPUnit\Framework\Assert`, `PHPUnit\Framework\BaseTestListener`, `PHPUnit\Framework\TestListener` classes) was introduced in v5.7.0.'."\n", + 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.' + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + public function configure(array $configuration): void + { + parent::configure($configuration); + + if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_6_0)) { + $this->originalClassRegEx = '/^PHPUnit_\w+$/i'; + // @noinspection ClassConstantCanBeUsedInspection + $this->classMap = [ + 'PHPUnit_Extensions_PhptTestCase' => 'PHPUnit\Runner\PhptTestCase', + 'PHPUnit_Framework_Constraint' => 'PHPUnit\Framework\Constraint\Constraint', + 'PHPUnit_Framework_Constraint_StringMatches' => 'PHPUnit\Framework\Constraint\StringMatchesFormatDescription', + 'PHPUnit_Framework_Constraint_JsonMatches_ErrorMessageProvider' => 'PHPUnit\Framework\Constraint\JsonMatchesErrorMessageProvider', + 'PHPUnit_Framework_Constraint_PCREMatch' => 'PHPUnit\Framework\Constraint\RegularExpression', + 'PHPUnit_Framework_Constraint_ExceptionMessageRegExp' => 'PHPUnit\Framework\Constraint\ExceptionMessageRegularExpression', + 'PHPUnit_Framework_Constraint_And' => 'PHPUnit\Framework\Constraint\LogicalAnd', + 'PHPUnit_Framework_Constraint_Or' => 'PHPUnit\Framework\Constraint\LogicalOr', + 'PHPUnit_Framework_Constraint_Not' => 'PHPUnit\Framework\Constraint\LogicalNot', + 'PHPUnit_Framework_Constraint_Xor' => 'PHPUnit\Framework\Constraint\LogicalXor', + 'PHPUnit_Framework_Error' => 'PHPUnit\Framework\Error\Error', + 'PHPUnit_Framework_TestSuite_DataProvider' => 'PHPUnit\Framework\DataProviderTestSuite', + 'PHPUnit_Framework_MockObject_Invocation_Static' => 'PHPUnit\Framework\MockObject\Invocation\StaticInvocation', + 'PHPUnit_Framework_MockObject_Invocation_Object' => 'PHPUnit\Framework\MockObject\Invocation\ObjectInvocation', + 'PHPUnit_Framework_MockObject_Stub_Return' => 'PHPUnit\Framework\MockObject\Stub\ReturnStub', + 'PHPUnit_Runner_Filter_Group_Exclude' => 'PHPUnit\Runner\Filter\ExcludeGroupFilterIterator', + 'PHPUnit_Runner_Filter_Group_Include' => 'PHPUnit\Runner\Filter\IncludeGroupFilterIterator', + 'PHPUnit_Runner_Filter_Test' => 'PHPUnit\Runner\Filter\NameFilterIterator', + 'PHPUnit_Util_PHP' => 'PHPUnit\Util\PHP\AbstractPhpProcess', + 'PHPUnit_Util_PHP_Default' => 'PHPUnit\Util\PHP\DefaultPhpProcess', + 'PHPUnit_Util_PHP_Windows' => 'PHPUnit\Util\PHP\WindowsPhpProcess', + 'PHPUnit_Util_Regex' => 'PHPUnit\Util\RegularExpression', + 'PHPUnit_Util_TestDox_ResultPrinter_XML' => 'PHPUnit\Util\TestDox\XmlResultPrinter', + 'PHPUnit_Util_TestDox_ResultPrinter_HTML' => 'PHPUnit\Util\TestDox\HtmlResultPrinter', + 'PHPUnit_Util_TestDox_ResultPrinter_Text' => 'PHPUnit\Util\TestDox\TextResultPrinter', + 'PHPUnit_Util_TestSuiteIterator' => 'PHPUnit\Framework\TestSuiteIterator', + 'PHPUnit_Util_XML' => 'PHPUnit\Util\Xml', + ]; + } elseif (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_7)) { + $this->originalClassRegEx = '/^PHPUnit_Framework_(TestCase|Assert|BaseTestListener|TestListener)+$/i'; + $this->classMap = []; + } else { + $this->originalClassRegEx = '/^PHPUnit_Framework_TestCase$/i'; + $this->classMap = []; + } + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $importedOriginalClassesMap = []; + $currIndex = 0; + + while (true) { + $currIndex = $tokens->getNextTokenOfKind($currIndex, [[T_STRING]]); + + if (null === $currIndex) { + break; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($currIndex); + + if ($tokens[$prevIndex]->isGivenKind([T_CONST, T_DOUBLE_COLON])) { + continue; + } + + $originalClass = $tokens[$currIndex]->getContent(); + $allowedReplacementScenarios = (new ClassyAnalyzer())->isClassyInvocation($tokens, $currIndex) + || $this->isImport($tokens, $currIndex); + + if (!$allowedReplacementScenarios || !Preg::match($this->originalClassRegEx, $originalClass)) { + ++$currIndex; + + continue; + } + + $substituteTokens = $this->generateReplacement($originalClass); + + $tokens->clearAt($currIndex); + $tokens->insertAt( + $currIndex, + isset($importedOriginalClassesMap[$originalClass]) ? $substituteTokens[$substituteTokens->getSize() - 1] : $substituteTokens + ); + + $prevIndex = $tokens->getPrevMeaningfulToken($currIndex); + if ($tokens[$prevIndex]->isGivenKind(T_USE)) { + $importedOriginalClassesMap[$originalClass] = true; + } elseif ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + + if ($tokens[$prevIndex]->isGivenKind(T_USE)) { + $importedOriginalClassesMap[$originalClass] = true; + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([PhpUnitTargetVersion::VERSION_4_8, PhpUnitTargetVersion::VERSION_5_7, PhpUnitTargetVersion::VERSION_6_0, PhpUnitTargetVersion::VERSION_NEWEST]) + ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) + ->getOption(), + ]); + } + + private function generateReplacement(string $originalClassName): Tokens + { + $delimiter = '_'; + $string = $originalClassName; + + $map = array_change_key_case($this->classMap); + if (isset($map[strtolower($originalClassName)])) { + $delimiter = '\\'; + $string = $map[strtolower($originalClassName)]; + } + + $parts = explode($delimiter, $string); + $tokensArray = []; + + while ([] !== $parts) { + $tokensArray[] = new Token([T_STRING, array_shift($parts)]); + if ([] !== $parts) { + $tokensArray[] = new Token([T_NS_SEPARATOR, '\\']); + } + } + + return Tokens::fromArray($tokensArray); + } + + private function isImport(Tokens $tokens, int $currIndex): bool + { + $prevIndex = $tokens->getPrevMeaningfulToken($currIndex); + + if ($tokens[$prevIndex]->isGivenKind([T_NS_SEPARATOR])) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + } + + return $tokens[$prevIndex]->isGivenKind([T_USE]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php new file mode 100644 index 00000000..f6fa1f0f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php @@ -0,0 +1,268 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Dariusz Rumiński + */ +final class PhpUnitNoExpectationAnnotationFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @var bool + */ + private $fixMessageRegExp; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->fixMessageRegExp = PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_4_3); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Usages of `@expectedException*` annotations MUST be replaced by `->setExpectedException*` methods.', + [ + new CodeSample( + ' PhpUnitTargetVersion::VERSION_3_2] + ), + ], + null, + 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.' + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, PhpUnitExpectationFixer. + */ + public function getPriority(): int + { + return 10; + } + + public function isRisky(): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([PhpUnitTargetVersion::VERSION_3_2, PhpUnitTargetVersion::VERSION_4_3, PhpUnitTargetVersion::VERSION_NEWEST]) + ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) + ->getOption(), + (new FixerOptionBuilder('use_class_const', 'Use ::class notation.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + if (!$tokens[$i]->isGivenKind(T_FUNCTION) || $tokensAnalyzer->isLambda($i)) { + continue; + } + + $functionIndex = $i; + $docBlockIndex = $i; + + // ignore abstract functions + $braceIndex = $tokens->getNextTokenOfKind($functionIndex, [';', '{']); + if (!$tokens[$braceIndex]->equals('{')) { + continue; + } + + do { + $docBlockIndex = $tokens->getPrevNonWhitespace($docBlockIndex); + } while ($tokens[$docBlockIndex]->isGivenKind([T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FINAL, T_ABSTRACT, T_COMMENT])); + + if (!$tokens[$docBlockIndex]->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + $annotations = []; + + foreach ($doc->getAnnotationsOfType([ + 'expectedException', + 'expectedExceptionCode', + 'expectedExceptionMessage', + 'expectedExceptionMessageRegExp', + ]) as $annotation) { + $tag = $annotation->getTag()->getName(); + $content = $this->extractContentFromAnnotation($annotation); + $annotations[$tag] = $content; + $annotation->remove(); + } + + if (!isset($annotations['expectedException'])) { + continue; + } + + if (!$this->fixMessageRegExp && isset($annotations['expectedExceptionMessageRegExp'])) { + continue; + } + + $originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $docBlockIndex); + + $paramList = $this->annotationsToParamList($annotations); + + $newMethodsCode = '' + .(isset($annotations['expectedExceptionMessageRegExp']) ? 'setExpectedExceptionRegExp' : 'setExpectedException') + .'(' + .implode(', ', $paramList) + .');'; + $newMethods = Tokens::fromCode($newMethodsCode); + $newMethods[0] = new Token([ + T_WHITESPACE, + $this->whitespacesConfig->getLineEnding().$originalIndent.$this->whitespacesConfig->getIndent(), + ]); + + // apply changes + $docContent = $doc->getContent(); + if ('' === $docContent) { + $docContent = '/** */'; + } + $tokens[$docBlockIndex] = new Token([T_DOC_COMMENT, $docContent]); + $tokens->insertAt($braceIndex + 1, $newMethods); + + $whitespaceIndex = $braceIndex + $newMethods->getSize() + 1; + $tokens[$whitespaceIndex] = new Token([ + T_WHITESPACE, + $this->whitespacesConfig->getLineEnding().$tokens[$whitespaceIndex]->getContent(), + ]); + + $i = $docBlockIndex; + } + } + + private function extractContentFromAnnotation(Annotation $annotation): string + { + $tag = $annotation->getTag()->getName(); + + if (!Preg::match('/@'.$tag.'\s+(.+)$/s', $annotation->getContent(), $matches)) { + return ''; + } + + $content = Preg::replace('/\*+\/$/', '', $matches[1]); + + if (Preg::match('/\R/u', $content)) { + $content = Preg::replace('/\s*\R+\s*\*\s*/u', ' ', $content); + } + + return rtrim($content); + } + + /** + * @param array $annotations + * + * @return list + */ + private function annotationsToParamList(array $annotations): array + { + $params = []; + $exceptionClass = ltrim($annotations['expectedException'], '\\'); + + if (str_contains($exceptionClass, '*')) { + $exceptionClass = substr($exceptionClass, 0, strpos($exceptionClass, '*')); + } + + $exceptionClass = trim($exceptionClass); + + if (true === $this->configuration['use_class_const']) { + $params[] = "\\{$exceptionClass}::class"; + } else { + $params[] = "'{$exceptionClass}'"; + } + + if (isset($annotations['expectedExceptionMessage'])) { + $params[] = var_export($annotations['expectedExceptionMessage'], true); + } elseif (isset($annotations['expectedExceptionMessageRegExp'])) { + $params[] = var_export($annotations['expectedExceptionMessageRegExp'], true); + } elseif (isset($annotations['expectedExceptionCode'])) { + $params[] = 'null'; + } + + if (isset($annotations['expectedExceptionCode'])) { + $params[] = $annotations['expectedExceptionCode']; + } + + return $params; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.php new file mode 100644 index 00000000..3fbd98ce --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.php @@ -0,0 +1,108 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Gert de Pagter + */ +final class PhpUnitSetUpTearDownVisibilityFixer extends AbstractPhpUnitFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Changes the visibility of the `setUp()` and `tearDown()` functions of PHPUnit to `protected`, to match the PHPUnit TestCase.', + [ + new CodeSample( + 'hello = "hello"; + } + + public function tearDown() + { + $this->hello = null; + } +} +' + ), + ], + null, + 'This fixer may change functions named `setUp()` or `tearDown()` outside of PHPUnit tests, '. + 'when a class is wrongly seen as a PHPUnit test.' + ); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $counter = 0; + $tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + if (2 === $counter) { + break; // we've seen both method we are interested in, so stop analyzing this class + } + + if (!$this->isSetupOrTearDownMethod($tokens, $i)) { + continue; + } + + ++$counter; + $visibility = $tokensAnalyzer->getMethodAttributes($i)['visibility']; + + if (T_PUBLIC === $visibility) { + $index = $tokens->getPrevTokenOfKind($i, [[T_PUBLIC]]); + $tokens[$index] = new Token([T_PROTECTED, 'protected']); + + continue; + } + + if (null === $visibility) { + $tokens->insertAt($i, [new Token([T_PROTECTED, 'protected']), new Token([T_WHITESPACE, ' '])]); + } + } + } + + private function isSetupOrTearDownMethod(Tokens $tokens, int $index): bool + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $isMethod = $tokens[$index]->isGivenKind(T_FUNCTION) && !$tokensAnalyzer->isLambda($index); + if (!$isMethod) { + return false; + } + + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + $functionName = strtolower($tokens[$functionNameIndex]->getContent()); + + return 'setup' === $functionName || 'teardown' === $functionName; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php new file mode 100644 index 00000000..0696cdfd --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Jefersson Nathan + */ +final class PhpUnitSizeClassFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface +{ + private const SIZES = ['small', 'medium', 'large']; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'All PHPUnit test cases should have `@small`, `@medium` or `@large` annotation to enable run time limits.', + [ + new CodeSample(" 'medium']), + ], + 'The special groups [small, medium, large] provides a way to identify tests that are taking long to be executed.' + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocSeparationFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('group', 'Define a specific group to be used in case no group is already in use.')) + ->setAllowedValues(self::SIZES) + ->setDefault('small') + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $classIndex = $tokens->getPrevTokenOfKind($startIndex, [[T_CLASS]]); + + if ($this->isAbstractClass($tokens, $classIndex)) { + return; + } + + $this->ensureIsDockBlockWithAnnotation( + $tokens, + $classIndex, + $this->configuration['group'], + self::SIZES + ); + } + + private function isAbstractClass(Tokens $tokens, int $i): bool + { + $typeIndex = $tokens->getPrevMeaningfulToken($i); + + return $tokens[$typeIndex]->isGivenKind(T_ABSTRACT); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitStrictFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitStrictFixer.php new file mode 100644 index 00000000..4d532566 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitStrictFixer.php @@ -0,0 +1,141 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class PhpUnitStrictFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private static array $assertionMap = [ + 'assertAttributeEquals' => 'assertAttributeSame', + 'assertAttributeNotEquals' => 'assertAttributeNotSame', + 'assertEquals' => 'assertSame', + 'assertNotEquals' => 'assertNotSame', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPUnit methods like `assertSame` should be used instead of `assertEquals`.', + [ + new CodeSample( + 'assertAttributeEquals(a(), b()); + $this->assertAttributeNotEquals(a(), b()); + $this->assertEquals(a(), b()); + $this->assertNotEquals(a(), b()); + } +} +' + ), + new CodeSample( + 'assertAttributeEquals(a(), b()); + $this->assertAttributeNotEquals(a(), b()); + $this->assertEquals(a(), b()); + $this->assertNotEquals(a(), b()); + } +} +', + ['assertions' => ['assertEquals']] + ), + ], + null, + 'Risky when any of the functions are overridden or when testing object equality.' + ); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + $functionsAnalyzer = new FunctionsAnalyzer(); + + foreach ($this->configuration['assertions'] as $methodBefore) { + $methodAfter = self::$assertionMap[$methodBefore]; + + for ($index = $startIndex; $index < $endIndex; ++$index) { + $methodIndex = $tokens->getNextTokenOfKind($index, [[T_STRING, $methodBefore]]); + + if (null === $methodIndex) { + break; + } + + if (!$functionsAnalyzer->isTheSameClassCall($tokens, $methodIndex)) { + continue; + } + + $openingParenthesisIndex = $tokens->getNextMeaningfulToken($methodIndex); + $argumentsCount = $argumentsAnalyzer->countArguments( + $tokens, + $openingParenthesisIndex, + $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingParenthesisIndex) + ); + + if (2 === $argumentsCount || 3 === $argumentsCount) { + $tokens[$methodIndex] = new Token([T_STRING, $methodAfter]); + } + + $index = $methodIndex; + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('assertions', 'List of assertion methods to fix.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset(array_keys(self::$assertionMap))]) + ->setDefault([ + 'assertAttributeEquals', + 'assertAttributeNotEquals', + 'assertEquals', + 'assertNotEquals', + ]) + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTargetVersion.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTargetVersion.php new file mode 100644 index 00000000..4bd1800a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTargetVersion.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use Composer\Semver\Comparator; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class PhpUnitTargetVersion +{ + public const VERSION_3_0 = '3.0'; + public const VERSION_3_2 = '3.2'; + public const VERSION_3_5 = '3.5'; + public const VERSION_4_3 = '4.3'; + public const VERSION_4_8 = '4.8'; + public const VERSION_5_0 = '5.0'; + public const VERSION_5_2 = '5.2'; + public const VERSION_5_4 = '5.4'; + public const VERSION_5_5 = '5.5'; + public const VERSION_5_6 = '5.6'; + public const VERSION_5_7 = '5.7'; + public const VERSION_6_0 = '6.0'; + public const VERSION_7_5 = '7.5'; + public const VERSION_8_4 = '8.4'; + public const VERSION_NEWEST = 'newest'; + + private function __construct() {} + + public static function fulfills(string $candidate, string $target): bool + { + if (self::VERSION_NEWEST === $target) { + throw new \LogicException(sprintf('Parameter `target` shall not be provided as "%s", determine proper target for tested PHPUnit feature instead.', self::VERSION_NEWEST)); + } + + if (self::VERSION_NEWEST === $candidate) { + return true; + } + + return Comparator::greaterThanOrEqualTo($candidate, $target); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.php new file mode 100644 index 00000000..abee1f2e --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.php @@ -0,0 +1,402 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Gert de Pagter + */ +final class PhpUnitTestAnnotationFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function isRisky(): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Adds or removes @test annotations from tests, following configuration.', + [ + new CodeSample('whitespacesConfig->getLineEnding()), + new CodeSample('whitespacesConfig->getLineEnding(), ['style' => 'annotation']), + ], + null, + 'This fixer may change the name of your tests, and could cause incompatibility with'. + ' abstract classes or interfaces.' + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, PhpUnitMethodCasingFixer, PhpdocTrimFixer. + */ + public function getPriority(): int + { + return 10; + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + if ('annotation' === $this->configuration['style']) { + $this->applyTestAnnotation($tokens, $startIndex, $endIndex); + } else { + $this->applyTestPrefix($tokens, $startIndex, $endIndex); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('style', 'Whether to use the @test annotation or not.')) + ->setAllowedValues(['prefix', 'annotation']) + ->setDefault('prefix') + ->getOption(), + ]); + } + + private function applyTestAnnotation(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + if (!$this->isTestMethod($tokens, $i)) { + continue; + } + + $functionNameIndex = $tokens->getNextMeaningfulToken($i); + $functionName = $tokens[$functionNameIndex]->getContent(); + + if ($this->hasTestPrefix($functionName) && !$this->hasProperTestAnnotation($tokens, $i)) { + $newFunctionName = $this->removeTestPrefix($functionName); + $tokens[$functionNameIndex] = new Token([T_STRING, $newFunctionName]); + } + + $docBlockIndex = $this->getDocBlockIndex($tokens, $i); + + if ($this->isPHPDoc($tokens, $docBlockIndex)) { + $lines = $this->updateDocBlock($tokens, $docBlockIndex); + $lines = $this->addTestAnnotation($lines, $tokens, $docBlockIndex); + $lines = implode('', $lines); + + $tokens[$docBlockIndex] = new Token([T_DOC_COMMENT, $lines]); + } else { + // Create a new docblock if it didn't have one before; + $this->createDocBlock($tokens, $docBlockIndex); + } + } + } + + private function applyTestPrefix(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + // We explicitly check again if the function has a doc block to save some time. + if (!$this->isTestMethod($tokens, $i)) { + continue; + } + + $docBlockIndex = $this->getDocBlockIndex($tokens, $i); + + if (!$this->isPHPDoc($tokens, $docBlockIndex)) { + continue; + } + + $lines = $this->updateDocBlock($tokens, $docBlockIndex); + $lines = implode('', $lines); + $tokens[$docBlockIndex] = new Token([T_DOC_COMMENT, $lines]); + + $functionNameIndex = $tokens->getNextMeaningfulToken($i); + $functionName = $tokens[$functionNameIndex]->getContent(); + + if ($this->hasTestPrefix($functionName)) { + continue; + } + + $newFunctionName = $this->addTestPrefix($functionName); + $tokens[$functionNameIndex] = new Token([T_STRING, $newFunctionName]); + } + } + + private function isTestMethod(Tokens $tokens, int $index): bool + { + // Check if we are dealing with a (non-abstract, non-lambda) function + if (!$this->isMethod($tokens, $index)) { + return false; + } + + // if the function name starts with test it is a test + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + $functionName = $tokens[$functionNameIndex]->getContent(); + + if ($this->hasTestPrefix($functionName)) { + return true; + } + + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + + // If the function doesn't have test in its name, and no doc block, it is not a test + return + $this->isPHPDoc($tokens, $docBlockIndex) + && str_contains($tokens[$docBlockIndex]->getContent(), '@test'); + } + + private function isMethod(Tokens $tokens, int $index): bool + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + return $tokens[$index]->isGivenKind(T_FUNCTION) && !$tokensAnalyzer->isLambda($index); + } + + private function hasTestPrefix(string $functionName): bool + { + return str_starts_with($functionName, 'test'); + } + + private function hasProperTestAnnotation(Tokens $tokens, int $index): bool + { + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + $doc = $tokens[$docBlockIndex]->getContent(); + + return Preg::match('/\*\s+@test\b/', $doc); + } + + private function removeTestPrefix(string $functionName): string + { + $remainder = Preg::replace('/^test(?=[A-Z_])_?/', '', $functionName); + + if ('' === $remainder) { + return $functionName; + } + + return lcfirst($remainder); + } + + private function addTestPrefix(string $functionName): string + { + return 'test'.ucfirst($functionName); + } + + private function createDocBlock(Tokens $tokens, int $docBlockIndex): void + { + $lineEnd = $this->whitespacesConfig->getLineEnding(); + $originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); + $toInsert = [ + new Token([T_DOC_COMMENT, '/**'.$lineEnd."{$originalIndent} * @test".$lineEnd."{$originalIndent} */"]), + new Token([T_WHITESPACE, $lineEnd.$originalIndent]), + ]; + $index = $tokens->getNextMeaningfulToken($docBlockIndex); + $tokens->insertAt($index, $toInsert); + } + + /** + * @return Line[] + */ + private function updateDocBlock(Tokens $tokens, int $docBlockIndex): array + { + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + $lines = $doc->getLines(); + + return $this->updateLines($lines, $tokens, $docBlockIndex); + } + + /** + * @param Line[] $lines + * + * @return Line[] + */ + private function updateLines(array $lines, Tokens $tokens, int $docBlockIndex): array + { + $needsAnnotation = 'annotation' === $this->configuration['style']; + + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + for ($i = 0; $i < \count($lines); ++$i) { + // If we need to add test annotation and it is a single line comment we need to deal with that separately + if ($needsAnnotation && ($lines[$i]->isTheStart() && $lines[$i]->isTheEnd())) { + if (!$this->doesDocBlockContainTest($doc)) { + $lines = $this->splitUpDocBlock($lines, $tokens, $docBlockIndex); + + return $this->updateLines($lines, $tokens, $docBlockIndex); + } + // One we split it up, we run the function again, so we deal with other things in a proper way + } + + if (!$needsAnnotation + && str_contains($lines[$i]->getContent(), ' @test') + && !str_contains($lines[$i]->getContent(), '@testWith') + && !str_contains($lines[$i]->getContent(), '@testdox') + ) { + // We remove @test from the doc block + $lines[$i] = new Line(str_replace(' @test', '', $lines[$i]->getContent())); + } + // ignore the line if it isn't @depends + if (!str_contains($lines[$i]->getContent(), '@depends')) { + continue; + } + + $lines[$i] = $this->updateDependsAnnotation($lines[$i]); + } + + return $lines; + } + + /** + * Take a one line doc block, and turn it into a multi line doc block. + * + * @param Line[] $lines + * + * @return Line[] + */ + private function splitUpDocBlock(array $lines, Tokens $tokens, int $docBlockIndex): array + { + $lineContent = $this->getSingleLineDocBlockEntry($lines); + $lineEnd = $this->whitespacesConfig->getLineEnding(); + $originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); + + return [ + new Line('/**'.$lineEnd), + new Line($originalIndent.' * '.$lineContent.$lineEnd), + new Line($originalIndent.' */'), + ]; + } + + /** + * @todo check whether it's doable to use \PhpCsFixer\DocBlock\DocBlock::getSingleLineDocBlockEntry instead + * + * @param Line[] $lines + */ + private function getSingleLineDocBlockEntry(array $lines): string + { + $line = $lines[0]; + $line = str_replace('*/', '', $line->getContent()); + $line = trim($line); + $line = str_split($line); + $i = \count($line); + do { + --$i; + } while ('*' !== $line[$i] && '*' !== $line[$i - 1] && '/' !== $line[$i - 2]); + if (' ' === $line[$i]) { + ++$i; + } + $line = \array_slice($line, $i); + + return implode('', $line); + } + + /** + * Updates the depends tag on the current doc block. + */ + private function updateDependsAnnotation(Line $line): Line + { + if ('annotation' === $this->configuration['style']) { + return $this->removeTestPrefixFromDependsAnnotation($line); + } + + return $this->addTestPrefixToDependsAnnotation($line); + } + + private function removeTestPrefixFromDependsAnnotation(Line $line): Line + { + $line = str_split($line->getContent()); + + $dependsIndex = $this->findWhereDependsFunctionNameStarts($line); + $dependsFunctionName = implode('', \array_slice($line, $dependsIndex)); + + if ($this->hasTestPrefix($dependsFunctionName)) { + $dependsFunctionName = $this->removeTestPrefix($dependsFunctionName); + } + array_splice($line, $dependsIndex); + + return new Line(implode('', $line).$dependsFunctionName); + } + + private function addTestPrefixToDependsAnnotation(Line $line): Line + { + $line = str_split($line->getContent()); + $dependsIndex = $this->findWhereDependsFunctionNameStarts($line); + $dependsFunctionName = implode('', \array_slice($line, $dependsIndex)); + + if (!$this->hasTestPrefix($dependsFunctionName)) { + $dependsFunctionName = $this->addTestPrefix($dependsFunctionName); + } + + array_splice($line, $dependsIndex); + + return new Line(implode('', $line).$dependsFunctionName); + } + + /** + * Helps to find where the function name in the doc block starts. + * + * @param list $line + */ + private function findWhereDependsFunctionNameStarts(array $line): int + { + $index = stripos(implode('', $line), '@depends') + 8; + + while (' ' === $line[$index]) { + ++$index; + } + + return $index; + } + + /** + * @param Line[] $lines + * + * @return Line[] + */ + private function addTestAnnotation(array $lines, Tokens $tokens, int $docBlockIndex): array + { + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + + if (!$this->doesDocBlockContainTest($doc)) { + $originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $docBlockIndex); + $lineEnd = $this->whitespacesConfig->getLineEnding(); + + array_splice($lines, -1, 0, $originalIndent.' *'.$lineEnd.$originalIndent.' * @test'.$lineEnd); + } + + return $lines; + } + + private function doesDocBlockContainTest(DocBlock $doc): bool + { + return 0 !== \count($doc->getAnnotationsOfType('test')); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php new file mode 100644 index 00000000..692389c8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php @@ -0,0 +1,482 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @author Filippo Tessarotto + */ +final class PhpUnitTestCaseStaticMethodCallsFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const CALL_TYPE_THIS = 'this'; + + /** + * @internal + */ + public const CALL_TYPE_SELF = 'self'; + + /** + * @internal + */ + public const CALL_TYPE_STATIC = 'static'; + + /** + * @var array + */ + private array $staticMethods = [ + // Assert methods + 'anything' => true, + 'arrayHasKey' => true, + 'assertArrayHasKey' => true, + 'assertArrayNotHasKey' => true, + 'assertArraySubset' => true, + 'assertAttributeContains' => true, + 'assertAttributeContainsOnly' => true, + 'assertAttributeCount' => true, + 'assertAttributeEmpty' => true, + 'assertAttributeEquals' => true, + 'assertAttributeGreaterThan' => true, + 'assertAttributeGreaterThanOrEqual' => true, + 'assertAttributeInstanceOf' => true, + 'assertAttributeInternalType' => true, + 'assertAttributeLessThan' => true, + 'assertAttributeLessThanOrEqual' => true, + 'assertAttributeNotContains' => true, + 'assertAttributeNotContainsOnly' => true, + 'assertAttributeNotCount' => true, + 'assertAttributeNotEmpty' => true, + 'assertAttributeNotEquals' => true, + 'assertAttributeNotInstanceOf' => true, + 'assertAttributeNotInternalType' => true, + 'assertAttributeNotSame' => true, + 'assertAttributeSame' => true, + 'assertClassHasAttribute' => true, + 'assertClassHasStaticAttribute' => true, + 'assertClassNotHasAttribute' => true, + 'assertClassNotHasStaticAttribute' => true, + 'assertContains' => true, + 'assertContainsEquals' => true, + 'assertContainsOnly' => true, + 'assertContainsOnlyInstancesOf' => true, + 'assertCount' => true, + 'assertDirectoryDoesNotExist' => true, + 'assertDirectoryExists' => true, + 'assertDirectoryIsNotReadable' => true, + 'assertDirectoryIsNotWritable' => true, + 'assertDirectoryIsReadable' => true, + 'assertDirectoryIsWritable' => true, + 'assertDirectoryNotExists' => true, + 'assertDirectoryNotIsReadable' => true, + 'assertDirectoryNotIsWritable' => true, + 'assertDoesNotMatchRegularExpression' => true, + 'assertEmpty' => true, + 'assertEqualXMLStructure' => true, + 'assertEquals' => true, + 'assertEqualsCanonicalizing' => true, + 'assertEqualsIgnoringCase' => true, + 'assertEqualsWithDelta' => true, + 'assertFalse' => true, + 'assertFileDoesNotExist' => true, + 'assertFileEquals' => true, + 'assertFileEqualsCanonicalizing' => true, + 'assertFileEqualsIgnoringCase' => true, + 'assertFileExists' => true, + 'assertFileIsNotReadable' => true, + 'assertFileIsNotWritable' => true, + 'assertFileIsReadable' => true, + 'assertFileIsWritable' => true, + 'assertFileNotEquals' => true, + 'assertFileNotEqualsCanonicalizing' => true, + 'assertFileNotEqualsIgnoringCase' => true, + 'assertFileNotExists' => true, + 'assertFileNotIsReadable' => true, + 'assertFileNotIsWritable' => true, + 'assertFinite' => true, + 'assertGreaterThan' => true, + 'assertGreaterThanOrEqual' => true, + 'assertInfinite' => true, + 'assertInstanceOf' => true, + 'assertInternalType' => true, + 'assertIsArray' => true, + 'assertIsBool' => true, + 'assertIsCallable' => true, + 'assertIsClosedResource' => true, + 'assertIsFloat' => true, + 'assertIsInt' => true, + 'assertIsIterable' => true, + 'assertIsNotArray' => true, + 'assertIsNotBool' => true, + 'assertIsNotCallable' => true, + 'assertIsNotClosedResource' => true, + 'assertIsNotFloat' => true, + 'assertIsNotInt' => true, + 'assertIsNotIterable' => true, + 'assertIsNotNumeric' => true, + 'assertIsNotObject' => true, + 'assertIsNotReadable' => true, + 'assertIsNotResource' => true, + 'assertIsNotScalar' => true, + 'assertIsNotString' => true, + 'assertIsNotWritable' => true, + 'assertIsNumeric' => true, + 'assertIsObject' => true, + 'assertIsReadable' => true, + 'assertIsResource' => true, + 'assertIsScalar' => true, + 'assertIsString' => true, + 'assertIsWritable' => true, + 'assertJson' => true, + 'assertJsonFileEqualsJsonFile' => true, + 'assertJsonFileNotEqualsJsonFile' => true, + 'assertJsonStringEqualsJsonFile' => true, + 'assertJsonStringEqualsJsonString' => true, + 'assertJsonStringNotEqualsJsonFile' => true, + 'assertJsonStringNotEqualsJsonString' => true, + 'assertLessThan' => true, + 'assertLessThanOrEqual' => true, + 'assertMatchesRegularExpression' => true, + 'assertNan' => true, + 'assertNotContains' => true, + 'assertNotContainsEquals' => true, + 'assertNotContainsOnly' => true, + 'assertNotCount' => true, + 'assertNotEmpty' => true, + 'assertNotEquals' => true, + 'assertNotEqualsCanonicalizing' => true, + 'assertNotEqualsIgnoringCase' => true, + 'assertNotEqualsWithDelta' => true, + 'assertNotFalse' => true, + 'assertNotInstanceOf' => true, + 'assertNotInternalType' => true, + 'assertNotIsReadable' => true, + 'assertNotIsWritable' => true, + 'assertNotNull' => true, + 'assertNotRegExp' => true, + 'assertNotSame' => true, + 'assertNotSameSize' => true, + 'assertNotTrue' => true, + 'assertNull' => true, + 'assertObjectEquals' => true, + 'assertObjectHasAttribute' => true, + 'assertObjectHasProperty' => true, + 'assertObjectNotHasAttribute' => true, + 'assertObjectNotHasProperty' => true, + 'assertRegExp' => true, + 'assertSame' => true, + 'assertSameSize' => true, + 'assertStringContainsString' => true, + 'assertStringContainsStringIgnoringCase' => true, + 'assertStringEndsNotWith' => true, + 'assertStringEndsWith' => true, + 'assertStringEqualsFile' => true, + 'assertStringEqualsFileCanonicalizing' => true, + 'assertStringEqualsFileIgnoringCase' => true, + 'assertStringMatchesFormat' => true, + 'assertStringMatchesFormatFile' => true, + 'assertStringNotContainsString' => true, + 'assertStringNotContainsStringIgnoringCase' => true, + 'assertStringNotEqualsFile' => true, + 'assertStringNotEqualsFileCanonicalizing' => true, + 'assertStringNotEqualsFileIgnoringCase' => true, + 'assertStringNotMatchesFormat' => true, + 'assertStringNotMatchesFormatFile' => true, + 'assertStringStartsNotWith' => true, + 'assertStringStartsWith' => true, + 'assertThat' => true, + 'assertTrue' => true, + 'assertXmlFileEqualsXmlFile' => true, + 'assertXmlFileNotEqualsXmlFile' => true, + 'assertXmlStringEqualsXmlFile' => true, + 'assertXmlStringEqualsXmlString' => true, + 'assertXmlStringNotEqualsXmlFile' => true, + 'assertXmlStringNotEqualsXmlString' => true, + 'attribute' => true, + 'attributeEqualTo' => true, + 'callback' => true, + 'classHasAttribute' => true, + 'classHasStaticAttribute' => true, + 'contains' => true, + 'containsEqual' => true, + 'containsIdentical' => true, + 'containsOnly' => true, + 'containsOnlyInstancesOf' => true, + 'countOf' => true, + 'directoryExists' => true, + 'equalTo' => true, + 'equalToCanonicalizing' => true, + 'equalToIgnoringCase' => true, + 'equalToWithDelta' => true, + 'fail' => true, + 'fileExists' => true, + 'getCount' => true, + 'getObjectAttribute' => true, + 'getStaticAttribute' => true, + 'greaterThan' => true, + 'greaterThanOrEqual' => true, + 'identicalTo' => true, + 'isEmpty' => true, + 'isFalse' => true, + 'isFinite' => true, + 'isInfinite' => true, + 'isInstanceOf' => true, + 'isJson' => true, + 'isNan' => true, + 'isNull' => true, + 'isReadable' => true, + 'isTrue' => true, + 'isType' => true, + 'isWritable' => true, + 'lessThan' => true, + 'lessThanOrEqual' => true, + 'logicalAnd' => true, + 'logicalNot' => true, + 'logicalOr' => true, + 'logicalXor' => true, + 'markTestIncomplete' => true, + 'markTestSkipped' => true, + 'matches' => true, + 'matchesRegularExpression' => true, + 'objectEquals' => true, + 'objectHasAttribute' => true, + 'readAttribute' => true, + 'resetCount' => true, + 'stringContains' => true, + 'stringEndsWith' => true, + 'stringStartsWith' => true, + + // TestCase methods + 'any' => true, + 'at' => true, + 'atLeast' => true, + 'atLeastOnce' => true, + 'atMost' => true, + 'exactly' => true, + 'never' => true, + 'once' => true, + 'onConsecutiveCalls' => true, + 'returnArgument' => true, + 'returnCallback' => true, + 'returnSelf' => true, + 'returnValue' => true, + 'returnValueMap' => true, + 'setUpBeforeClass' => true, + 'tearDownAfterClass' => true, + 'throwException' => true, + ]; + + /** + * @var array + */ + private array $allowedValues = [ + self::CALL_TYPE_THIS => true, + self::CALL_TYPE_SELF => true, + self::CALL_TYPE_STATIC => true, + ]; + + /** + * @var array>> + */ + private array $conversionMap = [ + self::CALL_TYPE_THIS => [[T_OBJECT_OPERATOR, '->'], [T_VARIABLE, '$this']], + self::CALL_TYPE_SELF => [[T_DOUBLE_COLON, '::'], [T_STRING, 'self']], + self::CALL_TYPE_STATIC => [[T_DOUBLE_COLON, '::'], [T_STATIC, 'static']], + ]; + + public function getDefinition(): FixerDefinitionInterface + { + $codeSample = 'assertSame(1, 2); + self::assertSame(1, 2); + static::assertSame(1, 2); + } +} +'; + + return new FixerDefinition( + 'Calls to `PHPUnit\Framework\TestCase` static methods must all be of the same type, either `$this->`, `self::` or `static::`.', + [ + new CodeSample($codeSample), + new CodeSample($codeSample, ['call_type' => self::CALL_TYPE_THIS]), + ], + null, + 'Risky when PHPUnit methods are overridden or not accessible, or when project has PHPUnit incompatibilities.' + ); + } + + /** + * {@inheritdoc} + * + * Must run before SelfStaticAccessorFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isRisky(): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $thisFixer = $this; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('call_type', 'The call type to use for referring to PHPUnit methods.')) + ->setAllowedTypes(['string']) + ->setAllowedValues(array_keys($this->allowedValues)) + ->setDefault('static') + ->getOption(), + (new FixerOptionBuilder('methods', 'Dictionary of `method` => `call_type` values that differ from the default strategy.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([static function (array $option) use ($thisFixer): bool { + foreach ($option as $method => $value) { + if (!isset($thisFixer->staticMethods[$method])) { + throw new InvalidOptionsException( + sprintf( + 'Unexpected "methods" key, expected any of %s, got "%s".', + Utils::naturalLanguageJoin(array_keys($thisFixer->staticMethods)), + \gettype($method).'#'.$method + ) + ); + } + + if (!isset($thisFixer->allowedValues[$value])) { + throw new InvalidOptionsException( + sprintf( + 'Unexpected value for method "%s", expected any of %s, got "%s".', + $method, + Utils::naturalLanguageJoin(array_keys($thisFixer->allowedValues)), + \is_object($value) ? \get_class($value) : (null === $value ? 'null' : \gettype($value).'#'.$value) + ) + ); + } + } + + return true; + }]) + ->setDefault([]) + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $analyzer = new TokensAnalyzer($tokens); + + for ($index = $startIndex; $index < $endIndex; ++$index) { + // skip anonymous classes + if ($tokens[$index]->isGivenKind(T_CLASS)) { + $index = $this->findEndOfNextBlock($tokens, $index); + + continue; + } + + $callType = $this->configuration['call_type']; + + if ($tokens[$index]->isGivenKind(T_FUNCTION)) { + // skip lambda + if ($analyzer->isLambda($index)) { + $index = $this->findEndOfNextBlock($tokens, $index); + + continue; + } + + // do not change `self` to `this` in static methods + if ('this' === $callType) { + $attributes = $analyzer->getMethodAttributes($index); + + if (false !== $attributes['static']) { + $index = $this->findEndOfNextBlock($tokens, $index); + + continue; + } + } + } + + if (!$tokens[$index]->isGivenKind(T_STRING) || !isset($this->staticMethods[$tokens[$index]->getContent()])) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$nextIndex]->equals('(')) { + $index = $nextIndex; + + continue; + } + + if ($tokens[$tokens->getNextMeaningfulToken($nextIndex)]->isGivenKind(CT::T_FIRST_CLASS_CALLABLE)) { + continue; + } + + $methodName = $tokens[$index]->getContent(); + + if (isset($this->configuration['methods'][$methodName])) { + $callType = $this->configuration['methods'][$methodName]; + } + + $operatorIndex = $tokens->getPrevMeaningfulToken($index); + $referenceIndex = $tokens->getPrevMeaningfulToken($operatorIndex); + + if (!$this->needsConversion($tokens, $index, $referenceIndex, $callType)) { + continue; + } + + $tokens[$operatorIndex] = new Token($this->conversionMap[$callType][0]); + $tokens[$referenceIndex] = new Token($this->conversionMap[$callType][1]); + } + } + + private function needsConversion(Tokens $tokens, int $index, int $referenceIndex, string $callType): bool + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + return $functionsAnalyzer->isTheSameClassCall($tokens, $index) + && !$tokens[$referenceIndex]->equals($this->conversionMap[$callType][1], false); + } + + private function findEndOfNextBlock(Tokens $tokens, int $index): int + { + $nextIndex = $tokens->getNextTokenOfKind($index, [';', '{']); + + return $tokens[$nextIndex]->equals('{') + ? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nextIndex) + : $nextIndex; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php new file mode 100644 index 00000000..a8373290 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php @@ -0,0 +1,82 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Dariusz Rumiński + */ +final class PhpUnitTestClassRequiresCoversFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Adds a default `@coversNothing` annotation to PHPUnit test classes that have no `@covers*` annotation.', + [ + new CodeSample( + 'assertSame(a(), b()); + } +} +' + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocSeparationFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $classIndex = $tokens->getPrevTokenOfKind($startIndex, [[T_CLASS]]); + + $tokensAnalyzer = new TokensAnalyzer($tokens); + $modifiers = $tokensAnalyzer->getClassyModifiers($classIndex); + + if (isset($modifiers['abstract'])) { + return; // don't add `@covers` annotation for abstract base classes + } + + $this->ensureIsDockBlockWithAnnotation( + $tokens, + $classIndex, + 'coversNothing', + [ + 'covers', + 'coversDefaultClass', + 'coversNothing', + ] + ); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/AlignMultilineCommentFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/AlignMultilineCommentFixer.php new file mode 100644 index 00000000..130b1349 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/AlignMultilineCommentFixer.php @@ -0,0 +1,167 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + * @author Julien Falque + */ +final class AlignMultilineCommentFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @var null|int[] + */ + private $tokenKinds; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->tokenKinds = [T_DOC_COMMENT]; + if ('phpdocs_only' !== $this->configuration['comment_type']) { + $this->tokenKinds[] = T_COMMENT; + } + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Each line of multi-line DocComments must have an asterisk [PSR-5] and must be aligned with the first one.', + [ + new CodeSample( + ' 'phpdocs_like'] + ), + new CodeSample( + ' 'all_multiline'] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocAnnotationWithoutDotFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. + * Must run after ArrayIndentationFixer. + */ + public function getPriority(): int + { + return 27; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound($this->tokenKinds); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind($this->tokenKinds)) { + continue; + } + + $whitespace = ''; + $previousIndex = $index - 1; + + if ($tokens[$previousIndex]->isWhitespace()) { + $whitespace = $tokens[$previousIndex]->getContent(); + --$previousIndex; + } + + if ($tokens[$previousIndex]->isGivenKind(T_OPEN_TAG)) { + $whitespace = Preg::replace('/\S/', '', $tokens[$previousIndex]->getContent()).$whitespace; + } + + if (!Preg::match('/\R(\h*)$/', $whitespace, $matches)) { + continue; + } + + if ($token->isGivenKind(T_COMMENT) && 'all_multiline' !== $this->configuration['comment_type'] && Preg::match('/\R(?:\R|\s*[^\s\*])/', $token->getContent())) { + continue; + } + + $indentation = $matches[1]; + $lines = Preg::split('/\R/u', $token->getContent()); + + foreach ($lines as $lineNumber => $line) { + if (0 === $lineNumber) { + continue; + } + + $line = ltrim($line); + + if ($token->isGivenKind(T_COMMENT) && (!isset($line[0]) || '*' !== $line[0])) { + continue; + } + + if (!isset($line[0])) { + $line = '*'; + } elseif ('*' !== $line[0]) { + $line = '* '.$line; + } + + $lines[$lineNumber] = $indentation.' '.$line; + } + + $tokens[$index] = new Token([$token->getId(), implode($lineEnding, $lines)]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('comment_type', 'Whether to fix PHPDoc comments only (`phpdocs_only`), any multi-line comment whose lines all start with an asterisk (`phpdocs_like`) or any multi-line comment (`all_multiline`).')) + ->setAllowedValues(['phpdocs_only', 'phpdocs_like', 'all_multiline']) + ->setDefault('phpdocs_only') + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.php new file mode 100644 index 00000000..b2282e86 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.php @@ -0,0 +1,162 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + * @author Dariusz Rumiński + */ +final class GeneralPhpdocAnnotationRemoveFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Configured annotations should be omitted from PHPDoc.', + [ + new CodeSample( + ' ['author']] + ), + new CodeSample( + ' ['author'], 'case_sensitive' => false] + ), + new CodeSample( + ' ['package', 'subpackage']] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, PhpdocAlignFixer, PhpdocLineSpanFixer, PhpdocSeparationFixer, PhpdocTrimFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 10; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if (0 === \count($this->configuration['annotations'])) { + return; + } + + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $annotations = $this->getAnnotationsToRemove($doc); + + // nothing to do if there are no annotations + if (0 === \count($annotations)) { + continue; + } + + foreach ($annotations as $annotation) { + $annotation->remove(); + } + + if ('' === $doc->getContent()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } else { + $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('annotations', 'List of annotations to remove, e.g. `["author"]`.')) + ->setAllowedTypes(['array']) + ->setDefault([]) + ->getOption(), + (new FixerOptionBuilder('case_sensitive', 'Should annotations be case sensitive.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + /** + * @return list + */ + private function getAnnotationsToRemove(DocBlock $doc): array + { + if (true === $this->configuration['case_sensitive']) { + return $doc->getAnnotationsOfType($this->configuration['annotations']); + } + + $typesToSearchFor = array_map(static fn (string $type): string => strtolower($type), $this->configuration['annotations']); + + $annotations = []; + + foreach ($doc->getAnnotations() as $annotation) { + $tagName = strtolower($annotation->getTag()->getName()); + if (\in_array($tagName, $typesToSearchFor, true)) { + $annotations[] = $annotation; + } + } + + return $annotations; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.php new file mode 100644 index 00000000..030aa338 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.php @@ -0,0 +1,199 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use Symfony\Component\OptionsResolver\Options; + +final class GeneralPhpdocTagRenameFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Renames PHPDoc tags.', + [ + new CodeSample(" [ + 'inheritDocs' => 'inheritDoc', + ], + ]), + new CodeSample(" [ + 'inheritDocs' => 'inheritDoc', + ], + 'fix_annotation' => false, + ]), + new CodeSample(" [ + 'inheritDocs' => 'inheritDoc', + ], + 'fix_inline' => false, + ]), + new CodeSample(" [ + 'inheritDocs' => 'inheritDoc', + ], + 'case_sensitive' => true, + ]), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + // must be run before PhpdocAddMissingParamAnnotationFixer + return 11; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('fix_annotation', 'Whether annotation tags should be fixed.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('fix_inline', 'Whether inline tags should be fixed.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('replacements', 'A map of tags to replace.')) + ->setAllowedTypes(['array']) + ->setNormalizer(static function (Options $options, $value): array { + $normalizedValue = []; + + foreach ($value as $from => $to) { + if (!\is_string($from)) { + throw new InvalidOptionsException('Tag to replace must be a string.'); + } + + if (!\is_string($to)) { + throw new InvalidOptionsException(sprintf( + 'Tag to replace to from "%s" must be a string.', + $from + )); + } + + if (!Preg::match('#^\S+$#', $to) || str_contains($to, '*/')) { + throw new InvalidOptionsException(sprintf( + 'Tag "%s" cannot be replaced by invalid tag "%s".', + $from, + $to + )); + } + + $from = trim($from); + $to = trim($to); + + if (!$options['case_sensitive']) { + $lowercaseFrom = strtolower($from); + + if (isset($normalizedValue[$lowercaseFrom]) && $normalizedValue[$lowercaseFrom] !== $to) { + throw new InvalidOptionsException(sprintf( + 'Tag "%s" cannot be configured to be replaced with several different tags when case sensitivity is off.', + $from + )); + } + + $from = $lowercaseFrom; + } + + $normalizedValue[$from] = $to; + } + + foreach ($normalizedValue as $from => $to) { + if (isset($normalizedValue[$to]) && $normalizedValue[$to] !== $to) { + throw new InvalidOptionsException(sprintf( + 'Cannot change tag "%1$s" to tag "%2$s", as the tag "%2$s" is configured to be replaced to "%3$s".', + $from, + $to, + $normalizedValue[$to] + )); + } + } + + return $normalizedValue; + }) + ->setDefault([]) + ->getOption(), + (new FixerOptionBuilder('case_sensitive', 'Whether tags should be replaced only if they have exact same casing.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if (0 === \count($this->configuration['replacements'])) { + return; + } + + if (true === $this->configuration['fix_annotation']) { + $regex = $this->configuration['fix_inline'] + ? '/"[^"]*"(*SKIP)(*FAIL)|\b(?<=@)(%s)\b/' + : '/"[^"]*"(*SKIP)(*FAIL)|(?configuration['case_sensitive']; + $replacements = $this->configuration['replacements']; + $regex = sprintf($regex, implode('|', array_keys($replacements))); + + if ($caseInsensitive) { + $regex .= 'i'; + } + + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $tokens[$index] = new Token([T_DOC_COMMENT, Preg::replaceCallback( + $regex, + static function (array $matches) use ($caseInsensitive, $replacements) { + if ($caseInsensitive) { + $matches[1] = strtolower($matches[1]); + } + + return $replacements[$matches[1]]; + }, + $token->getContent() + )]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php new file mode 100644 index 00000000..33fb2d0e --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php @@ -0,0 +1,110 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + */ +final class NoBlankLinesAfterPhpdocFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be blank lines between docblock and the documented element.', + [ + new CodeSample( + ' $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + // get the next non-whitespace token inc comments, provided + // that there is whitespace between it and the current token + $next = $tokens->getNextNonWhitespace($index); + if ($index + 2 === $next && false === $tokens[$next]->isGivenKind($forbiddenSuccessors)) { + $this->fixWhitespace($tokens, $index + 1); + } + } + } + + /** + * Cleanup a whitespace token. + */ + private function fixWhitespace(Tokens $tokens, int $index): void + { + $content = $tokens[$index]->getContent(); + // if there is more than one new line in the whitespace, then we need to fix it + if (substr_count($content, "\n") > 1) { + // the final bit of the whitespace must be the next statement's indentation + $tokens[$index] = new Token([T_WHITESPACE, substr($content, strrpos($content, "\n"))]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoEmptyPhpdocFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoEmptyPhpdocFixer.php new file mode 100644 index 00000000..e2421139 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoEmptyPhpdocFixer.php @@ -0,0 +1,62 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; + +final class NoEmptyPhpdocFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be empty PHPDoc blocks.', + [new CodeSample("isTokenKindFound(T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + if (Preg::match('#^/\*\*[\s\*]*\*/$#', $token->getContent())) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php new file mode 100644 index 00000000..c8b62882 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php @@ -0,0 +1,689 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +final class NoSuperfluousPhpdocTagsFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const NO_TYPE_INFO = [ + 'types' => [], + 'allows_null' => true, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes `@param`, `@return` and `@var` tags that don\'t provide any useful information.', + [ + new CodeSample(' true]), + new CodeSample(' true]), + new CodeSample(' true]), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, PhpdocAlignFixer, VoidReturnFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, FullyQualifiedStrictTypesFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocIndentFixer, PhpdocLineSpanFixer, PhpdocReturnSelfReferenceFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 6; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $namespaceUseAnalyzer = new NamespaceUsesAnalyzer(); + $shortNames = []; + $currentSymbol = null; + $currentSymbolEndIndex = null; + + foreach ($namespaceUseAnalyzer->getDeclarationsFromTokens($tokens) as $namespaceUseAnalysis) { + $shortNames[strtolower($namespaceUseAnalysis->getShortName())] = strtolower($namespaceUseAnalysis->getFullName()); + } + + $symbolKinds = [T_CLASS, T_INTERFACE]; + if (\defined('T_ENUM')) { // @TODO drop the condition when requiring PHP 8.1+ + $symbolKinds[] = T_ENUM; + } + + foreach ($tokens as $index => $token) { + if ($index === $currentSymbolEndIndex) { + $currentSymbol = null; + $currentSymbolEndIndex = null; + + continue; + } + + if ($token->isGivenKind(T_CLASS) && $tokensAnalyzer->isAnonymousClass($index)) { + continue; + } + + if ($token->isGivenKind($symbolKinds)) { + $currentSymbol = $tokens[$tokens->getNextMeaningfulToken($index)]->getContent(); + $currentSymbolEndIndex = $tokens->findBlockEnd( + Tokens::BLOCK_TYPE_CURLY_BRACE, + $tokens->getNextTokenOfKind($index, ['{']), + ); + + continue; + } + + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $documentedElement = $this->findDocumentedElement($tokens, $index); + + if (null === $documentedElement) { + continue; + } + + $content = $initialContent = $token->getContent(); + + if (true === $this->configuration['remove_inheritdoc']) { + $content = $this->removeSuperfluousInheritDoc($content); + } + + $namespace = (new NamespacesAnalyzer())->getNamespaceAt($tokens, $index)->getFullName(); + if ('' === $namespace) { + $namespace = null; + } + + if ('function' === $documentedElement['type']) { + $content = $this->fixFunctionDocComment($content, $tokens, $documentedElement, $namespace, $currentSymbol, $shortNames); + } elseif ('property' === $documentedElement['type']) { + $content = $this->fixPropertyDocComment($content, $tokens, $documentedElement, $namespace, $currentSymbol, $shortNames); + } elseif ('classy' === $documentedElement['type']) { + $content = $this->fixClassDocComment($content, $documentedElement); + } else { + throw new \RuntimeException('Unknown type.'); + } + + if ('' === $content) { + $content = '/** */'; + } + + if ($content !== $initialContent) { + $tokens[$index] = new Token([T_DOC_COMMENT, $content]); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('allow_mixed', 'Whether type `mixed` without description is allowed (`true`) or considered superfluous (`false`).')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('remove_inheritdoc', 'Remove `@inheritDoc` tags.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('allow_unused_params', 'Whether `param` annotation without actual signature is allowed (`true`) or considered superfluous (`false`).')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * @return null|array{ + * index: int, + * type: 'classy'|'function'|'property', + * modifiers: array, + * types: array, + * } + */ + private function findDocumentedElement(Tokens $tokens, int $docCommentIndex): ?array + { + $modifierKinds = [ + T_PRIVATE, + T_PROTECTED, + T_PUBLIC, + T_ABSTRACT, + T_FINAL, + T_STATIC, + ]; + + $typeKinds = [ + CT::T_NULLABLE_TYPE, + CT::T_ARRAY_TYPEHINT, + CT::T_TYPE_ALTERNATION, + CT::T_TYPE_INTERSECTION, + T_STRING, + T_NS_SEPARATOR, + ]; + + if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required + $modifierKinds[] = T_READONLY; + } + + $element = [ + 'modifiers' => [], + 'types' => [], + ]; + + $index = $tokens->getNextMeaningfulToken($docCommentIndex); + + // @TODO: drop condition when PHP 8.0+ is required + if (null !== $index && \defined('T_ATTRIBUTE') && $tokens[$index]->isGivenKind(T_ATTRIBUTE)) { + do { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + $index = $tokens->getNextMeaningfulToken($index); + } while (null !== $index && $tokens[$index]->isGivenKind(T_ATTRIBUTE)); + } + + while (true) { + if (null === $index) { + break; + } + + if ($tokens[$index]->isClassy()) { + $element['index'] = $index; + $element['type'] = 'classy'; + + return $element; + } + + if ($tokens[$index]->isGivenKind(T_FUNCTION)) { + $element['index'] = $index; + $element['type'] = 'function'; + + return $element; + } + + if ($tokens[$index]->isGivenKind(T_VARIABLE)) { + $element['index'] = $index; + $element['type'] = 'property'; + + return $element; + } + + if ($tokens[$index]->isGivenKind($modifierKinds)) { + $element['modifiers'][$index] = $tokens[$index]; + } elseif ($tokens[$index]->isGivenKind($typeKinds)) { + $element['types'][$index] = $tokens[$index]; + } else { + break; + } + + $index = $tokens->getNextMeaningfulToken($index); + } + + return null; + } + + /** + * @param array{ + * index: int, + * type: 'function', + * modifiers: array, + * types: array, + * } $element + * @param null|non-empty-string $namespace + * @param array $shortNames + */ + private function fixFunctionDocComment( + string $content, + Tokens $tokens, + array $element, + ?string $namespace, + ?string $currentSymbol, + array $shortNames + ): string { + $docBlock = new DocBlock($content); + + $openingParenthesisIndex = $tokens->getNextTokenOfKind($element['index'], ['(']); + $closingParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingParenthesisIndex); + + $argumentsInfo = $this->getArgumentsInfo( + $tokens, + $openingParenthesisIndex + 1, + $closingParenthesisIndex - 1 + ); + + foreach ($docBlock->getAnnotationsOfType('param') as $annotation) { + $argumentName = $annotation->getVariableName(); + + if (null === $argumentName) { + if ($this->annotationIsSuperfluous($annotation, self::NO_TYPE_INFO, $namespace, $currentSymbol, $shortNames)) { + $annotation->remove(); + } + + continue; + } + + if (!isset($argumentsInfo[$argumentName]) && true === $this->configuration['allow_unused_params']) { + continue; + } + + if (!isset($argumentsInfo[$argumentName]) || $this->annotationIsSuperfluous($annotation, $argumentsInfo[$argumentName], $namespace, $currentSymbol, $shortNames)) { + $annotation->remove(); + } + } + + $returnTypeInfo = $this->getReturnTypeInfo($tokens, $closingParenthesisIndex); + + foreach ($docBlock->getAnnotationsOfType('return') as $annotation) { + if ($this->annotationIsSuperfluous($annotation, $returnTypeInfo, $namespace, $currentSymbol, $shortNames)) { + $annotation->remove(); + } + } + + $this->removeSuperfluousModifierAnnotation($docBlock, $element); + + return $docBlock->getContent(); + } + + /** + * @param array{ + * index: int, + * type: 'property', + * modifiers: array, + * types: array, + * } $element + * @param null|non-empty-string $namespace + * @param array $shortNames + */ + private function fixPropertyDocComment( + string $content, + Tokens $tokens, + array $element, + ?string $namespace, + ?string $currentSymbol, + array $shortNames + ): string { + if (\count($element['types']) > 0) { + $propertyTypeInfo = $this->parseTypeHint($tokens, array_key_first($element['types'])); + } else { + $propertyTypeInfo = self::NO_TYPE_INFO; + } + + $docBlock = new DocBlock($content); + + foreach ($docBlock->getAnnotationsOfType('var') as $annotation) { + if ($this->annotationIsSuperfluous($annotation, $propertyTypeInfo, $namespace, $currentSymbol, $shortNames)) { + $annotation->remove(); + } + } + + return $docBlock->getContent(); + } + + /** + * @param array{ + * index: int, + * type: 'classy', + * modifiers: array, + * types: array, + * } $element + */ + private function fixClassDocComment(string $content, array $element): string + { + $docBlock = new DocBlock($content); + + $this->removeSuperfluousModifierAnnotation($docBlock, $element); + + return $docBlock->getContent(); + } + + /** + * @return array, allows_null: bool}> + */ + private function getArgumentsInfo(Tokens $tokens, int $start, int $end): array + { + $argumentsInfo = []; + + for ($index = $start; $index <= $end; ++$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(T_VARIABLE)) { + continue; + } + + $beforeArgumentIndex = $tokens->getPrevTokenOfKind($index, ['(', ',']); + $typeIndex = $tokens->getNextMeaningfulToken($beforeArgumentIndex); + + if ($typeIndex !== $index) { + $info = $this->parseTypeHint($tokens, $typeIndex); + } else { + $info = self::NO_TYPE_INFO; + } + + if (!$info['allows_null']) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ( + $tokens[$nextIndex]->equals('=') + && $tokens[$tokens->getNextMeaningfulToken($nextIndex)]->equals([T_STRING, 'null'], false) + ) { + $info['allows_null'] = true; + } + } + + $argumentsInfo[$token->getContent()] = $info; + } + + return $argumentsInfo; + } + + /** + * @return array{types: list, allows_null: bool} + */ + private function getReturnTypeInfo(Tokens $tokens, int $closingParenthesisIndex): array + { + $colonIndex = $tokens->getNextMeaningfulToken($closingParenthesisIndex); + + return $tokens[$colonIndex]->isGivenKind(CT::T_TYPE_COLON) + ? $this->parseTypeHint($tokens, $tokens->getNextMeaningfulToken($colonIndex)) + : self::NO_TYPE_INFO; + } + + /** + * @param int $index The index of the first token of the type hint + * + * @return array{types: list, allows_null: bool} + */ + private function parseTypeHint(Tokens $tokens, int $index): array + { + $allowsNull = false; + + $types = []; + + while (true) { + $type = ''; + + if (\defined('T_READONLY') && $tokens[$index]->isGivenKind(T_READONLY)) { // @TODO: simplify condition when PHP 8.1+ is required + $index = $tokens->getNextMeaningfulToken($index); + } + + if ($tokens[$index]->isGivenKind([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE])) { + $index = $tokens->getNextMeaningfulToken($index); + + continue; + } + + if ($tokens[$index]->isGivenKind(CT::T_NULLABLE_TYPE)) { + $allowsNull = true; + $index = $tokens->getNextMeaningfulToken($index); + } + + while ($tokens[$index]->isGivenKind([T_NS_SEPARATOR, T_STATIC, T_STRING, CT::T_ARRAY_TYPEHINT, T_CALLABLE])) { + $type .= $tokens[$index]->getContent(); + $index = $tokens->getNextMeaningfulToken($index); + } + + if ('' === $type) { + break; + } + + $types[] = $type; + + if (!$tokens[$index]->isGivenKind([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION])) { + break; + } + + $index = $tokens->getNextMeaningfulToken($index); + } + + return [ + 'types' => $types, + 'allows_null' => $allowsNull, + ]; + } + + /** + * @param null|non-empty-string $namespace + * @param array $symbolShortNames + */ + private function annotationIsSuperfluous( + Annotation $annotation, + array $info, + ?string $namespace, + ?string $currentSymbol, + array $symbolShortNames + ): bool { + if ('param' === $annotation->getTag()->getName()) { + $regex = '{@param(?:\s+'.TypeExpression::REGEX_TYPES.')?(?!\S)(?:\s+(?:\&\s*)?(?:\.{3}\s*)?\$\S+)?(?:\s+(?(?!\*+\/)\S+))?}s'; + } elseif ('var' === $annotation->getTag()->getName()) { + $regex = '{@var(?:\s+'.TypeExpression::REGEX_TYPES.')?(?!\S)(?:\s+\$\S+)?(?:\s+(?(?!\*\/)\S+))?}s'; + } else { + $regex = '{@return(?:\s+'.TypeExpression::REGEX_TYPES.')?(?!\S)(?:\s+(?(?!\*\/)\S+))?}s'; + } + + if (!Preg::match($regex, $annotation->getContent(), $matches)) { + // Unable to match the annotation, it must be malformed or has unsupported format. + // Either way we don't want to tinker with it. + return false; + } + + if (isset($matches['description'])) { + return false; + } + + if (!isset($matches['types']) || '' === $matches['types']) { + // If there's no type info in the annotation, further checks make no sense, exit early. + return true; + } + + $annotationTypes = $this->toComparableNames($annotation->getTypes(), $namespace, $currentSymbol, $symbolShortNames); + + if (['null'] === $annotationTypes && ['null'] !== $info['types']) { + return false; + } + + if (['mixed'] === $annotationTypes && [] === $info['types']) { + return false === $this->configuration['allow_mixed']; + } + + $actualTypes = $info['types']; + + if ($info['allows_null']) { + $actualTypes[] = 'null'; + } + + $actualTypes = $this->toComparableNames($actualTypes, $namespace, $currentSymbol, $symbolShortNames); + + if ($annotationTypes === $actualTypes) { + return true; + } + + // retry comparison with annotation type unioned with null + // phpstan implies the null presence from the native type + return $actualTypes === $this->toComparableNames(array_merge($annotationTypes, ['null']), null, null, []); + } + + /** + * Normalizes types to make them comparable. + * + * Converts given types to lowercase, replaces imports aliases with + * their matching FQCN, and finally sorts the result. + * + * @param string[] $types The types to normalize + * @param null|non-empty-string $namespace + * @param array $symbolShortNames The imports aliases + * + * @return array The normalized types + */ + private function toComparableNames(array $types, ?string $namespace, ?string $currentSymbol, array $symbolShortNames): array + { + $normalized = array_map( + function (string $type) use ($namespace, $currentSymbol, $symbolShortNames): string { + if (str_contains($type, '&')) { + $intersects = explode('&', $type); + + $intersects = $this->toComparableNames($intersects, $namespace, $currentSymbol, $symbolShortNames); + + return implode('&', $intersects); + } + + if ('self' === $type && null !== $currentSymbol) { + $type = $currentSymbol; + } + + $type = strtolower($type); + + if (isset($symbolShortNames[$type])) { + return $symbolShortNames[$type]; // always FQCN /wo leading backslash and in lower-case + } + + if (str_starts_with($type, '\\')) { + return substr($type, 1); + } + + if (null !== $namespace && !(new TypeAnalysis($type))->isReservedType()) { + $type = strtolower($namespace).'\\'.$type; + } + + return $type; + }, + $types + ); + + sort($normalized); + + return $normalized; + } + + private function removeSuperfluousInheritDoc(string $docComment): string + { + return Preg::replace('~ + # $1: before @inheritDoc tag + ( + # beginning of comment or a PHPDoc tag + (?: + ^/\*\* + (?: + \R + [ \t]*(?:\*[ \t]*)? + )*? + | + @\N+ + ) + + # empty comment lines + (?: + \R + [ \t]*(?:\*[ \t]*?)? + )* + ) + + # spaces before @inheritDoc tag + [ \t]* + + # @inheritDoc tag + (?:@inheritDocs?|\{@inheritDocs?\}) + + # $2: after @inheritDoc tag + ( + # empty comment lines + (?: + \R + [ \t]*(?:\*[ \t]*)? + )* + + # a PHPDoc tag or end of comment + (?: + @\N+ + | + (?: + \R + [ \t]*(?:\*[ \t]*)? + )* + [ \t]*\*/$ + ) + ) + ~ix', '$1$2', $docComment); + } + + private function removeSuperfluousModifierAnnotation(DocBlock $docBlock, array $element): void + { + foreach (['abstract' => T_ABSTRACT, 'final' => T_FINAL] as $annotationType => $modifierToken) { + $annotations = $docBlock->getAnnotationsOfType($annotationType); + + foreach ($element['modifiers'] as $token) { + if ($token->isGivenKind($modifierToken)) { + foreach ($annotations as $annotation) { + $annotation->remove(); + } + } + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php new file mode 100644 index 00000000..908a4bc0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php @@ -0,0 +1,276 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class PhpdocAddMissingParamAnnotationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPDoc should contain `@param` for all params.', + [ + new CodeSample( + ' true] + ), + new CodeSample( + ' false] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer, PhpdocOrderFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocTagRenameFixer, PhpdocIndentFixer, PhpdocNoAliasTagFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 10; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $tokenContent = $token->getContent(); + + if (false !== stripos($tokenContent, 'inheritdoc')) { + continue; + } + + // ignore one-line phpdocs like `/** foo */`, as there is no place to put new annotations + if (!str_contains($tokenContent, "\n")) { + continue; + } + + $mainIndex = $index; + $index = $tokens->getNextMeaningfulToken($index); + + if (null === $index) { + return; + } + + while ($tokens[$index]->isGivenKind([ + T_ABSTRACT, + T_FINAL, + T_PRIVATE, + T_PROTECTED, + T_PUBLIC, + T_STATIC, + ])) { + $index = $tokens->getNextMeaningfulToken($index); + } + + if (!$tokens[$index]->isGivenKind(T_FUNCTION)) { + continue; + } + + $openIndex = $tokens->getNextTokenOfKind($index, ['(']); + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); + + $arguments = []; + + foreach ($argumentsAnalyzer->getArguments($tokens, $openIndex, $index) as $start => $end) { + $argumentInfo = $this->prepareArgumentInformation($tokens, $start, $end); + + if (false === $this->configuration['only_untyped'] || '' === $argumentInfo['type']) { + $arguments[$argumentInfo['name']] = $argumentInfo; + } + } + + if (0 === \count($arguments)) { + continue; + } + + $doc = new DocBlock($tokenContent); + $lastParamLine = null; + + foreach ($doc->getAnnotationsOfType('param') as $annotation) { + $pregMatched = Preg::match('/^[^$]+(\$\w+).*$/s', $annotation->getContent(), $matches); + + if ($pregMatched) { + unset($arguments[$matches[1]]); + } + + $lastParamLine = max($lastParamLine, $annotation->getEnd()); + } + + if (0 === \count($arguments)) { + continue; + } + + $lines = $doc->getLines(); + $linesCount = \count($lines); + + Preg::match('/^(\s*).*$/', $lines[$linesCount - 1]->getContent(), $matches); + $indent = $matches[1]; + + $newLines = []; + + foreach ($arguments as $argument) { + $type = $argument['type'] ?: 'mixed'; + + if (!str_starts_with($type, '?') && 'null' === strtolower($argument['default'])) { + $type = 'null|'.$type; + } + + $newLines[] = new Line(sprintf( + '%s* @param %s %s%s', + $indent, + $type, + $argument['name'], + $this->whitespacesConfig->getLineEnding() + )); + } + + array_splice( + $lines, + $lastParamLine > 0 ? $lastParamLine + 1 : $linesCount - 1, + 0, + $newLines + ); + + $tokens[$mainIndex] = new Token([T_DOC_COMMENT, implode('', $lines)]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('only_untyped', 'Whether to add missing `@param` annotations for untyped parameters only.')) + ->setDefault(true) + ->setAllowedTypes(['bool']) + ->getOption(), + ]); + } + + /** + * @return array{default: string, name: string, type: string} + */ + private function prepareArgumentInformation(Tokens $tokens, int $start, int $end): array + { + $info = [ + 'default' => '', + 'name' => '', + 'type' => '', + ]; + + $sawName = false; + + for ($index = $start; $index <= $end; ++$index) { + $token = $tokens[$index]; + + if ( + $token->isComment() + || $token->isWhitespace() + || $token->isGivenKind([ + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, + ]) + || (\defined('T_READONLY') && $token->isGivenKind(T_READONLY)) + ) { + continue; + } + + if ($token->isGivenKind(T_VARIABLE)) { + $sawName = true; + $info['name'] = $token->getContent(); + + continue; + } + + if ($token->equals('=')) { + continue; + } + + if ($sawName) { + $info['default'] .= $token->getContent(); + } elseif (!$token->equals('&')) { + if ($token->isGivenKind(T_ELLIPSIS)) { + if ('' === $info['type']) { + $info['type'] = 'array'; + } else { + $info['type'] .= '[]'; + } + } else { + $info['type'] .= $token->getContent(); + } + } + } + + return $info; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAlignFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAlignFixer.php new file mode 100644 index 00000000..fb18574e --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAlignFixer.php @@ -0,0 +1,442 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Fabien Potencier + * @author Jordi Boggiano + * @author Sebastiaan Stok + * @author Graham Campbell + * @author Dariusz Rumiński + */ +final class PhpdocAlignFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @internal + */ + public const ALIGN_LEFT = 'left'; + + /** + * @internal + */ + public const ALIGN_VERTICAL = 'vertical'; + + private const DEFAULT_TAGS = [ + 'method', + 'param', + 'property', + 'return', + 'throws', + 'type', + 'var', + ]; + + private const TAGS_WITH_NAME = [ + 'param', + 'property', + 'property-read', + 'property-write', + 'phpstan-param', + 'phpstan-property', + 'phpstan-property-read', + 'phpstan-property-write', + 'phpstan-assert', + 'phpstan-assert-if-true', + 'phpstan-assert-if-false', + 'psalm-param', + 'psalm-param-out', + 'psalm-property', + 'psalm-property-read', + 'psalm-property-write', + 'psalm-assert', + 'psalm-assert-if-true', + 'psalm-assert-if-false', + ]; + + private const TAGS_WITH_METHOD_SIGNATURE = [ + 'method', + 'phpstan-method', + 'psalm-method', + ]; + + private string $regex; + + private string $regexCommentLine; + + /** + * @var string + */ + private $align; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $tagsWithNameToAlign = array_intersect($this->configuration['tags'], self::TAGS_WITH_NAME); + $tagsWithMethodSignatureToAlign = array_intersect($this->configuration['tags'], self::TAGS_WITH_METHOD_SIGNATURE); + $tagsWithoutNameToAlign = array_diff($this->configuration['tags'], $tagsWithNameToAlign, $tagsWithMethodSignatureToAlign); + + $indentRegex = '^(?P(?:\ {2}|\t)*)\ ?'; + + $types = []; + + // e.g. @param <$var> + if ([] !== $tagsWithNameToAlign) { + $types[] = '(?P'.implode('|', $tagsWithNameToAlign).')\s+(?P(?:'.TypeExpression::REGEX_TYPES.')?)\s*(?P(?:&|\.{3})?\$\S+)'; + } + + // e.g. @return + if ([] !== $tagsWithoutNameToAlign) { + $types[] = '(?P'.implode('|', $tagsWithoutNameToAlign).')\s+(?P(?:'.TypeExpression::REGEX_TYPES.')?)'; + } + + // e.g. @method + if ([] !== $tagsWithMethodSignatureToAlign) { + $types[] = '(?P'.implode('|', $tagsWithMethodSignatureToAlign).')(\s+(?Pstatic))?(\s+(?P(?:'.TypeExpression::REGEX_TYPES.')?))\s+(?P.+\))'; + } + + // optional + $desc = '(?:\s+(?P\V*))'; + + $this->regex = '/'.$indentRegex.'\*\h*@(?J)(?:'.implode('|', $types).')'.$desc.'\h*\r?$/'; + $this->regexCommentLine = '/'.$indentRegex.'\*(?!\h?+@)(?:\s+(?P\V+))(?align = $this->configuration['align']; + } + + public function getDefinition(): FixerDefinitionInterface + { + $code = <<<'EOF' + self::ALIGN_VERTICAL]), + new CodeSample($code, ['align' => self::ALIGN_LEFT]), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAnnotationWithoutDotFixer, PhpdocIndentFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocScalarFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagTypeFixer, PhpdocToCommentFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. + */ + public function getPriority(): int + { + /* + * Should be run after all other docblock fixers. This because they + * modify other annotations to change their type and or separation + * which totally change the behavior of this fixer. It's important that + * annotations are of the correct type, and are grouped correctly + * before running this fixer. + */ + return -42; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $content = $token->getContent(); + $docBlock = new DocBlock($content); + $this->fixDocBlock($docBlock); + $newContent = $docBlock->getContent(); + if ($newContent !== $content) { + $tokens[$index] = new Token([T_DOC_COMMENT, $newContent]); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $tags = new FixerOptionBuilder( + 'tags', + 'The tags that should be aligned. Allowed values are tags with name (`\''.implode('\', \'', self::TAGS_WITH_NAME).'\'`), tags with method signature (`\''.implode('\', \'', self::TAGS_WITH_METHOD_SIGNATURE).'\'`) and any custom tag with description (e.g. `@tag `).' + ); + $tags + ->setAllowedTypes(['array']) + ->setDefault(self::DEFAULT_TAGS) + ; + + $align = new FixerOptionBuilder('align', 'How comments should be aligned.'); + $align + ->setAllowedTypes(['string']) + ->setAllowedValues([self::ALIGN_LEFT, self::ALIGN_VERTICAL]) + ->setDefault(self::ALIGN_VERTICAL) + ; + + return new FixerConfigurationResolver([$tags->getOption(), $align->getOption()]); + } + + private function fixDocBlock(DocBlock $docBlock): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + for ($i = 0, $l = \count($docBlock->getLines()); $i < $l; ++$i) { + $matches = $this->getMatches($docBlock->getLine($i)->getContent()); + + if (null === $matches) { + continue; + } + + $current = $i; + $items = [$matches]; + + while (true) { + if (null === $docBlock->getLine(++$i)) { + break 2; + } + + $matches = $this->getMatches($docBlock->getLine($i)->getContent(), true); + if (null === $matches) { + break; + } + + $items[] = $matches; + } + + // compute the max length of the tag, hint and variables + $hasStatic = false; + $tagMax = 0; + $hintMax = 0; + $varMax = 0; + + foreach ($items as $item) { + if (null === $item['tag']) { + continue; + } + + $hasStatic |= '' !== $item['static']; + $tagMax = max($tagMax, \strlen($item['tag'])); + $hintMax = max($hintMax, \strlen($item['hint'])); + $varMax = max($varMax, \strlen($item['var'])); + } + + $currTag = null; + + // update + foreach ($items as $j => $item) { + if (null === $item['tag']) { + if ('@' === $item['desc'][0]) { + $line = $item['indent'].' * '.$item['desc']; + $docBlock->getLine($current + $j)->setContent($line.$lineEnding); + + continue; + } + + $extraIndent = 2; + + if (\in_array($currTag, self::TAGS_WITH_NAME, true) || \in_array($currTag, self::TAGS_WITH_METHOD_SIGNATURE, true)) { + $extraIndent += $varMax + 1; + } + + if ($hasStatic) { + $extraIndent += 7; // \strlen('static '); + } + + $line = + $item['indent'] + .' * ' + .$this->getIndent( + $tagMax + $hintMax + $extraIndent, + $this->getLeftAlignedDescriptionIndent($items, $j) + ) + .$item['desc']; + + $docBlock->getLine($current + $j)->setContent($line.$lineEnding); + + continue; + } + + $currTag = $item['tag']; + + $line = + $item['indent'] + .' * @' + .$item['tag']; + + if ($hasStatic) { + $line .= + $this->getIndent( + $tagMax - \strlen($item['tag']) + 1, + '' !== $item['static'] ? 1 : 0 + ) + .($item['static'] ?: $this->getIndent(6 /* \strlen('static') */, 0)); + $hintVerticalAlignIndent = 1; + } else { + $hintVerticalAlignIndent = $tagMax - \strlen($item['tag']) + 1; + } + + $line .= + $this->getIndent( + $hintVerticalAlignIndent, + '' !== $item['hint'] ? 1 : 0 + ) + .$item['hint']; + + if ('' !== $item['var']) { + $line .= + $this->getIndent(($hintMax ?: -1) - \strlen($item['hint']) + 1) + .$item['var'] + .( + '' !== $item['desc'] + ? $this->getIndent($varMax - \strlen($item['var']) + 1).$item['desc'] + : '' + ); + } elseif ('' !== $item['desc']) { + $line .= $this->getIndent($hintMax - \strlen($item['hint']) + 1).$item['desc']; + } + + $docBlock->getLine($current + $j)->setContent($line.$lineEnding); + } + } + } + + /** + * @TODO Introduce proper DTO instead of an array + * + * @return null|array{indent: null|string, tag: null|string, hint: string, var: null|string, static: string, desc?: null|string} + */ + private function getMatches(string $line, bool $matchCommentOnly = false): ?array + { + if (Preg::match($this->regex, $line, $matches)) { + if (isset($matches['tag2']) && '' !== $matches['tag2']) { + $matches['tag'] = $matches['tag2']; + $matches['hint'] = $matches['hint2']; + $matches['var'] = ''; + } + + if (isset($matches['tag3']) && '' !== $matches['tag3']) { + $matches['tag'] = $matches['tag3']; + $matches['hint'] = $matches['hint3']; + $matches['var'] = $matches['signature']; + + // Since static can be both a return type declaration & a keyword that defines static methods + // we assume it's a type declaration when only one value is present + if ('' === $matches['hint'] && '' !== $matches['static']) { + $matches['hint'] = $matches['static']; + $matches['static'] = ''; + } + } + + if (isset($matches['hint'])) { + $matches['hint'] = trim($matches['hint']); + } + + if (!isset($matches['static'])) { + $matches['static'] = ''; + } + + return $matches; + } + + if ($matchCommentOnly && Preg::match($this->regexCommentLine, $line, $matches)) { + $matches['tag'] = null; + $matches['var'] = ''; + $matches['hint'] = ''; + $matches['static'] = ''; + + return $matches; + } + + return null; + } + + private function getIndent(int $verticalAlignIndent, int $leftAlignIndent = 1): string + { + $indent = self::ALIGN_VERTICAL === $this->align ? $verticalAlignIndent : $leftAlignIndent; + + return str_repeat(' ', $indent); + } + + /** + * @param non-empty-list $items + */ + private function getLeftAlignedDescriptionIndent(array $items, int $index): int + { + if (self::ALIGN_LEFT !== $this->align) { + return 0; + } + + // Find last tagged line: + $item = null; + for (; $index >= 0; --$index) { + $item = $items[$index]; + if (null !== $item['tag']) { + break; + } + } + + // No last tag found — no indent: + if (null === $item) { + return 0; + } + + // Indent according to existing values: + return + $this->getSentenceIndent($item['static']) + + $this->getSentenceIndent($item['tag']) + + $this->getSentenceIndent($item['hint']) + + $this->getSentenceIndent($item['var']); + } + + /** + * Get indent for sentence. + */ + private function getSentenceIndent(?string $sentence): int + { + if (null === $sentence) { + return 0; + } + + $length = \strlen($sentence); + + return 0 === $length ? 0 : $length + 1; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php new file mode 100644 index 00000000..8cacdc38 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php @@ -0,0 +1,123 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class PhpdocAnnotationWithoutDotFixer extends AbstractFixer +{ + /** + * @var string[] + */ + private array $tags = ['throws', 'return', 'param', 'internal', 'deprecated', 'var', 'type']; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPDoc annotation descriptions should not be a sentence.', + [new CodeSample('isTokenKindFound(T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $annotations = $doc->getAnnotations(); + + if (0 === \count($annotations)) { + continue; + } + + foreach ($annotations as $annotation) { + if ( + !$annotation->getTag()->valid() || !\in_array($annotation->getTag()->getName(), $this->tags, true) + ) { + continue; + } + + $lineAfterAnnotation = $doc->getLine($annotation->getEnd() + 1); + if (null !== $lineAfterAnnotation) { + $lineAfterAnnotationTrimmed = ltrim($lineAfterAnnotation->getContent()); + if ('' === $lineAfterAnnotationTrimmed || !str_starts_with($lineAfterAnnotationTrimmed, '*')) { + // malformed PHPDoc, missing asterisk ! + continue; + } + } + + $content = $annotation->getContent(); + + if ( + !Preg::match('/[.。]\h*$/u', $content) + || Preg::match('/[.。](?!\h*$)/u', $content, $matches) + ) { + continue; + } + + $endLine = $doc->getLine($annotation->getEnd()); + $endLine->setContent(Preg::replace('/(?getContent())); + + $startLine = $doc->getLine($annotation->getStart()); + $optionalTypeRegEx = $annotation->supportTypes() + ? sprintf('(?:%s\s+(?:\$\w+\s+)?)?', preg_quote(implode('|', $annotation->getTypes()), '/')) + : ''; + $content = Preg::replaceCallback( + '/^(\s*\*\s*@\w+\s+'.$optionalTypeRegEx.')(\p{Lu}?(?=\p{Ll}|\p{Zs}))(.*)$/', + static fn (array $matches): string => $matches[1].mb_strtolower($matches[2]).$matches[3], + $startLine->getContent(), + 1 + ); + $startLine->setContent($content); + } + + $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocIndentFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocIndentFixer.php new file mode 100644 index 00000000..dcb49fc2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocIndentFixer.php @@ -0,0 +1,135 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Utils; + +/** + * @author Ceeram + * @author Graham Campbell + */ +final class PhpdocIndentFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Docblocks should have the same indentation as the documented subject.', + [new CodeSample('isTokenKindFound(T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + // skip if there is no next token or if next token is block end `}` + if (null === $nextIndex || $tokens[$nextIndex]->equals('}')) { + continue; + } + + $prevIndex = $index - 1; + $prevToken = $tokens[$prevIndex]; + + // ignore inline docblocks + if ( + $prevToken->isGivenKind(T_OPEN_TAG) + || ($prevToken->isWhitespace(" \t") && !$tokens[$index - 2]->isGivenKind(T_OPEN_TAG)) + || $prevToken->equalsAny([';', ',', '{', '(']) + ) { + continue; + } + + if ($tokens[$nextIndex - 1]->isWhitespace()) { + $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$nextIndex - 1]); + } else { + $indent = ''; + } + + $newPrevContent = $this->fixWhitespaceBeforeDocblock($prevToken->getContent(), $indent); + + if ('' !== $newPrevContent) { + if ($prevToken->isArray()) { + $tokens[$prevIndex] = new Token([$prevToken->getId(), $newPrevContent]); + } else { + $tokens[$prevIndex] = new Token($newPrevContent); + } + } else { + $tokens->clearAt($prevIndex); + } + + $tokens[$index] = new Token([T_DOC_COMMENT, $this->fixDocBlock($token->getContent(), $indent)]); + } + } + + /** + * Fix indentation of Docblock. + * + * @param string $content Docblock contents + * @param string $indent Indentation to apply + * + * @return string Dockblock contents including correct indentation + */ + private function fixDocBlock(string $content, string $indent): string + { + return ltrim(Preg::replace('/^\h*\*/m', $indent.' *', $content)); + } + + /** + * @param string $content Whitespace before Docblock + * @param string $indent Indentation of the documented subject + * + * @return string Whitespace including correct indentation for Dockblock after this whitespace + */ + private function fixWhitespaceBeforeDocblock(string $content, string $indent): string + { + return rtrim($content, " \t").$indent; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.php new file mode 100644 index 00000000..668dd843 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.php @@ -0,0 +1,107 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class PhpdocInlineTagNormalizerFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Fixes PHPDoc inline tags.', + [ + new CodeSample( + " ['TUTORIAL']] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if (0 === \count($this->configuration['tags'])) { + return; + } + + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + // Move `@` inside tag, for example @{tag} -> {@tag}, replace multiple curly brackets, + // remove spaces between '{' and '@', remove white space between end + // of text and closing bracket and between the tag and inline comment. + $content = Preg::replaceCallback( + sprintf( + '#(?:@{+|{+\h*@)\h*(%s)\b([^}]*)(?:}+)#i', + implode('|', array_map(static fn (string $tag): string => preg_quote($tag, '/'), $this->configuration['tags'])) + ), + static function (array $matches): string { + $doc = trim($matches[2]); + + if ('' === $doc) { + return '{@'.$matches[1].'}'; + } + + return '{@'.$matches[1].' '.$doc.'}'; + }, + $token->getContent() + ); + + $tokens[$index] = new Token([T_DOC_COMMENT, $content]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('tags', 'The list of tags to normalize.')) + ->setAllowedTypes(['array']) + ->setDefault(['example', 'id', 'internal', 'inheritdoc', 'inheritdocs', 'link', 'source', 'toc', 'tutorial']) + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocLineSpanFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocLineSpanFixer.php new file mode 100644 index 00000000..a667dd20 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocLineSpanFixer.php @@ -0,0 +1,156 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Gert de Pagter + */ +final class PhpdocLineSpanFixer extends AbstractFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Changes doc blocks from single to multi line, or reversed. Works for class constants, properties and methods only.', + [ + new CodeSample(" 'single'] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 7; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('const', 'Whether const blocks should be single or multi line.')) + ->setAllowedValues(['single', 'multi', null]) + ->setDefault('multi') + ->getOption(), + (new FixerOptionBuilder('property', 'Whether property doc blocks should be single or multi line.')) + ->setAllowedValues(['single', 'multi', null]) + ->setDefault('multi') + ->getOption(), + (new FixerOptionBuilder('method', 'Whether method doc blocks should be single or multi line.')) + ->setAllowedValues(['single', 'multi', null]) + ->setDefault('multi') + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $analyzer = new TokensAnalyzer($tokens); + + foreach ($analyzer->getClassyElements() as $index => $element) { + if (!$this->hasDocBlock($tokens, $index)) { + continue; + } + + $type = $element['type']; + + if (!isset($this->configuration[$type])) { + continue; + } + + $docIndex = $this->getDocBlockIndex($tokens, $index); + $doc = new DocBlock($tokens[$docIndex]->getContent()); + + if ('multi' === $this->configuration[$type]) { + $doc->makeMultiLine(WhitespacesAnalyzer::detectIndent($tokens, $docIndex), $this->whitespacesConfig->getLineEnding()); + } elseif ('single' === $this->configuration[$type]) { + $doc->makeSingleLine(); + } + + $tokens->offsetSet($docIndex, new Token([T_DOC_COMMENT, $doc->getContent()])); + } + } + + private function hasDocBlock(Tokens $tokens, int $index): bool + { + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + + return $tokens[$docBlockIndex]->isGivenKind(T_DOC_COMMENT); + } + + private function getDocBlockIndex(Tokens $tokens, int $index): int + { + $propertyPartKinds = [ + T_PUBLIC, + T_PROTECTED, + T_PRIVATE, + T_FINAL, + T_ABSTRACT, + T_COMMENT, + T_VAR, + T_STATIC, + T_STRING, + T_NS_SEPARATOR, + CT::T_ARRAY_TYPEHINT, + CT::T_NULLABLE_TYPE, + ]; + + if (\defined('T_ATTRIBUTE')) { // @TODO: drop condition when PHP 8.0+ is required + $propertyPartKinds[] = T_ATTRIBUTE; + } + + if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required + $propertyPartKinds[] = T_READONLY; + } + + do { + $index = $tokens->getPrevNonWhitespace($index); + + if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $index = $tokens->getPrevTokenOfKind($index, [[T_ATTRIBUTE]]); + } + } while ($tokens[$index]->isGivenKind($propertyPartKinds)); + + return $index; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAccessFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAccessFixer.php new file mode 100644 index 00000000..12300026 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAccessFixer.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @author Graham Campbell + * @author Dariusz Rumiński + */ +final class PhpdocNoAccessFixer extends AbstractProxyFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + '`@access` annotations should be omitted from PHPDoc.', + [ + new CodeSample( + 'configure(['annotations' => ['access']]); + + return [$fixer]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.php new file mode 100644 index 00000000..5bd71385 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.php @@ -0,0 +1,126 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\ConfigurationException\InvalidConfigurationException; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; + +/** + * Case-sensitive tag replace fixer (does not process inline tags like {@inheritdoc}). + * + * @author Graham Campbell + * @author Dariusz Rumiński + */ +final class PhpdocNoAliasTagFixer extends AbstractProxyFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'No alias PHPDoc tags should be used.', + [ + new CodeSample( + ' ['link' => 'website']] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocSingleLineVarSpacingFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return parent::getPriority(); + } + + public function configure(array $configuration): void + { + parent::configure($configuration); + + /** @var GeneralPhpdocTagRenameFixer $generalPhpdocTagRenameFixer */ + $generalPhpdocTagRenameFixer = $this->proxyFixers['general_phpdoc_tag_rename']; + + try { + $generalPhpdocTagRenameFixer->configure([ + 'fix_annotation' => true, + 'fix_inline' => false, + 'replacements' => $this->configuration['replacements'], + 'case_sensitive' => true, + ]); + } catch (InvalidConfigurationException $exception) { + throw new InvalidFixerConfigurationException( + $this->getName(), + Preg::replace('/^\[.+?\] /', '', $exception->getMessage()), + $exception + ); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('replacements', 'Mapping between replaced annotations with new ones.')) + ->setAllowedTypes(['array']) + ->setDefault([ + 'property-read' => 'property', + 'property-write' => 'property', + 'type' => 'var', + 'link' => 'see', + ]) + ->getOption(), + ]); + } + + protected function createProxyFixers(): array + { + return [new GeneralPhpdocTagRenameFixer()]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php new file mode 100644 index 00000000..3b22bad9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php @@ -0,0 +1,117 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + */ +final class PhpdocNoEmptyReturnFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + '`@return void` and `@return null` annotations should be omitted from PHPDoc.', + [ + new CodeSample( + ' $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $annotations = $doc->getAnnotationsOfType('return'); + + if (0 === \count($annotations)) { + continue; + } + + foreach ($annotations as $annotation) { + $this->fixAnnotation($annotation); + } + + $newContent = $doc->getContent(); + + if ($newContent === $token->getContent()) { + continue; + } + + if ('' === $newContent) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + continue; + } + + $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); + } + } + + /** + * Remove `return void` or `return null` annotations. + */ + private function fixAnnotation(Annotation $annotation): void + { + $types = $annotation->getNormalizedTypes(); + + if (1 === \count($types) && ('null' === $types[0] || 'void' === $types[0])) { + $annotation->remove(); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoPackageFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoPackageFixer.php new file mode 100644 index 00000000..e254ad0c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoPackageFixer.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @author Graham Campbell + * @author Dariusz Rumiński + */ +final class PhpdocNoPackageFixer extends AbstractProxyFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + '`@package` and `@subpackage` annotations should be omitted from PHPDoc.', + [ + new CodeSample( + 'configure(['annotations' => ['package', 'subpackage']]); + + return [$fixer]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php new file mode 100644 index 00000000..4174f2d9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php @@ -0,0 +1,151 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Remove inheritdoc tags from classy that does not inherit. + */ +final class PhpdocNoUselessInheritdocFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Classy that does not inherit must not have `@inheritdoc` tags.', + [ + new CodeSample("isTokenKindFound(T_DOC_COMMENT) && $tokens->isAnyTokenKindsFound([T_CLASS, T_INTERFACE]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + // min. offset 4 as minimal candidate is @: isGivenKind([T_CLASS, T_INTERFACE])) { + $index = $this->fixClassy($tokens, $index); + } + } + } + + private function fixClassy(Tokens $tokens, int $index): int + { + // figure out where the classy starts + $classOpenIndex = $tokens->getNextTokenOfKind($index, ['{']); + + // figure out where the classy ends + $classEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpenIndex); + + // is classy extending or implementing some interface + $extendingOrImplementing = $this->isExtendingOrImplementing($tokens, $index, $classOpenIndex); + + if (!$extendingOrImplementing) { + // PHPDoc of classy should not have inherit tag even when using traits as Traits cannot provide this information + $this->fixClassyOutside($tokens, $index); + } + + // figure out if the classy uses a trait + if (!$extendingOrImplementing && $this->isUsingTrait($tokens, $index, $classOpenIndex, $classEndIndex)) { + $extendingOrImplementing = true; + } + + $this->fixClassyInside($tokens, $classOpenIndex, $classEndIndex, !$extendingOrImplementing); + + return $classEndIndex; + } + + private function fixClassyInside(Tokens $tokens, int $classOpenIndex, int $classEndIndex, bool $fixThisLevel): void + { + for ($i = $classOpenIndex; $i < $classEndIndex; ++$i) { + if ($tokens[$i]->isGivenKind(T_CLASS)) { + $i = $this->fixClassy($tokens, $i); + } elseif ($fixThisLevel && $tokens[$i]->isGivenKind(T_DOC_COMMENT)) { + $this->fixToken($tokens, $i); + } + } + } + + private function fixClassyOutside(Tokens $tokens, int $classIndex): void + { + $previousIndex = $tokens->getPrevNonWhitespace($classIndex); + if ($tokens[$previousIndex]->isGivenKind(T_DOC_COMMENT)) { + $this->fixToken($tokens, $previousIndex); + } + } + + private function fixToken(Tokens $tokens, int $tokenIndex): void + { + $count = 0; + $content = Preg::replaceCallback( + '#(\h*(?:@{*|{*\h*@)\h*inheritdoc\h*)([^}]*)((?:}*)\h*)#i', + static fn (array $matches): string => ' '.$matches[2], + $tokens[$tokenIndex]->getContent(), + -1, + $count + ); + + if ($count) { + $tokens[$tokenIndex] = new Token([T_DOC_COMMENT, $content]); + } + } + + private function isExtendingOrImplementing(Tokens $tokens, int $classIndex, int $classOpenIndex): bool + { + for ($index = $classIndex; $index < $classOpenIndex; ++$index) { + if ($tokens[$index]->isGivenKind([T_EXTENDS, T_IMPLEMENTS])) { + return true; + } + } + + return false; + } + + private function isUsingTrait(Tokens $tokens, int $classIndex, int $classOpenIndex, int $classCloseIndex): bool + { + if ($tokens[$classIndex]->isGivenKind(T_INTERFACE)) { + // cannot use Trait inside an interface + return false; + } + + $useIndex = $tokens->getNextTokenOfKind($classOpenIndex, [[CT::T_USE_TRAIT]]); + + return null !== $useIndex && $useIndex < $classCloseIndex; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php new file mode 100644 index 00000000..c3728efc --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php @@ -0,0 +1,214 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Options; + +/** + * @author Filippo Tessarotto + * @author Andreas Möller + */ +final class PhpdocOrderByValueFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Order phpdoc tags by value.', + [ + new CodeSample( + ' [ + 'author', + ], + ] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpUnitFqcnAnnotationFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return -10; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAllTokenKindsFound([T_CLASS, T_DOC_COMMENT]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if ([] === $this->configuration['annotations']) { + return; + } + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + foreach ($this->configuration['annotations'] as $type => $typeLowerCase) { + $findPattern = sprintf( + '/@%s\s.+@%s\s/s', + $type, + $type + ); + + if ( + !$tokens[$index]->isGivenKind(T_DOC_COMMENT) + || !Preg::match($findPattern, $tokens[$index]->getContent()) + ) { + continue; + } + + $docBlock = new DocBlock($tokens[$index]->getContent()); + + $annotations = $docBlock->getAnnotationsOfType($type); + $annotationMap = []; + + if (\in_array($type, ['property', 'property-read', 'property-write'], true)) { + $replacePattern = sprintf( + '/(?s)\*\s*@%s\s+(?P.+\s+)?\$(?P[^\s]+).*/', + $type + ); + + $replacement = '\2'; + } elseif ('method' === $type) { + $replacePattern = '/(?s)\*\s*@method\s+(?P.+\s+)?(?P.+)\(.*/'; + $replacement = '\2'; + } else { + $replacePattern = sprintf( + '/\*\s*@%s\s+(?P.+)/', + $typeLowerCase + ); + + $replacement = '\1'; + } + + foreach ($annotations as $annotation) { + $rawContent = $annotation->getContent(); + + $comparableContent = Preg::replace( + $replacePattern, + $replacement, + strtolower(trim($rawContent)) + ); + + $annotationMap[$comparableContent] = $rawContent; + } + + $orderedAnnotationMap = $annotationMap; + + ksort($orderedAnnotationMap, SORT_STRING); + + if ($orderedAnnotationMap === $annotationMap) { + continue; + } + + $lines = $docBlock->getLines(); + + foreach (array_reverse($annotations) as $annotation) { + array_splice( + $lines, + $annotation->getStart(), + $annotation->getEnd() - $annotation->getStart() + 1, + array_pop($orderedAnnotationMap) + ); + } + + $tokens[$index] = new Token([T_DOC_COMMENT, implode('', $lines)]); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $allowedValues = [ + 'author', + 'covers', + 'coversNothing', + 'dataProvider', + 'depends', + 'group', + 'internal', + 'method', + 'mixin', + 'property', + 'property-read', + 'property-write', + 'requires', + 'throws', + 'uses', + ]; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('annotations', 'List of annotations to order, e.g. `["covers"]`.')) + ->setAllowedTypes([ + 'array', + ]) + ->setAllowedValues([ + new AllowedValueSubset($allowedValues), + ]) + ->setNormalizer(static function (Options $options, $value): array { + $normalized = []; + + foreach ($value as $annotation) { + // since we will be using "strtolower" on the input annotations when building the sorting + // map we must match the type in lower case as well + $normalized[$annotation] = strtolower($annotation); + } + + return $normalized; + }) + ->setDefault([ + 'covers', + ]) + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderFixer.php new file mode 100644 index 00000000..4ae2c5f1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderFixer.php @@ -0,0 +1,208 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @author Graham Campbell + * @author Jakub Kwaśniewski + */ +final class PhpdocOrderFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @const string[] + * + * @TODO: 4.0 - change default to ['param', 'return', 'throws'] + */ + private const ORDER_DEFAULT = ['param', 'throws', 'return']; + + public function getDefinition(): FixerDefinitionInterface + { + $code = <<<'EOF' + self::ORDER_DEFAULT]), + new CodeSample($code, ['order' => ['param', 'return', 'throws']]), + new CodeSample($code, ['order' => ['param', 'custom', 'throws', 'return']]), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer, PhpdocSeparationFixer, PhpdocTrimFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocIndentFixer, PhpdocNoEmptyReturnFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return -2; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('order', 'Sequence in which annotations in PHPDoc should be ordered.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([static function ($order) { + if (\count($order) < 2) { + throw new InvalidOptionsException('The option "order" value is invalid. Minimum two tags are required.'); + } + + return true; + }]) + ->setDefault(self::ORDER_DEFAULT) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + // assuming annotations are already grouped by tags + $content = $token->getContent(); + + // sort annotations + $successors = $this->configuration['order']; + while (\count($successors) >= 3) { + $predecessor = array_shift($successors); + $content = $this->moveAnnotationsBefore($predecessor, $successors, $content); + } + + // we're parsing the content last time to make sure the internal + // state of the docblock is correct after the modifications + $predecessors = $this->configuration['order']; + $last = array_pop($predecessors); + $content = $this->moveAnnotationsAfter($last, $predecessors, $content); + + // persist the content at the end + $tokens[$index] = new Token([T_DOC_COMMENT, $content]); + } + } + + /** + * Move all given annotations in before given set of annotations. + * + * @param string $move Tag of annotations that should be moved + * @param string[] $before Tags of annotations that should moved annotations be placed before + */ + private function moveAnnotationsBefore(string $move, array $before, string $content): string + { + $doc = new DocBlock($content); + $toBeMoved = $doc->getAnnotationsOfType($move); + + // nothing to do if there are no annotations to be moved + if (0 === \count($toBeMoved)) { + return $content; + } + + $others = $doc->getAnnotationsOfType($before); + + if (0 === \count($others)) { + return $content; + } + + // get the index of the final line of the final toBoMoved annotation + $end = end($toBeMoved)->getEnd(); + + $line = $doc->getLine($end); + + // move stuff about if required + foreach ($others as $other) { + if ($other->getStart() < $end) { + // we're doing this to maintain the original line indices + $line->setContent($line->getContent().$other->getContent()); + $other->remove(); + } + } + + return $doc->getContent(); + } + + /** + * Move all given annotations after given set of annotations. + * + * @param string $move Tag of annotations that should be moved + * @param string[] $after Tags of annotations that should moved annotations be placed after + */ + private function moveAnnotationsAfter(string $move, array $after, string $content): string + { + $doc = new DocBlock($content); + $toBeMoved = $doc->getAnnotationsOfType($move); + + // nothing to do if there are no annotations to be moved + if (0 === \count($toBeMoved)) { + return $content; + } + + $others = $doc->getAnnotationsOfType($after); + + // nothing to do if there are no other annotations + if (0 === \count($others)) { + return $content; + } + + // get the index of the first line of the first toBeMoved annotation + $start = $toBeMoved[0]->getStart(); + $line = $doc->getLine($start); + + // move stuff about if required + foreach (array_reverse($others) as $other) { + if ($other->getEnd() > $start) { + // we're doing this to maintain the original line indices + $line->setContent($other->getContent().$line->getContent()); + $other->remove(); + } + } + + return $doc->getContent(); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocParamOrderFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocParamOrderFixer.php new file mode 100644 index 00000000..fb3f4124 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocParamOrderFixer.php @@ -0,0 +1,272 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Jonathan Gruber + */ +final class PhpdocParamOrderFixer extends AbstractFixer +{ + private const PARAM_TAG = 'param'; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return parent::getPriority(); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Orders all `@param` annotations in DocBlocks according to method signature.', + [ + new CodeSample( + ' $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + // Check for function / closure token + $nextFunctionToken = $tokens->getNextTokenOfKind($index, [[T_FUNCTION], [T_FN]]); + if (null === $nextFunctionToken) { + return; + } + + // Find start index of param block (opening parenthesis) + $paramBlockStart = $tokens->getNextTokenOfKind($index, ['(']); + if (null === $paramBlockStart) { + return; + } + + $doc = new DocBlock($tokens[$index]->getContent()); + $paramAnnotations = $doc->getAnnotationsOfType(self::PARAM_TAG); + + if ([] === $paramAnnotations) { + continue; + } + + $paramNames = $this->getFunctionParamNames($tokens, $paramBlockStart); + $doc = $this->rewriteDocBlock($doc, $paramNames, $paramAnnotations); + + $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); + } + } + + /** + * @return Token[] + */ + private function getFunctionParamNames(Tokens $tokens, int $paramBlockStart): array + { + $paramBlockEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $paramBlockStart); + + $paramNames = []; + for ( + $i = $tokens->getNextTokenOfKind($paramBlockStart, [[T_VARIABLE]]); + null !== $i && $i < $paramBlockEnd; + $i = $tokens->getNextTokenOfKind($i, [[T_VARIABLE]]) + ) { + $paramNames[] = $tokens[$i]; + } + + return $paramNames; + } + + /** + * Overwrite the param annotations in order. + * + * @param Token[] $paramNames + * @param Annotation[] $paramAnnotations + */ + private function rewriteDocBlock(DocBlock $doc, array $paramNames, array $paramAnnotations): DocBlock + { + $orderedAnnotations = $this->sortParamAnnotations($paramNames, $paramAnnotations); + $otherAnnotations = $this->getOtherAnnotationsBetweenParams($doc, $paramAnnotations); + + // Append annotations found between param ones + if ([] !== $otherAnnotations) { + array_push($orderedAnnotations, ...$otherAnnotations); + } + + // Overwrite all annotations between first and last @param tag in order + $paramsStart = reset($paramAnnotations)->getStart(); + $paramsEnd = end($paramAnnotations)->getEnd(); + + foreach ($doc->getAnnotations() as $annotation) { + if ($annotation->getStart() < $paramsStart || $annotation->getEnd() > $paramsEnd) { + continue; + } + + $annotation->remove(); + $doc + ->getLine($annotation->getStart()) + ->setContent(current($orderedAnnotations)) + ; + + next($orderedAnnotations); + } + + return $doc; + } + + /** + * Sort the param annotations according to the function parameters. + * + * @param Token[] $funcParamNames + * @param Annotation[] $paramAnnotations + * + * @return string[] + */ + private function sortParamAnnotations(array $funcParamNames, array $paramAnnotations): array + { + $validParams = []; + foreach ($funcParamNames as $paramName) { + $indices = $this->findParamAnnotationByIdentifier($paramAnnotations, $paramName->getContent()); + + // Found an exactly matching @param annotation + if (\is_array($indices)) { + foreach ($indices as $index) { + $validParams[$index] = $paramAnnotations[$index]->getContent(); + } + } + } + + // Detect superfluous annotations + /** @var Annotation[] $invalidParams */ + $invalidParams = array_diff_key($paramAnnotations, $validParams); + $invalidParams = array_values($invalidParams); + + // Append invalid parameters to the (ordered) valid ones + $orderedParams = array_values($validParams); + foreach ($invalidParams as $params) { + $orderedParams[] = $params->getContent(); + } + + return $orderedParams; + } + + /** + * Fetch all annotations except the param ones. + * + * @param Annotation[] $paramAnnotations + * + * @return string[] + */ + private function getOtherAnnotationsBetweenParams(DocBlock $doc, array $paramAnnotations): array + { + if (0 === \count($paramAnnotations)) { + return []; + } + + $paramsStart = reset($paramAnnotations)->getStart(); + $paramsEnd = end($paramAnnotations)->getEnd(); + + $otherAnnotations = []; + foreach ($doc->getAnnotations() as $annotation) { + if ($annotation->getStart() < $paramsStart || $annotation->getEnd() > $paramsEnd) { + continue; + } + + if (self::PARAM_TAG !== $annotation->getTag()->getName()) { + $otherAnnotations[] = $annotation->getContent(); + } + } + + return $otherAnnotations; + } + + /** + * Return the indices of the lines of a specific parameter annotation. + * + * @param Annotation[] $paramAnnotations + * + * @return null|array + */ + private function findParamAnnotationByIdentifier(array $paramAnnotations, string $identifier): ?array + { + $blockLevel = 0; + $blockMatch = false; + $blockIndices = []; + + $paramRegex = '/\*\s*@param\s*(?:|'.TypeExpression::REGEX_TYPES.'\s*)&?(?=\$\b)'.preg_quote($identifier).'\b/'; + + foreach ($paramAnnotations as $i => $param) { + $blockStart = Preg::match('/\s*{\s*/', $param->getContent()); + $blockEndMatches = Preg::matchAll('/}[\*\s\n]*/', $param->getContent()); + + if (0 === $blockLevel && Preg::match($paramRegex, $param->getContent())) { + if ($blockStart) { + $blockMatch = true; // Start of a nested block + } else { + return [$i]; // Top level match + } + } + + if ($blockStart) { + ++$blockLevel; + } + + if (0 !== $blockEndMatches) { + $blockLevel -= $blockEndMatches; + } + + if ($blockMatch) { + $blockIndices[] = $i; + if (0 === $blockLevel) { + return $blockIndices; + } + } + } + + return null; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php new file mode 100644 index 00000000..f672e1ee --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php @@ -0,0 +1,220 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use Symfony\Component\OptionsResolver\Options; + +final class PhpdocReturnSelfReferenceFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var string[] + */ + private static array $toTypes = [ + '$this', + 'static', + 'self', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The type of `@return` annotations of methods returning a reference to itself must the configured one.', + [ + new CodeSample( + ' ['this' => 'self']] + ), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return \count($tokens) > 10 && $tokens->isAllTokenKindsFound([T_DOC_COMMENT, T_FUNCTION]) && $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + /** + * {@inheritdoc} + * + * Must run before NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 10; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + foreach ($tokensAnalyzer->getClassyElements() as $index => $element) { + if ('method' === $element['type']) { + $this->fixMethod($tokens, $index); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $default = [ + 'this' => '$this', + '@this' => '$this', + '$self' => 'self', + '@self' => 'self', + '$static' => 'static', + '@static' => 'static', + ]; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('replacements', 'Mapping between replaced return types with new ones.')) + ->setAllowedTypes(['array']) + ->setNormalizer(static function (Options $options, array $value) use ($default): array { + $normalizedValue = []; + + foreach ($value as $from => $to) { + if (\is_string($from)) { + $from = strtolower($from); + } + + if (!isset($default[$from])) { + throw new InvalidOptionsException(sprintf( + 'Unknown key "%s", expected any of %s.', + \gettype($from).'#'.$from, + Utils::naturalLanguageJoin(array_keys($default)) + )); + } + + if (!\in_array($to, self::$toTypes, true)) { + throw new InvalidOptionsException(sprintf( + 'Unknown value "%s", expected any of %s.', + \is_object($to) ? \get_class($to) : \gettype($to).(\is_resource($to) ? '' : '#'.$to), + Utils::naturalLanguageJoin(self::$toTypes) + )); + } + + $normalizedValue[$from] = $to; + } + + return $normalizedValue; + }) + ->setDefault($default) + ->getOption(), + ]); + } + + private function fixMethod(Tokens $tokens, int $index): void + { + static $methodModifiers = [T_STATIC, T_FINAL, T_ABSTRACT, T_PRIVATE, T_PROTECTED, T_PUBLIC]; + + // find PHPDoc of method (if any) + while (true) { + $tokenIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$tokenIndex]->isGivenKind($methodModifiers)) { + break; + } + + $index = $tokenIndex; + } + + $docIndex = $tokens->getPrevNonWhitespace($index); + if (!$tokens[$docIndex]->isGivenKind(T_DOC_COMMENT)) { + return; + } + + // find @return + $docBlock = new DocBlock($tokens[$docIndex]->getContent()); + $returnsBlock = $docBlock->getAnnotationsOfType('return'); + + if (0 === \count($returnsBlock)) { + return; // no return annotation found + } + + $returnsBlock = $returnsBlock[0]; + $types = $returnsBlock->getTypes(); + + if (0 === \count($types)) { + return; // no return type(s) found + } + + $newTypes = []; + + foreach ($types as $type) { + $newTypes[] = $this->configuration['replacements'][strtolower($type)] ?? $type; + } + + if ($types === $newTypes) { + return; + } + + $returnsBlock->setTypes($newTypes); + $tokens[$docIndex] = new Token([T_DOC_COMMENT, $docBlock->getContent()]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocScalarFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocScalarFixer.php new file mode 100644 index 00000000..df397ef0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocScalarFixer.php @@ -0,0 +1,122 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractPhpdocTypesFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @author Graham Campbell + */ +final class PhpdocScalarFixer extends AbstractPhpdocTypesFixer implements ConfigurableFixerInterface +{ + /** + * The types to fix. + * + * @var array + */ + private static array $types = [ + 'boolean' => 'bool', + 'callback' => 'callable', + 'double' => 'float', + 'integer' => 'int', + 'real' => 'float', + 'str' => 'string', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Scalar types should always be written in the same form. `int` not `integer`, `bool` not `boolean`, `float` not `real` or `double`.', + [ + new CodeSample(' ['boolean']] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. + * Must run after PhpdocTypesFixer. + */ + public function getPriority(): int + { + /* + * Should be run before all other docblock fixers apart from the + * phpdoc_to_comment and phpdoc_indent fixer to make sure all fixers + * apply correct indentation to new code they add. This should run + * before alignment of params is done since this fixer might change + * the type and thereby un-aligning the params. We also must run after + * the phpdoc_types_fixer because it can convert types to things that + * we can fix. + */ + return 15; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $types = array_keys(self::$types); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('types', 'A list of types to fix.')) + ->setAllowedValues([new AllowedValueSubset($types)]) + ->setDefault($types) + ->getOption(), + ]); + } + + protected function normalize(string $type): string + { + if (\in_array($type, $this->configuration['types'], true)) { + return self::$types[$type]; + } + + return $type; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSeparationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSeparationFixer.php new file mode 100644 index 00000000..03275367 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSeparationFixer.php @@ -0,0 +1,320 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @author Graham Campbell + * @author Jakub Kwaśniewski + */ +final class PhpdocSeparationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @internal + * + * @var string[][] + */ + public const OPTION_GROUPS_DEFAULT = [ + ['author', 'copyright', 'license'], + ['category', 'package', 'subpackage'], + ['property', 'property-read', 'property-write'], + ['deprecated', 'link', 'see', 'since'], + ]; + + /** + * @var string[][] + */ + private array $groups; + + public function getDefinition(): FixerDefinitionInterface + { + $code = <<<'EOF' + [ + ['deprecated', 'link', 'see', 'since'], + ['author', 'copyright', 'license'], + ['category', 'package', 'subpackage'], + ['property', 'property-read', 'property-write'], + ['param', 'return'], + ]]), + new CodeSample($code, ['groups' => [ + ['author', 'throws', 'custom'], + ['return', 'param'], + ]]), + new CodeSample( + <<<'EOF' + [['ORM\*'], ['Assert\*']]], + ), + new CodeSample($code, ['skip_unlisted_annotations' => true]), + ], + ); + } + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->groups = $this->configuration['groups']; + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, PhpUnitInternalClassFixer, PhpUnitSizeClassFixer, PhpUnitTestClassRequiresCoversFixer, PhpdocIndentFixer, PhpdocNoAccessFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocOrderFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return -3; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $this->fixDescription($doc); + $this->fixAnnotations($doc); + + $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $allowTagToBelongToOnlyOneGroup = static function ($groups) { + $tags = []; + foreach ($groups as $groupIndex => $group) { + foreach ($group as $member) { + if (isset($tags[$member])) { + if ($groupIndex === $tags[$member]) { + throw new InvalidOptionsException( + 'The option "groups" value is invalid. '. + 'The "'.$member.'" tag is specified more than once.' + ); + } + + throw new InvalidOptionsException( + 'The option "groups" value is invalid. '. + 'The "'.$member.'" tag belongs to more than one group.' + ); + } + $tags[$member] = $groupIndex; + } + } + + return true; + }; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('groups', 'Sets of annotation types to be grouped together. Use `*` to match any tag character.')) + ->setAllowedTypes(['string[][]']) + ->setDefault(self::OPTION_GROUPS_DEFAULT) + ->setAllowedValues([$allowTagToBelongToOnlyOneGroup]) + ->getOption(), + (new FixerOptionBuilder('skip_unlisted_annotations', 'Whether to skip annotations that are not listed in any group.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) // @TODO 4.0: set to `true`. + ->getOption(), + ]); + } + + /** + * Make sure the description is separated from the annotations. + */ + private function fixDescription(DocBlock $doc): void + { + foreach ($doc->getLines() as $index => $line) { + if ($line->containsATag()) { + break; + } + + if ($line->containsUsefulContent()) { + $next = $doc->getLine($index + 1); + + if (null !== $next && $next->containsATag()) { + $line->addBlank(); + + break; + } + } + } + } + + /** + * Make sure the annotations are correctly separated. + */ + private function fixAnnotations(DocBlock $doc): void + { + foreach ($doc->getAnnotations() as $index => $annotation) { + $next = $doc->getAnnotation($index + 1); + + if (null === $next) { + break; + } + + $shouldBeTogether = $this->shouldBeTogether($annotation, $next, $this->groups); + + if (true === $shouldBeTogether) { + $this->ensureAreTogether($doc, $annotation, $next); + } elseif (false === $shouldBeTogether || !$this->configuration['skip_unlisted_annotations']) { + $this->ensureAreSeparate($doc, $annotation, $next); + } + } + } + + /** + * Force the given annotations to immediately follow each other. + */ + private function ensureAreTogether(DocBlock $doc, Annotation $first, Annotation $second): void + { + $pos = $first->getEnd(); + $final = $second->getStart(); + + for (++$pos; $pos < $final; ++$pos) { + $doc->getLine($pos)->remove(); + } + } + + /** + * Force the given annotations to have one empty line between each other. + */ + private function ensureAreSeparate(DocBlock $doc, Annotation $first, Annotation $second): void + { + $pos = $first->getEnd(); + $final = $second->getStart() - 1; + + // check if we need to add a line, or need to remove one or more lines + if ($pos === $final) { + $doc->getLine($pos)->addBlank(); + + return; + } + + for (++$pos; $pos < $final; ++$pos) { + $doc->getLine($pos)->remove(); + } + } + + /** + * @param list> $groups + */ + private function shouldBeTogether(Annotation $first, Annotation $second, array $groups): ?bool + { + $firstName = $this->tagName($first); + $secondName = $this->tagName($second); + + // A tag could not be read. + if (null === $firstName || null === $secondName) { + return null; + } + + if ($firstName === $secondName) { + return true; + } + + foreach ($groups as $group) { + $firstTagIsInGroup = $this->isInGroup($firstName, $group); + $secondTagIsInGroup = $this->isInGroup($secondName, $group); + + if ($firstTagIsInGroup) { + return $secondTagIsInGroup; + } + + if ($secondTagIsInGroup) { + return false; + } + } + + return null; + } + + private function tagName(Annotation $annotation): ?string + { + Preg::match('/@([a-zA-Z0-9_\\\\-]+(?=\s|$|\())/', $annotation->getContent(), $matches); + + return $matches[1] ?? null; + } + + /** + * @param list $group + */ + private function isInGroup(string $tag, array $group): bool + { + foreach ($group as $tagInGroup) { + $tagInGroup = str_replace('*', '\*', $tagInGroup); + $tagInGroup = preg_quote($tagInGroup, '/'); + $tagInGroup = str_replace('\\\\\*', '.*?', $tagInGroup); + + if (Preg::match("/^{$tagInGroup}$/", $tag)) { + return true; + } + } + + return false; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.php new file mode 100644 index 00000000..9c2bda1d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for part of rule defined in PSR5 ¶7.22. + */ +final class PhpdocSingleLineVarSpacingFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Single line `@var` PHPDoc should have proper spacing.', + [new CodeSample("isAnyTokenKindsFound([T_COMMENT, T_DOC_COMMENT]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + /** @var Token $token */ + foreach ($tokens as $index => $token) { + if (!$token->isComment()) { + continue; + } + + $content = $token->getContent(); + $fixedContent = $this->fixTokenContent($content); + + if ($content !== $fixedContent) { + $tokens[$index] = new Token([T_DOC_COMMENT, $fixedContent]); + } + } + } + + private function fixTokenContent(string $content): string + { + return Preg::replaceCallback( + '#^/\*\*\h*@var\h+(\S+)\h*(\$\S+)?\h*([^\n]*)\*/$#', + static function (array $matches) { + $content = '/** @var'; + + for ($i = 1, $m = \count($matches); $i < $m; ++$i) { + if ('' !== $matches[$i]) { + $content .= ' '.$matches[$i]; + } + } + + return rtrim($content).' */'; + }, + $content + ); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSummaryFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSummaryFixer.php new file mode 100644 index 00000000..65406b37 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSummaryFixer.php @@ -0,0 +1,99 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\ShortDescription; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + */ +final class PhpdocSummaryFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPDoc summary should end in either a full stop, exclamation mark, or question mark.', + [new CodeSample('isTokenKindFound(T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $end = (new ShortDescription($doc))->getEnd(); + + if (null !== $end) { + $line = $doc->getLine($end); + $content = rtrim($line->getContent()); + + if ( + // final line of Description is NOT properly formatted + !$this->isCorrectlyFormatted($content) + // and first line of Description, if different than final line, does NOT indicate a list + && (1 === $end || ($doc->isMultiLine() && ':' !== substr(rtrim($doc->getLine(1)->getContent()), -1))) + ) { + $line->setContent($content.'.'.$this->whitespacesConfig->getLineEnding()); + $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); + } + } + } + } + + /** + * Is the last line of the short description correctly formatted? + */ + private function isCorrectlyFormatted(string $content): bool + { + if (false !== stripos($content, '{@inheritdoc}')) { + return true; + } + + return $content !== rtrim($content, '.:。!?¡¿!?'); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagCasingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagCasingFixer.php new file mode 100644 index 00000000..cdeb5315 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagCasingFixer.php @@ -0,0 +1,97 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\ConfigurationException\InvalidConfigurationException; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; + +final class PhpdocTagCasingFixer extends AbstractProxyFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Fixes casing of PHPDoc tags.', + [ + new CodeSample(" ['foo'], + ]), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return parent::getPriority(); + } + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $replacements = []; + foreach ($this->configuration['tags'] as $tag) { + $replacements[$tag] = $tag; + } + + /** @var GeneralPhpdocTagRenameFixer $generalPhpdocTagRenameFixer */ + $generalPhpdocTagRenameFixer = $this->proxyFixers['general_phpdoc_tag_rename']; + + try { + $generalPhpdocTagRenameFixer->configure([ + 'fix_annotation' => true, + 'fix_inline' => true, + 'replacements' => $replacements, + 'case_sensitive' => false, + ]); + } catch (InvalidConfigurationException $exception) { + throw new InvalidFixerConfigurationException( + $this->getName(), + Preg::replace('/^\[.+?\] /', '', $exception->getMessage()), + $exception + ); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('tags', 'List of tags to fix with their expected casing.')) + ->setAllowedTypes(['array']) + ->setDefault(['inheritDoc']) + ->getOption(), + ]); + } + + protected function createProxyFixers(): array + { + return [new GeneralPhpdocTagRenameFixer()]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagTypeFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagTypeFixer.php new file mode 100644 index 00000000..947b526c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagTypeFixer.php @@ -0,0 +1,200 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use Symfony\Component\OptionsResolver\Options; + +final class PhpdocTagTypeFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const TAG_REGEX = '/^(?: + (? + (?:@(?.+?)(?:\s.+)?) + ) + | + {(? + (?:@(?.+?)(?:\s.+)?) + )} + )$/x'; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Forces PHPDoc tags to be either regular annotations or inline.', + [ + new CodeSample( + " ['inheritdoc' => 'inline']] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if (0 === \count($this->configuration['tags'])) { + return; + } + + $regularExpression = sprintf( + '/({?@(?:%s).*?(?:(?=\s\*\/)|(?=\n)}?))/i', + implode('|', array_map( + static fn (string $tag): string => preg_quote($tag, '/'), + array_keys($this->configuration['tags']) + )) + ); + + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $parts = Preg::split( + $regularExpression, + $token->getContent(), + -1, + PREG_SPLIT_DELIM_CAPTURE + ); + + for ($i = 1, $max = \count($parts) - 1; $i < $max; $i += 2) { + if (!Preg::match(self::TAG_REGEX, $parts[$i], $matches)) { + continue; + } + + if ('' !== $matches['tag']) { + $tag = $matches['tag']; + $tagName = $matches['tag_name']; + } else { + $tag = $matches['inlined_tag']; + $tagName = $matches['inlined_tag_name']; + } + + $tagName = strtolower($tagName); + if (!isset($this->configuration['tags'][$tagName])) { + continue; + } + + if ('inline' === $this->configuration['tags'][$tagName]) { + $parts[$i] = '{'.$tag.'}'; + + continue; + } + + if (!$this->tagIsSurroundedByText($parts, $i)) { + $parts[$i] = $tag; + } + } + + $tokens[$index] = new Token([T_DOC_COMMENT, implode('', $parts)]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('tags', 'The list of tags to fix.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([static function (array $value): bool { + foreach ($value as $type) { + if (!\in_array($type, ['annotation', 'inline'], true)) { + throw new InvalidOptionsException("Unknown tag type \"{$type}\"."); + } + } + + return true; + }]) + ->setDefault([ + 'api' => 'annotation', + 'author' => 'annotation', + 'copyright' => 'annotation', + 'deprecated' => 'annotation', + 'example' => 'annotation', + 'global' => 'annotation', + 'inheritDoc' => 'annotation', + 'internal' => 'annotation', + 'license' => 'annotation', + 'method' => 'annotation', + 'package' => 'annotation', + 'param' => 'annotation', + 'property' => 'annotation', + 'return' => 'annotation', + 'see' => 'annotation', + 'since' => 'annotation', + 'throws' => 'annotation', + 'todo' => 'annotation', + 'uses' => 'annotation', + 'var' => 'annotation', + 'version' => 'annotation', + ]) + ->setNormalizer(static function (Options $options, $value): array { + $normalized = []; + + foreach ($value as $tag => $type) { + $normalized[strtolower($tag)] = $type; + } + + return $normalized; + }) + ->getOption(), + ]); + } + + /** + * @param list $parts + */ + private function tagIsSurroundedByText(array $parts, int $index): bool + { + return + Preg::match('/(^|\R)\h*[^@\s]\N*/', $this->cleanComment($parts[$index - 1])) + || Preg::match('/^.*?\R\s*[^@\s]/', $this->cleanComment($parts[$index + 1])); + } + + private function cleanComment(string $comment): string + { + $comment = Preg::replace('/^\/\*\*|\*\/$/', '', $comment); + + return Preg::replace('/(\R)(\h*\*)?\h*/', '$1', $comment); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocToCommentFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocToCommentFixer.php new file mode 100644 index 00000000..402ca5fc --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocToCommentFixer.php @@ -0,0 +1,145 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\CommentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Ceeram + * @author Dariusz Rumiński + */ +final class PhpdocToCommentFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var string[] + */ + private array $ignoredTags = []; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + /** + * {@inheritdoc} + * + * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyCommentFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocAnnotationWithoutDotFixer, PhpdocIndentFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer, SingleLineCommentSpacingFixer, SingleLineCommentStyleFixer. + * Must run after CommentToPhpdocFixer. + */ + public function getPriority(): int + { + /* + * Should be run before all other docblock fixers so that these fixers + * don't touch doc comments which are meant to be converted to regular + * comments. + */ + return 25; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Docblocks should only be used on structural elements.', + [ + new CodeSample( + ' $sqlite) { + $sqlite->open($path); +} +' + ), + new CodeSample( + ' $sqlite) { + $sqlite->open($path); +} + +/** @todo This should be a PHPDoc as the tag is on "ignored_tags" list */ +foreach($connections as $key => $sqlite) { + $sqlite->open($path); +} +', + ['ignored_tags' => ['todo']] + ), + ] + ); + } + + public function configure(array $configuration = null): void + { + parent::configure($configuration); + + $this->ignoredTags = array_map( + static fn (string $tag): string => strtolower($tag), + $this->configuration['ignored_tags'] + ); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('ignored_tags', 'List of ignored tags (matched case insensitively).')) + ->setAllowedTypes(['array']) + ->setDefault([]) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $commentsAnalyzer = new CommentsAnalyzer(); + + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + if ($commentsAnalyzer->isHeaderComment($tokens, $index)) { + continue; + } + + if ($commentsAnalyzer->isBeforeStructuralElement($tokens, $index)) { + continue; + } + + if (0 < Preg::matchAll('~\@([a-zA-Z0-9_\\\\-]+)\b~', $token->getContent(), $matches)) { + foreach ($matches[1] as $match) { + if (\in_array(strtolower($match), $this->ignoredTags, true)) { + continue 2; + } + } + } + + $tokens[$index] = new Token([T_COMMENT, '/*'.ltrim($token->getContent(), '/*')]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php new file mode 100644 index 00000000..33a4a037 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php @@ -0,0 +1,188 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\DocBlock\ShortDescription; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Nobu Funaki + * @author Dariusz Rumiński + */ +final class PhpdocTrimConsecutiveBlankLineSeparationFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes extra blank lines after summary and after description in PHPDoc.', + [ + new CodeSample( + 'isTokenKindFound(T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $summaryEnd = (new ShortDescription($doc))->getEnd(); + + if (null !== $summaryEnd) { + $this->fixSummary($doc, $summaryEnd); + $this->fixDescription($doc, $summaryEnd); + } + + $this->fixAllTheRest($doc); + + $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); + } + } + + private function fixSummary(DocBlock $doc, int $summaryEnd): void + { + $nonBlankLineAfterSummary = $this->findNonBlankLine($doc, $summaryEnd); + + $this->removeExtraBlankLinesBetween($doc, $summaryEnd, $nonBlankLineAfterSummary); + } + + private function fixDescription(DocBlock $doc, int $summaryEnd): void + { + $annotationStart = $this->findFirstAnnotationOrEnd($doc); + + // assuming the end of the Description appears before the first Annotation + $descriptionEnd = $this->reverseFindLastUsefulContent($doc, $annotationStart); + + if (null === $descriptionEnd || $summaryEnd === $descriptionEnd) { + return; // no Description + } + + if ($annotationStart === \count($doc->getLines()) - 1) { + return; // no content after Description + } + + $this->removeExtraBlankLinesBetween($doc, $descriptionEnd, $annotationStart); + } + + private function fixAllTheRest(DocBlock $doc): void + { + $annotationStart = $this->findFirstAnnotationOrEnd($doc); + $lastLine = $this->reverseFindLastUsefulContent($doc, \count($doc->getLines()) - 1); + + if (null !== $lastLine && $annotationStart !== $lastLine) { + $this->removeExtraBlankLinesBetween($doc, $annotationStart, $lastLine); + } + } + + private function removeExtraBlankLinesBetween(DocBlock $doc, int $from, int $to): void + { + for ($index = $from + 1; $index < $to; ++$index) { + $line = $doc->getLine($index); + $next = $doc->getLine($index + 1); + $this->removeExtraBlankLine($line, $next); + } + } + + private function removeExtraBlankLine(Line $current, Line $next): void + { + if (!$current->isTheEnd() && !$current->containsUsefulContent() + && !$next->isTheEnd() && !$next->containsUsefulContent()) { + $current->remove(); + } + } + + private function findNonBlankLine(DocBlock $doc, int $after): ?int + { + foreach ($doc->getLines() as $index => $line) { + if ($index <= $after) { + continue; + } + + if ($line->containsATag() || $line->containsUsefulContent() || $line->isTheEnd()) { + return $index; + } + } + + return null; + } + + private function findFirstAnnotationOrEnd(DocBlock $doc): int + { + $index = null; + foreach ($doc->getLines() as $index => $line) { + if ($line->containsATag()) { + return $index; + } + } + + return $index; // no Annotation, return the last line + } + + private function reverseFindLastUsefulContent(DocBlock $doc, int $from): ?int + { + for ($index = $from - 1; $index >= 0; --$index) { + if ($doc->getLine($index)->containsUsefulContent()) { + return $index; + } + } + + return null; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimFixer.php new file mode 100644 index 00000000..c472d0d9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimFixer.php @@ -0,0 +1,115 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + */ +final class PhpdocTrimFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPDoc should start and end with content, excluding the very first and last line of the docblocks.', + [new CodeSample('isTokenKindFound(T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $content = $token->getContent(); + $content = $this->fixStart($content); + // we need re-parse the docblock after fixing the start before + // fixing the end in order for the lines to be correctly indexed + $content = $this->fixEnd($content); + $tokens[$index] = new Token([T_DOC_COMMENT, $content]); + } + } + + /** + * Make sure the first useful line starts immediately after the first line. + */ + private function fixStart(string $content): string + { + return Preg::replace( + '~ + (^/\*\*) # DocComment begin + (?: + \R\h*(?:\*\h*)? # lines without useful content + (?!\R\h*\*/) # not followed by a DocComment end + )+ + (\R\h*(?:\*\h*)?\S) # first line with useful content + ~x', + '$1$2', + $content + ); + } + + /** + * Make sure the last useful line is immediately before the final line. + */ + private function fixEnd(string $content): string + { + return Preg::replace( + '~ + (\R\h*(?:\*\h*)?\S.*?) # last line with useful content + (?: + (? + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractPhpdocTypesFixer; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; + +/** + * @author Graham Campbell + * @author Dariusz Rumiński + */ +final class PhpdocTypesFixer extends AbstractPhpdocTypesFixer implements ConfigurableFixerInterface +{ + /** + * Available types, grouped. + * + * @var array + */ + private const POSSIBLE_TYPES = [ + 'simple' => [ + 'array', + 'bool', + 'callable', + 'float', + 'int', + 'iterable', + 'null', + 'object', + 'string', + ], + 'alias' => [ + 'boolean', + 'double', + 'integer', + ], + 'meta' => [ + '$this', + 'false', + 'mixed', + 'parent', + 'resource', + 'scalar', + 'self', + 'static', + 'true', + 'void', + ], + ]; + + /** @var array */ + private array $typesSetToFix; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $typesToFix = array_merge(...array_map(static fn (string $group): array => self::POSSIBLE_TYPES[$group], $this->configuration['groups'])); + + $this->typesSetToFix = array_combine($typesToFix, array_fill(0, \count($typesToFix), true)); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The correct case must be used for standard PHP types in PHPDoc.', + [ + new CodeSample( + ' ['simple', 'alias']] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocScalarFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. + * Must run after PhpdocIndentFixer. + */ + public function getPriority(): int + { + /* + * Should be run before all other docblock fixers apart from the + * phpdoc_to_comment and phpdoc_indent fixer to make sure all fixers + * apply correct indentation to new code they add. This should run + * before alignment of params is done since this fixer might change + * the type and thereby un-aligning the params. We also must run before + * the phpdoc_scalar_fixer so that it can make changes after us. + */ + return 16; + } + + protected function normalize(string $type): string + { + $typeExpression = new TypeExpression($type, null, []); + + $typeExpression->walkTypes(function (TypeExpression $type): void { + if (!$type->isUnionType()) { + $value = $type->toString(); + $valueLower = strtolower($value); + if (isset($this->typesSetToFix[$valueLower])) { + $value = $valueLower; + } + + // normalize shape/callable/generic identifiers too + // TODO parse them as inner types and this will be not needed then + $value = Preg::replaceCallback( + '/^(\??\s*)([^()[\]{}<>\'"]+)(?])/', + fn ($matches) => $matches[1].$this->normalize($matches[2]).$matches[3], + $value + ); + + // TODO TypeExpression should be immutable and walkTypes method should be changed to mapTypes method + \Closure::bind(static function () use ($type, $value): void { + $type->value = $value; + }, null, TypeExpression::class)(); + } + }); + + return $typeExpression->toString(); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $possibleGroups = array_keys(self::POSSIBLE_TYPES); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('groups', 'Type groups to fix.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset($possibleGroups)]) + ->setDefault($possibleGroups) + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php new file mode 100644 index 00000000..7cd26008 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php @@ -0,0 +1,200 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class PhpdocTypesOrderFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Sorts PHPDoc types.', + [ + new CodeSample( + ' 'always_last'] + ), + new CodeSample( + ' 'alpha'] + ), + new CodeSample( + ' 'alpha', + 'null_adjustment' => 'always_last', + ] + ), + new CodeSample( + ' 'alpha', + 'null_adjustment' => 'none', + ] + ), + new CodeSample( + ' true] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_DOC_COMMENT); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('sort_algorithm', 'The sorting algorithm to apply.')) + ->setAllowedValues(['alpha', 'none']) + ->setDefault('alpha') + ->getOption(), + (new FixerOptionBuilder('null_adjustment', 'Forces the position of `null` (overrides `sort_algorithm`).')) + ->setAllowedValues(['always_first', 'always_last', 'none']) + ->setDefault('always_first') + ->getOption(), + (new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $annotations = $doc->getAnnotationsOfType(Annotation::getTagsWithTypes()); + + if (0 === \count($annotations)) { + continue; + } + + foreach ($annotations as $annotation) { + // fix main types + if (null !== $annotation->getTypeExpression()) { + $annotation->setTypes( + $this->sortTypes( + $annotation->getTypeExpression() + ) + ); + } + + // fix @method parameters types + $line = $doc->getLine($annotation->getStart()); + $line->setContent(Preg::replaceCallback('/@method\s+'.TypeExpression::REGEX_TYPES.'\s+\K(?&callable)/', function (array $matches) { + $typeExpression = new TypeExpression($matches[0], null, []); + + return implode('|', $this->sortTypes($typeExpression)); + }, $line->getContent())); + } + + $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); + } + } + + /** + * @return string[] + */ + private function sortTypes(TypeExpression $typeExpression): array + { + $normalizeType = static fn (string $type): string => Preg::replace('/^\\??\\\?/', '', $type); + + $typeExpression->sortTypes( + function (TypeExpression $a, TypeExpression $b) use ($normalizeType): int { + $a = $normalizeType($a->toString()); + $b = $normalizeType($b->toString()); + $lowerCaseA = strtolower($a); + $lowerCaseB = strtolower($b); + + if ('none' !== $this->configuration['null_adjustment']) { + if ('null' === $lowerCaseA && 'null' !== $lowerCaseB) { + return 'always_last' === $this->configuration['null_adjustment'] ? 1 : -1; + } + if ('null' !== $lowerCaseA && 'null' === $lowerCaseB) { + return 'always_last' === $this->configuration['null_adjustment'] ? -1 : 1; + } + } + + if ('alpha' === $this->configuration['sort_algorithm']) { + return $this->configuration['case_sensitive'] ? $a <=> $b : strcasecmp($a, $b); + } + + return 0; + } + ); + + return $typeExpression->getTypes(); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php new file mode 100644 index 00000000..400f8dd7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php @@ -0,0 +1,81 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + */ +final class PhpdocVarAnnotationCorrectOrderFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + '`@var` and `@type` annotations must have type and name in the correct order.', + [new CodeSample('isTokenKindFound(T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + if (false === stripos($token->getContent(), '@var') && false === stripos($token->getContent(), '@type')) { + continue; + } + + $newContent = Preg::replace( + '/(@(?:type|var)\s*)(\$\S+)(\h+)([^\$](?:[^<\s]|<[^>]*>)*)(\s|\*)/i', + '$1$4$3$2$5', + $token->getContent() + ); + + if ($newContent === $token->getContent()) { + continue; + } + + $tokens[$index] = new Token([$token->getId(), $newContent]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.php new file mode 100644 index 00000000..f42b2d9f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.php @@ -0,0 +1,152 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + * @author Dave van der Brugge + */ +final class PhpdocVarWithoutNameFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + '`@var` and `@type` annotations of classy properties should not contain the name.', + [new CodeSample('isTokenKindFound(T_DOC_COMMENT) && $tokens->isAnyTokenKindsFound([T_CLASS, T_TRAIT]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if (null === $nextIndex) { + continue; + } + + // For people writing "static public $foo" instead of "public static $foo" + if ($tokens[$nextIndex]->isGivenKind(T_STATIC)) { + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + } + + // We want only doc blocks that are for properties and thus have specified access modifiers next + $propertyModifierKinds = [T_PRIVATE, T_PROTECTED, T_PUBLIC, T_VAR]; + + if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required + $propertyModifierKinds[] = T_READONLY; + } + + if (!$tokens[$nextIndex]->isGivenKind($propertyModifierKinds)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + + $firstLevelLines = $this->getFirstLevelLines($doc); + $annotations = $doc->getAnnotationsOfType(['type', 'var']); + + foreach ($annotations as $annotation) { + if (isset($firstLevelLines[$annotation->getStart()])) { + $this->fixLine($firstLevelLines[$annotation->getStart()]); + } + } + + $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]); + } + } + + private function fixLine(Line $line): void + { + Preg::matchAll('/ \$'.TypeExpression::REGEX_IDENTIFIER.'(?getContent(), $matches); + + if (isset($matches[0])) { + foreach ($matches[0] as $match) { + $line->setContent(str_replace($match, '', $line->getContent())); + } + } + } + + /** + * @return Line[] + */ + private function getFirstLevelLines(DocBlock $docBlock): array + { + $nested = 0; + $lines = $docBlock->getLines(); + + foreach ($lines as $index => $line) { + $content = $line->getContent(); + + if (Preg::match('/\s*\*\s*}$/', $content)) { + --$nested; + } + + if ($nested > 0) { + unset($lines[$index]); + } + + if (Preg::match('/\s\{$/', $content)) { + ++$nested; + } + } + + return $lines; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/NoUselessReturnFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/NoUselessReturnFixer.php new file mode 100644 index 00000000..aba3072c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/NoUselessReturnFixer.php @@ -0,0 +1,103 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ReturnNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +final class NoUselessReturnFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAllTokenKindsFound([T_FUNCTION, T_RETURN]); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be an empty `return` statement at the end of a function.', + [ + new CodeSample( + ' $token) { + if (!$token->isGivenKind(T_FUNCTION)) { + continue; + } + + $index = $tokens->getNextTokenOfKind($index, [';', '{']); + if ($tokens[$index]->equals('{')) { + $this->fixFunction($tokens, $index, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index)); + } + } + } + + /** + * @param int $start Token index of the opening brace token of the function + * @param int $end Token index of the closing brace token of the function + */ + private function fixFunction(Tokens $tokens, int $start, int $end): void + { + for ($index = $end; $index > $start; --$index) { + if (!$tokens[$index]->isGivenKind(T_RETURN)) { + continue; + } + + $nextAt = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$nextAt]->equals(';')) { + continue; + } + + if ($tokens->getNextMeaningfulToken($nextAt) !== $end) { + continue; + } + + $previous = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$previous]->equalsAny([[T_ELSE], ')'])) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($nextAt); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/ReturnAssignmentFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/ReturnAssignmentFixer.php new file mode 100644 index 00000000..1e883382 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/ReturnAssignmentFixer.php @@ -0,0 +1,527 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ReturnNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +final class ReturnAssignmentFixer extends AbstractFixer +{ + private TokensAnalyzer $tokensAnalyzer; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Local, dynamic and directly referenced variables should not be assigned and directly returned by a function or method.', + [new CodeSample("isAllTokenKindsFound([T_FUNCTION, T_RETURN, T_VARIABLE]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokenCount = \count($tokens); + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($index = 1; $index < $tokenCount; ++$index) { + if (!$tokens[$index]->isGivenKind(T_FUNCTION)) { + continue; + } + + $next = $tokens->getNextMeaningfulToken($index); + if ($tokens[$next]->isGivenKind(CT::T_RETURN_REF)) { + continue; + } + + $functionOpenIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + if ($tokens[$functionOpenIndex]->equals(';')) { // abstract function + $index = $functionOpenIndex - 1; + + continue; + } + + $functionCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $functionOpenIndex); + $totalTokensAdded = 0; + + do { + $tokensAdded = $this->fixFunction( + $tokens, + $index, + $functionOpenIndex, + $functionCloseIndex + ); + + $functionCloseIndex += $tokensAdded; + $totalTokensAdded += $tokensAdded; + } while ($tokensAdded > 0); + + $index = $functionCloseIndex; + $tokenCount += $totalTokensAdded; + } + } + + /** + * @param int $functionIndex token index of T_FUNCTION + * @param int $functionOpenIndex token index of the opening brace token of the function + * @param int $functionCloseIndex token index of the closing brace token of the function + * + * @return int >= 0 number of tokens inserted into the Tokens collection + */ + private function fixFunction(Tokens $tokens, int $functionIndex, int $functionOpenIndex, int $functionCloseIndex): int + { + static $riskyKinds = [ + CT::T_DYNAMIC_VAR_BRACE_OPEN, // "$h = ${$g};" case + T_EVAL, // "$c = eval('return $this;');" case + T_GLOBAL, + T_INCLUDE, // loading additional symbols we cannot analyze here + T_INCLUDE_ONCE, // " + T_REQUIRE, // " + T_REQUIRE_ONCE, // " + ]; + + $inserted = 0; + $candidates = []; + $isRisky = false; + + if ($tokens[$tokens->getNextMeaningfulToken($functionIndex)]->isGivenKind(CT::T_RETURN_REF)) { + $isRisky = true; + } + + // go through the function declaration and check if references are passed + // - check if it will be risky to fix return statements of this function + for ($index = $functionIndex + 1; $index < $functionOpenIndex; ++$index) { + if ($tokens[$index]->equals('&')) { + $isRisky = true; + + break; + } + } + + // go through all the tokens of the body of the function: + // - check if it will be risky to fix return statements of this function + // - check nested functions; fix when found and update the upper limit + number of inserted token + // - check for return statements that might be fixed (based on if fixing will be risky, which is only know after analyzing the whole function) + + for ($index = $functionOpenIndex + 1; $index < $functionCloseIndex; ++$index) { + if ($tokens[$index]->isGivenKind(T_FUNCTION)) { + $nestedFunctionOpenIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + if ($tokens[$nestedFunctionOpenIndex]->equals(';')) { // abstract function + $index = $nestedFunctionOpenIndex - 1; + + continue; + } + + $nestedFunctionCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nestedFunctionOpenIndex); + + $tokensAdded = $this->fixFunction( + $tokens, + $index, + $nestedFunctionOpenIndex, + $nestedFunctionCloseIndex + ); + + $index = $nestedFunctionCloseIndex + $tokensAdded; + $functionCloseIndex += $tokensAdded; + $inserted += $tokensAdded; + } + + if ($isRisky) { + continue; // don't bother to look into anything else than nested functions as the current is risky already + } + + if ($tokens[$index]->equals('&')) { + $isRisky = true; + + continue; + } + + if ($tokens[$index]->isGivenKind(T_RETURN)) { + $candidates[] = $index; + + continue; + } + + // test if there is anything in the function body that might + // change global state or indirect changes (like through references, eval, etc.) + + if ($tokens[$index]->isGivenKind($riskyKinds)) { + $isRisky = true; + + continue; + } + + if ($tokens[$index]->isGivenKind(T_STATIC)) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$nextIndex]->isGivenKind(T_FUNCTION)) { + $isRisky = true; // "static $a" case + + continue; + } + } + + if ($tokens[$index]->equals('$')) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ($tokens[$nextIndex]->isGivenKind(T_VARIABLE)) { + $isRisky = true; // "$$a" case + + continue; + } + } + + if ($this->tokensAnalyzer->isSuperGlobal($index)) { + $isRisky = true; + + continue; + } + } + + if ($isRisky) { + return $inserted; + } + + // fix the candidates in reverse order when applicable + for ($i = \count($candidates) - 1; $i >= 0; --$i) { + $index = $candidates[$i]; + + // Check if returning only a variable (i.e. not the result of an expression, function call etc.) + $returnVarIndex = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$returnVarIndex]->isGivenKind(T_VARIABLE)) { + continue; // example: "return 1;" + } + + $endReturnVarIndex = $tokens->getNextMeaningfulToken($returnVarIndex); + if (!$tokens[$endReturnVarIndex]->equalsAny([';', [T_CLOSE_TAG]])) { + continue; // example: "return $a + 1;" + } + + // Check that the variable is assigned just before it is returned + $assignVarEndIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$assignVarEndIndex]->equals(';')) { + continue; // example: "? return $a;" + } + + // Note: here we are @ "; return $a;" (or "; return $a ? >") + while (true) { + $prevMeaningFul = $tokens->getPrevMeaningfulToken($assignVarEndIndex); + + if (!$tokens[$prevMeaningFul]->equals(')')) { + break; + } + + $assignVarEndIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $prevMeaningFul); + } + + $assignVarOperatorIndex = $tokens->getPrevTokenOfKind( + $assignVarEndIndex, + ['=', ';', '{', '}', [T_OPEN_TAG], [T_OPEN_TAG_WITH_ECHO]] + ); + + if ($tokens[$assignVarOperatorIndex]->equals('}')) { + $startIndex = $this->isCloseBracePartOfDefinition($tokens, $assignVarOperatorIndex); // test for `anonymous class`, `lambda` and `match` + + if (null === $startIndex) { + continue; + } + + $assignVarOperatorIndex = $tokens->getPrevMeaningfulToken($startIndex); + } + + if (!$tokens[$assignVarOperatorIndex]->equals('=')) { + continue; + } + + // Note: here we are @ "= [^;{] ; return $a;" + $assignVarIndex = $tokens->getPrevMeaningfulToken($assignVarOperatorIndex); + if (!$tokens[$assignVarIndex]->equals($tokens[$returnVarIndex], false)) { + continue; + } + + // Note: here we are @ "$a = [^;{] ; return $a;" + $beforeAssignVarIndex = $tokens->getPrevMeaningfulToken($assignVarIndex); + if (!$tokens[$beforeAssignVarIndex]->equalsAny([';', '{', '}'])) { + continue; + } + + // Check if there is a `catch` or `finally` block between the assignment and the return + if ($this->isUsedInCatchOrFinally($tokens, $returnVarIndex, $functionOpenIndex, $functionCloseIndex)) { + continue; + } + + // Note: here we are @ "[;{}] $a = [^;{] ; return $a;" + $inserted += $this->simplifyReturnStatement( + $tokens, + $assignVarIndex, + $assignVarOperatorIndex, + $index, + $endReturnVarIndex + ); + } + + return $inserted; + } + + /** + * @return int >= 0 number of tokens inserted into the Tokens collection + */ + private function simplifyReturnStatement( + Tokens $tokens, + int $assignVarIndex, + int $assignVarOperatorIndex, + int $returnIndex, + int $returnVarEndIndex + ): int { + $inserted = 0; + $originalIndent = $tokens[$assignVarIndex - 1]->isWhitespace() + ? $tokens[$assignVarIndex - 1]->getContent() + : null; + + // remove the return statement + if ($tokens[$returnVarEndIndex]->equals(';')) { // do not remove PHP close tags + $tokens->clearTokenAndMergeSurroundingWhitespace($returnVarEndIndex); + } + + for ($i = $returnIndex; $i <= $returnVarEndIndex - 1; ++$i) { + $this->clearIfSave($tokens, $i); + } + + // remove no longer needed indentation of the old/remove return statement + if ($tokens[$returnIndex - 1]->isWhitespace()) { + $content = $tokens[$returnIndex - 1]->getContent(); + $fistLinebreakPos = strrpos($content, "\n"); + $content = false === $fistLinebreakPos + ? ' ' + : substr($content, $fistLinebreakPos); + + $tokens[$returnIndex - 1] = new Token([T_WHITESPACE, $content]); + } + + // remove the variable and the assignment + for ($i = $assignVarIndex; $i <= $assignVarOperatorIndex; ++$i) { + $this->clearIfSave($tokens, $i); + } + + // insert new return statement + $tokens->insertAt($assignVarIndex, new Token([T_RETURN, 'return'])); + ++$inserted; + + // use the original indent of the var assignment for the new return statement + if ( + null !== $originalIndent + && $tokens[$assignVarIndex - 1]->isWhitespace() + && $originalIndent !== $tokens[$assignVarIndex - 1]->getContent() + ) { + $tokens[$assignVarIndex - 1] = new Token([T_WHITESPACE, $originalIndent]); + } + + // remove trailing space after the new return statement which might be added during the cleanup process + $nextIndex = $tokens->getNonEmptySibling($assignVarIndex, 1); + if (!$tokens[$nextIndex]->isWhitespace()) { + $tokens->insertAt($nextIndex, new Token([T_WHITESPACE, ' '])); + ++$inserted; + } + + return $inserted; + } + + private function clearIfSave(Tokens $tokens, int $index): void + { + if ($tokens[$index]->isComment()) { + return; + } + + if ($tokens[$index]->isWhitespace() && $tokens[$tokens->getPrevNonWhitespace($index)]->isComment()) { + return; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + + /** + * @param int $index open brace index + * + * @return null|int index of the first token of a definition (lambda, anonymous class or match) or `null` if not an anonymous + */ + private function isCloseBracePartOfDefinition(Tokens $tokens, int $index): ?int + { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + $candidateIndex = $this->isOpenBraceOfLambda($tokens, $index); + + if (null !== $candidateIndex) { + return $candidateIndex; + } + + $candidateIndex = $this->isOpenBraceOfAnonymousClass($tokens, $index); + + return $candidateIndex ?? $this->isOpenBraceOfMatch($tokens, $index); + } + + /** + * @param int $index open brace index + * + * @return null|int index of T_NEW of anonymous class or `null` if not an anonymous + */ + private function isOpenBraceOfAnonymousClass(Tokens $tokens, int $index): ?int + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while ($tokens[$index]->equalsAny([',', [T_STRING], [T_IMPLEMENTS], [T_EXTENDS], [T_NS_SEPARATOR]])); + + if ($tokens[$index]->equals(')')) { // skip constructor braces and content within + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $index = $tokens->getPrevMeaningfulToken($index); + } + + if (!$tokens[$index]->isGivenKind(T_CLASS) || !$this->tokensAnalyzer->isAnonymousClass($index)) { + return null; + } + + return $tokens->getPrevTokenOfKind($index, [[T_NEW]]); + } + + /** + * @param int $index open brace index + * + * @return null|int index of T_FUNCTION or T_STATIC of lambda or `null` if not a lambda + */ + private function isOpenBraceOfLambda(Tokens $tokens, int $index): ?int + { + $index = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$index]->equals(')')) { + return null; + } + + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $index = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(CT::T_USE_LAMBDA)) { + $index = $tokens->getPrevTokenOfKind($index, [')']); + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $index = $tokens->getPrevMeaningfulToken($index); + } + + if ($tokens[$index]->isGivenKind(CT::T_RETURN_REF)) { + $index = $tokens->getPrevMeaningfulToken($index); + } + + if (!$tokens[$index]->isGivenKind(T_FUNCTION)) { + return null; + } + + $staticCandidate = $tokens->getPrevMeaningfulToken($index); + + return $tokens[$staticCandidate]->isGivenKind(T_STATIC) ? $staticCandidate : $index; + } + + /** + * @param int $index open brace index + * + * @return null|int index of T_MATCH or `null` if not a `match` + */ + private function isOpenBraceOfMatch(Tokens $tokens, int $index): ?int + { + if (!\defined('T_MATCH') || !$tokens->isTokenKindFound(T_MATCH)) { // @TODO: drop condition when PHP 8.0+ is required + return null; + } + + $index = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$index]->equals(')')) { + return null; + } + + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $index = $tokens->getPrevMeaningfulToken($index); + + return $tokens[$index]->isGivenKind(T_MATCH) ? $index : null; + } + + private function isUsedInCatchOrFinally(Tokens $tokens, int $returnVarIndex, int $functionOpenIndex, int $functionCloseIndex): bool + { + // Find try + $tryIndex = $tokens->getPrevTokenOfKind($returnVarIndex, [[T_TRY]]); + if (null === $tryIndex || $tryIndex <= $functionOpenIndex) { + return false; + } + $tryOpenIndex = $tokens->getNextTokenOfKind($tryIndex, ['{']); + $tryCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $tryOpenIndex); + + // Find catch or finally + $nextIndex = $tokens->getNextMeaningfulToken($tryCloseIndex); + if (null === $nextIndex) { + return false; + } + + // Find catches + while ($tokens[$nextIndex]->isGivenKind(T_CATCH)) { + $catchOpenIndex = $tokens->getNextTokenOfKind($nextIndex, ['{']); + $catchCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $catchOpenIndex); + + if ($catchCloseIndex >= $functionCloseIndex) { + return false; + } + $varIndex = $tokens->getNextTokenOfKind($catchOpenIndex, [$tokens[$returnVarIndex]]); + // Check if the variable is used in the finally block + if (null !== $varIndex && $varIndex < $catchCloseIndex) { + return true; + } + + $nextIndex = $tokens->getNextMeaningfulToken($catchCloseIndex); + if (null === $nextIndex) { + return false; + } + } + + if (!$tokens[$nextIndex]->isGivenKind(T_FINALLY)) { + return false; + } + + $finallyIndex = $nextIndex; + if ($finallyIndex >= $functionCloseIndex) { + return false; + } + $finallyOpenIndex = $tokens->getNextTokenOfKind($finallyIndex, ['{']); + $finallyCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $finallyOpenIndex); + $varIndex = $tokens->getNextTokenOfKind($finallyOpenIndex, [$tokens[$returnVarIndex]]); + // Check if the variable is used in the finally block + if (null !== $varIndex && $varIndex < $finallyCloseIndex) { + return true; + } + + return false; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php new file mode 100644 index 00000000..bc222aa3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php @@ -0,0 +1,148 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ReturnNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + */ +final class SimplifiedNullReturnFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'A return statement wishing to return `void` should not return `null`.', + [ + new CodeSample("isTokenKindFound(T_RETURN); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_RETURN)) { + continue; + } + + if ($this->needFixing($tokens, $index)) { + $this->clear($tokens, $index); + } + } + } + + /** + * Clear the return statement located at a given index. + */ + private function clear(Tokens $tokens, int $index): void + { + while (!$tokens[++$index]->equals(';')) { + if ($this->shouldClearToken($tokens, $index)) { + $tokens->clearAt($index); + } + } + } + + /** + * Does the return statement located at a given index need fixing? + */ + private function needFixing(Tokens $tokens, int $index): bool + { + if ($this->isStrictOrNullableReturnTypeFunction($tokens, $index)) { + return false; + } + + $content = ''; + while (!$tokens[$index]->equals(';')) { + $index = $tokens->getNextMeaningfulToken($index); + $content .= $tokens[$index]->getContent(); + } + + $content = ltrim($content, '('); + $content = rtrim($content, ');'); + + return 'null' === strtolower($content); + } + + /** + * Is the return within a function with a non-void or nullable return type? + * + * @param int $returnIndex Current return token index + */ + private function isStrictOrNullableReturnTypeFunction(Tokens $tokens, int $returnIndex): bool + { + $functionIndex = $returnIndex; + do { + $functionIndex = $tokens->getPrevTokenOfKind($functionIndex, [[T_FUNCTION]]); + if (null === $functionIndex) { + return false; + } + $openingCurlyBraceIndex = $tokens->getNextTokenOfKind($functionIndex, ['{']); + $closingCurlyBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openingCurlyBraceIndex); + } while ($closingCurlyBraceIndex < $returnIndex); + + $possibleVoidIndex = $tokens->getPrevMeaningfulToken($openingCurlyBraceIndex); + $isStrictReturnType = $tokens[$possibleVoidIndex]->isGivenKind(T_STRING) && 'void' !== $tokens[$possibleVoidIndex]->getContent(); + + $nullableTypeIndex = $tokens->getNextTokenOfKind($functionIndex, [[CT::T_NULLABLE_TYPE]]); + $isNullableReturnType = null !== $nullableTypeIndex && $nullableTypeIndex < $openingCurlyBraceIndex; + + return $isStrictReturnType || $isNullableReturnType; + } + + /** + * Should we clear the specific token? + * + * If the token is a comment, or is whitespace that is immediately before a + * comment, then we'll leave it alone. + */ + private function shouldClearToken(Tokens $tokens, int $index): bool + { + $token = $tokens[$index]; + + return !$token->isComment() && !($token->isWhitespace() && $tokens[$index + 1]->isComment()); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php new file mode 100644 index 00000000..f92ced5c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php @@ -0,0 +1,228 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Semicolon; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + * @author Egidijus Girčys + */ +final class MultilineWhitespaceBeforeSemicolonsFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @internal + */ + public const STRATEGY_NO_MULTI_LINE = 'no_multi_line'; + + /** + * @internal + */ + public const STRATEGY_NEW_LINE_FOR_CHAINED_CALLS = 'new_line_for_chained_calls'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Forbid multi-line whitespace before the closing semicolon or move the semicolon to the new line for chained calls.', + [ + new CodeSample( + 'method1() + ->method2() + ->method(3); +', + ['strategy' => self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before SpaceAfterSemicolonFixer. + * Must run after CombineConsecutiveIssetsFixer, GetClassToClassKeywordFixer, NoEmptyStatementFixer, SimplifiedIfReturnFixer, SingleImportPerStatementFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(';'); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder( + 'strategy', + 'Forbid multi-line whitespace or move the semicolon to the new line for chained calls.' + )) + ->setAllowedValues([self::STRATEGY_NO_MULTI_LINE, self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS]) + ->setDefault(self::STRATEGY_NO_MULTI_LINE) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + for ($index = 0, $count = \count($tokens); $index < $count; ++$index) { + if (!$tokens[$index]->equals(';')) { + continue; + } + + $previousIndex = $index - 1; + $previous = $tokens[$previousIndex]; + + $indent = $this->findWhitespaceBeforeFirstCall($index, $tokens); + if (self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS === $this->configuration['strategy'] && null !== $indent) { + if ($previous->isWhitespace() && $previous->getContent() === $lineEnding.$indent) { + continue; + } + + // unset whitespace and semicolon + if ($previous->isWhitespace()) { + $tokens->clearAt($previousIndex); + } + $tokens->clearAt($index); + + // find the line ending token index after the semicolon + $index = $this->getNewLineIndex($index, $tokens); + + // appended new line to the last method call + $newline = new Token([T_WHITESPACE, $lineEnding.$indent]); + + // insert the new line with indented semicolon + $tokens->insertAt($index++, [$newline, new Token(';')]); + } else { + if (!$previous->isWhitespace() || !str_contains($previous->getContent(), "\n")) { + continue; + } + + $content = $previous->getContent(); + if (str_starts_with($content, $lineEnding) && $tokens[$index - 2]->isComment()) { + // if there is comment between closing parenthesis and semicolon + + // unset whitespace and semicolon + $tokens->clearAt($previousIndex); + $tokens->clearAt($index); + + // find the significant token index before the semicolon + $significantTokenIndex = $this->getPreviousSignificantTokenIndex($index, $tokens); + + // insert the semicolon + $tokens->insertAt($significantTokenIndex + 1, [new Token(';')]); + } else { + // if there is whitespace between closing bracket and semicolon, just remove it + $tokens->clearAt($previousIndex); + } + } + } + } + + /** + * Find the index for the next new line. Return the given index when there's no new line. + */ + private function getNewLineIndex(int $index, Tokens $tokens): int + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + for ($index, $count = \count($tokens); $index < $count; ++$index) { + if (false !== strstr($tokens[$index]->getContent(), $lineEnding)) { + return $index; + } + } + + return $index; + } + + /** + * Find the index for the previous significant token. Return the given index when there's no significant token. + */ + private function getPreviousSignificantTokenIndex(int $index, Tokens $tokens): int + { + $stopTokens = [ + T_LNUMBER, + T_DNUMBER, + T_STRING, + T_VARIABLE, + T_CONSTANT_ENCAPSED_STRING, + ]; + for ($index; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind($stopTokens) || $tokens[$index]->equals(')')) { + return $index; + } + } + + return $index; + } + + /** + * Checks if the semicolon closes a multiline call and returns the whitespace of the first call at $index. + * i.e. it will return the whitespace marked with '____' in the example underneath. + * + * .. + * ____$this->methodCall() + * ->anotherCall(); + * .. + */ + private function findWhitespaceBeforeFirstCall(int $index, Tokens $tokens): ?string + { + $isMultilineCall = false; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + while (!$tokens[$prevIndex]->equalsAny([';', ':', '{', '}', [T_OPEN_TAG], [T_OPEN_TAG_WITH_ECHO], [T_ELSE]])) { + $index = $prevIndex; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + $blockType = Tokens::detectBlockType($tokens[$index]); + if (null !== $blockType && !$blockType['isStart']) { + $prevIndex = $tokens->findBlockStart($blockType['type'], $index); + + continue; + } + + if ($tokens[$index]->isObjectOperator() || $tokens[$index]->isGivenKind(T_DOUBLE_COLON)) { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $isMultilineCall |= $tokens->isPartialCodeMultiline($prevIndex, $index); + } + } + + return $isMultilineCall ? WhitespacesAnalyzer::detectIndent($tokens, $index) : null; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoEmptyStatementFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoEmptyStatementFixer.php new file mode 100644 index 00000000..15c1e670 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoEmptyStatementFixer.php @@ -0,0 +1,186 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Semicolon; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Dariusz Rumiński + */ +final class NoEmptyStatementFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Remove useless (semicolon) statements.', + [ + new CodeSample("isTokenKindFound(';'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + if ($tokens[$index]->isGivenKind([T_BREAK, T_CONTINUE])) { + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->equals([T_LNUMBER, '1'])) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + + continue; + } + + // skip T_FOR parenthesis to ignore double `;` like `for ($i = 1; ; ++$i) {...}` + if ($tokens[$index]->isGivenKind(T_FOR)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextMeaningfulToken($index)) + 1; + + continue; + } + + if (!$tokens[$index]->equals(';')) { + continue; + } + + $previousMeaningfulIndex = $tokens->getPrevMeaningfulToken($index); + + // A semicolon can always be removed if it follows a semicolon, '{' or opening tag. + if ($tokens[$previousMeaningfulIndex]->equalsAny(['{', ';', [T_OPEN_TAG]])) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + continue; + } + + // A semicolon might be removed if it follows a '}' but only if the brace is part of certain structures. + if ($tokens[$previousMeaningfulIndex]->equals('}')) { + $this->fixSemicolonAfterCurlyBraceClose($tokens, $index, $previousMeaningfulIndex); + + continue; + } + + // A semicolon might be removed together with its noop statement, for example "getPrevMeaningfulToken($previousMeaningfulIndex); + + if ( + $tokens[$prePreviousMeaningfulIndex]->equalsAny([';', '{', '}', [T_OPEN_TAG]]) + && $tokens[$previousMeaningfulIndex]->isGivenKind([T_CONSTANT_ENCAPSED_STRING, T_DNUMBER, T_LNUMBER, T_STRING, T_VARIABLE]) + ) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($previousMeaningfulIndex); + } + } + } + + /** + * Fix semicolon after closing curly brace if needed. + * + * Test for the following cases + * - just '{' '}' block (following open tag or ';') + * - if, else, elseif + * - interface, trait, class (but not anonymous) + * - catch, finally (but not try) + * - for, foreach, while (but not 'do - while') + * - switch + * - function (declaration, but not lambda) + * - declare (with '{' '}') + * - namespace (with '{' '}') + * + * @param int $index Semicolon index + */ + private function fixSemicolonAfterCurlyBraceClose(Tokens $tokens, int $index, int $curlyCloseIndex): void + { + static $beforeCurlyOpeningKinds = null; + + if (null === $beforeCurlyOpeningKinds) { + $beforeCurlyOpeningKinds = [T_ELSE, T_FINALLY, T_NAMESPACE, T_OPEN_TAG]; + } + + $curlyOpeningIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $curlyCloseIndex); + $beforeCurlyOpeningIndex = $tokens->getPrevMeaningfulToken($curlyOpeningIndex); + + if ($tokens[$beforeCurlyOpeningIndex]->isGivenKind($beforeCurlyOpeningKinds) || $tokens[$beforeCurlyOpeningIndex]->equalsAny([';', '{', '}'])) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + return; + } + + // check for namespaces and class, interface and trait definitions + if ($tokens[$beforeCurlyOpeningIndex]->isGivenKind(T_STRING)) { + $classyTestIndex = $tokens->getPrevMeaningfulToken($beforeCurlyOpeningIndex); + + while ($tokens[$classyTestIndex]->equals(',') || $tokens[$classyTestIndex]->isGivenKind([T_STRING, T_NS_SEPARATOR, T_EXTENDS, T_IMPLEMENTS])) { + $classyTestIndex = $tokens->getPrevMeaningfulToken($classyTestIndex); + } + + $tokensAnalyzer = new TokensAnalyzer($tokens); + + if ( + $tokens[$classyTestIndex]->isGivenKind(T_NAMESPACE) + || ($tokens[$classyTestIndex]->isClassy() && !$tokensAnalyzer->isAnonymousClass($classyTestIndex)) + ) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + + return; + } + + // early return check, below only control structures with conditions are fixed + if (!$tokens[$beforeCurlyOpeningIndex]->equals(')')) { + return; + } + + $openingBraceIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $beforeCurlyOpeningIndex); + $beforeOpeningBraceIndex = $tokens->getPrevMeaningfulToken($openingBraceIndex); + + if ($tokens[$beforeOpeningBraceIndex]->isGivenKind([T_IF, T_ELSEIF, T_FOR, T_FOREACH, T_WHILE, T_SWITCH, T_CATCH, T_DECLARE])) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + return; + } + + // check for function definition + if ($tokens[$beforeOpeningBraceIndex]->isGivenKind(T_STRING)) { + $beforeStringIndex = $tokens->getPrevMeaningfulToken($beforeOpeningBraceIndex); + + if ($tokens[$beforeStringIndex]->isGivenKind(T_FUNCTION)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); // implicit return + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php new file mode 100644 index 00000000..f06d9d73 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php @@ -0,0 +1,66 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Semicolon; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + */ +final class NoSinglelineWhitespaceBeforeSemicolonsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Single-line whitespace before closing semicolon are prohibited.', + [new CodeSample("foo() ;\n")] + ); + } + + /** + * {@inheritdoc} + * + * Must run after CombineConsecutiveIssetsFixer, FunctionToConstantFixer, LongToShorthandOperatorFixer, NoEmptyStatementFixer, NoUnneededImportAliasFixer, SimplifiedIfReturnFixer, SingleImportPerStatementFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(';'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->equals(';') || !$tokens[$index - 1]->isWhitespace(" \t")) { + continue; + } + + if ($tokens[$index - 2]->equals(';')) { + // do not remove all whitespace before the semicolon because it is also whitespace after another semicolon + $tokens->ensureWhitespaceAtIndex($index - 1, 0, ' '); + } elseif (!$tokens[$index - 2]->isComment()) { + $tokens->clearAt($index - 1); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php new file mode 100644 index 00000000..2fe9ab07 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php @@ -0,0 +1,64 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Semicolon; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class SemicolonAfterInstructionFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Instructions must be terminated with a semicolon.', + [new CodeSample("\n")] + ); + } + + /** + * {@inheritdoc} + * + * Must run before SimplifiedIfReturnFixer. + */ + public function getPriority(): int + { + return 2; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_CLOSE_TAG); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; $index > 1; --$index) { + if (!$tokens[$index]->isGivenKind(T_CLOSE_TAG)) { + continue; + } + + $prev = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prev]->equalsAny([';', '{', '}', ':', [T_OPEN_TAG]])) { + continue; + } + + $tokens->insertAt($prev + 1, new Token(';')); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php new file mode 100644 index 00000000..63be6cfe --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php @@ -0,0 +1,134 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Semicolon; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class SpaceAfterSemicolonFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Fix whitespace after a semicolon.', + [ + new CodeSample( + " true, + ]), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run after CombineConsecutiveUnsetsFixer, MultilineWhitespaceBeforeSemicolonsFixer, NoEmptyStatementFixer, OrderedClassElementsFixer, SingleImportPerStatementFixer, SingleTraitInsertPerStatementFixer. + */ + public function getPriority(): int + { + return -1; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(';'); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('remove_in_empty_for_expressions', 'Whether spaces should be removed for empty `for` expressions.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $insideForParenthesesUntil = null; + + for ($index = 0, $max = \count($tokens) - 1; $index < $max; ++$index) { + if (true === $this->configuration['remove_in_empty_for_expressions']) { + if ($tokens[$index]->isGivenKind(T_FOR)) { + $index = $tokens->getNextMeaningfulToken($index); + $insideForParenthesesUntil = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + + continue; + } + + if ($index === $insideForParenthesesUntil) { + $insideForParenthesesUntil = null; + + continue; + } + } + + if (!$tokens[$index]->equals(';')) { + continue; + } + + if (!$tokens[$index + 1]->isWhitespace()) { + if ( + !$tokens[$index + 1]->equalsAny([')', [T_INLINE_HTML]]) && ( + false === $this->configuration['remove_in_empty_for_expressions'] + || !$tokens[$index + 1]->equals(';') + ) + ) { + $tokens->insertAt($index + 1, new Token([T_WHITESPACE, ' '])); + ++$max; + } + + continue; + } + + if ( + null !== $insideForParenthesesUntil + && ($tokens[$index + 2]->equals(';') || $index + 2 === $insideForParenthesesUntil) + && !Preg::match('/\R/', $tokens[$index + 1]->getContent()) + ) { + $tokens->clearAt($index + 1); + + continue; + } + + if ( + isset($tokens[$index + 2]) + && !$tokens[$index + 1]->equals([T_WHITESPACE, ' ']) + && $tokens[$index + 1]->isWhitespace(" \t") + && !$tokens[$index + 2]->isComment() + && !$tokens[$index + 2]->equals(')') + ) { + $tokens[$index + 1] = new Token([T_WHITESPACE, ' ']); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/DeclareStrictTypesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/DeclareStrictTypesFixer.php new file mode 100644 index 00000000..4a83a9de --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/DeclareStrictTypesFixer.php @@ -0,0 +1,140 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Strict; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Jordi Boggiano + */ +final class DeclareStrictTypesFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Force strict types declaration in all files. Requires PHP >= 7.0.', + [ + new CodeSample( + "isGivenKind(T_OPEN_TAG); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + // check if the declaration is already done + $searchIndex = $tokens->getNextMeaningfulToken(0); + if (null === $searchIndex) { + $this->insertSequence($tokens); // declaration not found, insert one + + return; + } + + $sequenceLocation = $tokens->findSequence([[T_DECLARE, 'declare'], '(', [T_STRING, 'strict_types'], '=', [T_LNUMBER], ')'], $searchIndex, null, false); + if (null === $sequenceLocation) { + $this->insertSequence($tokens); // declaration not found, insert one + + return; + } + + $this->fixStrictTypesCasingAndValue($tokens, $sequenceLocation); + } + + /** + * @param array $sequence + */ + private function fixStrictTypesCasingAndValue(Tokens $tokens, array $sequence): void + { + /** @var int $index */ + /** @var Token $token */ + foreach ($sequence as $index => $token) { + if ($token->isGivenKind(T_STRING)) { + $tokens[$index] = new Token([T_STRING, strtolower($token->getContent())]); + + continue; + } + if ($token->isGivenKind(T_LNUMBER)) { + $tokens[$index] = new Token([T_LNUMBER, '1']); + + break; + } + } + } + + private function insertSequence(Tokens $tokens): void + { + $sequence = [ + new Token([T_DECLARE, 'declare']), + new Token('('), + new Token([T_STRING, 'strict_types']), + new Token('='), + new Token([T_LNUMBER, '1']), + new Token(')'), + new Token(';'), + ]; + $endIndex = \count($sequence); + + $tokens->insertAt(1, $sequence); + + // start index of the sequence is always 1 here, 0 is always open tag + // transform "getContent(), "\n")) { + $tokens[0] = new Token([$tokens[0]->getId(), trim($tokens[0]->getContent()).' ']); + } + + if ($endIndex === \count($tokens) - 1) { + return; // no more tokens after sequence, single_blank_line_at_eof might add a line + } + + $lineEnding = $this->whitespacesConfig->getLineEnding(); + if (!$tokens[1 + $endIndex]->isWhitespace()) { + $tokens->insertAt(1 + $endIndex, new Token([T_WHITESPACE, $lineEnding])); + + return; + } + + $content = $tokens[1 + $endIndex]->getContent(); + $tokens[1 + $endIndex] = new Token([T_WHITESPACE, $lineEnding.ltrim($content, " \t")]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictComparisonFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictComparisonFixer.php new file mode 100644 index 00000000..18222c59 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictComparisonFixer.php @@ -0,0 +1,80 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Strict; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class StrictComparisonFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Comparisons should be strict.', + [new CodeSample("isAnyTokenKindsFound([T_IS_EQUAL, T_IS_NOT_EQUAL]); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + static $map = [ + T_IS_EQUAL => [ + 'id' => T_IS_IDENTICAL, + 'content' => '===', + ], + T_IS_NOT_EQUAL => [ + 'id' => T_IS_NOT_IDENTICAL, + 'content' => '!==', + ], + ]; + + foreach ($tokens as $index => $token) { + $tokenId = $token->getId(); + + if (isset($map[$tokenId])) { + $tokens[$index] = new Token([$map[$tokenId]['id'], $map[$tokenId]['content']]); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictParamFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictParamFixer.php new file mode 100644 index 00000000..d9280969 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictParamFixer.php @@ -0,0 +1,165 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Strict; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class StrictParamFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Functions should be used with `$strict` param set to `true`.', + [new CodeSample("isTokenKindFound(T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run before MethodArgumentSpaceFixer, NativeFunctionInvocationFixer. + */ + public function getPriority(): int + { + return 31; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + static $map = null; + + if (null === $map) { + $trueToken = new Token([T_STRING, 'true']); + + $map = [ + 'array_keys' => [null, null, $trueToken], + 'array_search' => [null, null, $trueToken], + 'base64_decode' => [null, $trueToken], + 'in_array' => [null, null, $trueToken], + 'mb_detect_encoding' => [null, [new Token([T_STRING, 'mb_detect_order']), new Token('('), new Token(')')], $trueToken], + ]; + } + + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + + $nextIndex = $tokens->getNextMeaningfulToken($index); + if (null !== $nextIndex && !$tokens[$nextIndex]->equals('(')) { + continue; + } + + $lowercaseContent = strtolower($token->getContent()); + if (isset($map[$lowercaseContent]) && $functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + $this->fixFunction($tokens, $index, $map[$lowercaseContent]); + } + } + } + + private function fixFunction(Tokens $tokens, int $functionIndex, array $functionParams): void + { + $startBraceIndex = $tokens->getNextTokenOfKind($functionIndex, ['(']); + $endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startBraceIndex); + $paramsQuantity = 0; + $expectParam = true; + + for ($index = $startBraceIndex + 1; $index < $endBraceIndex; ++$index) { + $token = $tokens[$index]; + + if ($expectParam && !$token->isWhitespace() && !$token->isComment()) { + ++$paramsQuantity; + $expectParam = false; + } + + if ($token->equals('(')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + + continue; + } + + if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); + + continue; + } + + if ($token->equals(',')) { + $expectParam = true; + + continue; + } + } + + $functionParamsQuantity = \count($functionParams); + + if ($paramsQuantity === $functionParamsQuantity) { + return; + } + + $tokensToInsert = []; + + for ($i = $paramsQuantity; $i < $functionParamsQuantity; ++$i) { + // function call do not have all params that are required to set useStrict flag, exit from method! + if (!$functionParams[$i]) { + return; + } + + $tokensToInsert[] = new Token(','); + $tokensToInsert[] = new Token([T_WHITESPACE, ' ']); + + if (!\is_array($functionParams[$i])) { + $tokensToInsert[] = clone $functionParams[$i]; + + continue; + } + + foreach ($functionParams[$i] as $param) { + $tokensToInsert[] = clone $param; + } + } + + $beforeEndBraceIndex = $tokens->getPrevMeaningfulToken($endBraceIndex); + + if ($tokens[$beforeEndBraceIndex]->equals(',')) { + array_shift($tokensToInsert); + $tokensToInsert[] = new Token(','); + } + + $tokens->insertAt($beforeEndBraceIndex + 1, $tokensToInsert); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php new file mode 100644 index 00000000..af0a103d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php @@ -0,0 +1,158 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + */ +final class EscapeImplicitBackslashesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + $codeSample = <<<'EOF' + true] + ), + new CodeSample( + $codeSample, + ['double_quoted' => false] + ), + new CodeSample( + $codeSample, + ['heredoc_syntax' => false] + ), + ], + 'In PHP double-quoted strings and heredocs some chars like `n`, `$` or `u` have special meanings if preceded by a backslash ' + .'(and some are special only if followed by other special chars), while a backslash preceding other chars are interpreted like a plain ' + .'backslash. The precise list of those special chars is hard to remember and to identify quickly: this fixer escapes backslashes ' + ."that do not start a special interpretation with the char after them.\n" + .'It is possible to fix also single-quoted strings: in this case there is no special chars apart from single-quote and backslash ' + .'itself, so the fixer simply ensure that all backslashes are escaped. Both single and double backslashes are allowed in single-quoted ' + .'strings, so the purpose in this context is mainly to have a uniformed way to have them written all over the codebase.' + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([T_ENCAPSED_AND_WHITESPACE, T_CONSTANT_ENCAPSED_STRING]); + } + + /** + * {@inheritdoc} + * + * Must run before HeredocToNowdocFixer, SingleQuoteFixer. + * Must run after BacktickToShellExecFixer. + */ + public function getPriority(): int + { + return 15; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + static $singleQuotedRegex = '/(? $token) { + $content = $token->getContent(); + if ($token->equalsAny(['"', 'b"', 'B"'])) { + $doubleQuoteOpened = !$doubleQuoteOpened; + } + if (!$token->isGivenKind([T_ENCAPSED_AND_WHITESPACE, T_CONSTANT_ENCAPSED_STRING]) || !str_contains($content, '\\')) { + continue; + } + + // Nowdoc syntax + if ($token->isGivenKind(T_ENCAPSED_AND_WHITESPACE) && '\'' === substr(rtrim($tokens[$index - 1]->getContent()), -1)) { + continue; + } + + $firstTwoCharacters = strtolower(substr($content, 0, 2)); + $isSingleQuotedString = $token->isGivenKind(T_CONSTANT_ENCAPSED_STRING) && ('\'' === $content[0] || 'b\'' === $firstTwoCharacters); + $isDoubleQuotedString = + ($token->isGivenKind(T_CONSTANT_ENCAPSED_STRING) && ('"' === $content[0] || 'b"' === $firstTwoCharacters)) + || ($token->isGivenKind(T_ENCAPSED_AND_WHITESPACE) && $doubleQuoteOpened); + $isHeredocSyntax = !$isSingleQuotedString && !$isDoubleQuotedString; + if ( + (false === $this->configuration['single_quoted'] && $isSingleQuotedString) + || (false === $this->configuration['double_quoted'] && $isDoubleQuotedString) + || (false === $this->configuration['heredoc_syntax'] && $isHeredocSyntax) + ) { + continue; + } + + $regex = $heredocSyntaxRegex; + if ($isSingleQuotedString) { + $regex = $singleQuotedRegex; + } elseif ($isDoubleQuotedString) { + $regex = $doubleQuotedRegex; + } + + $newContent = Preg::replace($regex, '\\\\\\\\$1', $content); + if ($newContent !== $content) { + $tokens[$index] = new Token([$token->getId(), $newContent]); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('single_quoted', 'Whether to fix single-quoted strings.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('double_quoted', 'Whether to fix double-quoted strings.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('heredoc_syntax', 'Whether to fix heredoc syntax.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/ExplicitStringVariableFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/ExplicitStringVariableFixer.php new file mode 100644 index 00000000..92bc84ff --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/ExplicitStringVariableFixer.php @@ -0,0 +1,165 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + */ +final class ExplicitStringVariableFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts implicit variables into explicit ones in double-quoted strings or heredoc syntax.', + [new CodeSample( + <<<'EOT' + country !"; + $c = "I have $farm[0] chickens !"; + + EOT + )], + 'The reasoning behind this rule is the following:' + ."\n".'- When there are two valid ways of doing the same thing, using both is confusing, there should be a coding standard to follow.' + ."\n".'- PHP manual marks `"$var"` syntax as implicit and `"${var}"` syntax as explicit: explicit code should always be preferred.' + ."\n".'- Explicit syntax allows word concatenation inside strings, e.g. `"${var}IsAVar"`, implicit doesn\'t.' + ."\n".'- Explicit syntax is easier to detect for IDE/editors and therefore has colors/highlight with higher contrast, which is easier to read.' + ."\n".'Backtick operator is skipped because it is harder to handle; you can use `backtick_to_shell_exec` fixer to normalize backticks to strings.' + ); + } + + /** + * {@inheritdoc} + * + * Must run after BacktickToShellExecFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_VARIABLE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $backtickStarted = false; + for ($index = \count($tokens) - 1; $index > 0; --$index) { + $token = $tokens[$index]; + + if ($token->equals('`')) { + $backtickStarted = !$backtickStarted; + + continue; + } + + if ($backtickStarted || !$token->isGivenKind(T_VARIABLE)) { + continue; + } + + $prevToken = $tokens[$index - 1]; + + if (!$this->isStringPartToken($prevToken)) { + continue; + } + + $distinctVariableIndex = $index; + $variableTokens = [ + $distinctVariableIndex => [ + 'tokens' => [$index => $token], + 'firstVariableTokenIndex' => $index, + 'lastVariableTokenIndex' => $index, + ], + ]; + + $nextIndex = $index + 1; + $squareBracketCount = 0; + + while (!$this->isStringPartToken($tokens[$nextIndex])) { + if ($tokens[$nextIndex]->isGivenKind(T_CURLY_OPEN)) { + $nextIndex = $tokens->getNextTokenOfKind($nextIndex, [[CT::T_CURLY_CLOSE]]); + } elseif ($tokens[$nextIndex]->isGivenKind(T_VARIABLE) && 1 !== $squareBracketCount) { + $distinctVariableIndex = $nextIndex; + $variableTokens[$distinctVariableIndex] = [ + 'tokens' => [$nextIndex => $tokens[$nextIndex]], + 'firstVariableTokenIndex' => $nextIndex, + 'lastVariableTokenIndex' => $nextIndex, + ]; + } else { + $variableTokens[$distinctVariableIndex]['tokens'][$nextIndex] = $tokens[$nextIndex]; + $variableTokens[$distinctVariableIndex]['lastVariableTokenIndex'] = $nextIndex; + + if ($tokens[$nextIndex]->equalsAny(['[', ']'])) { + ++$squareBracketCount; + } + } + + ++$nextIndex; + } + krsort($variableTokens, SORT_NUMERIC); + + foreach ($variableTokens as $distinctVariableSet) { + if (1 === \count($distinctVariableSet['tokens'])) { + $singleVariableIndex = key($distinctVariableSet['tokens']); + $singleVariableToken = current($distinctVariableSet['tokens']); + $tokens->overrideRange($singleVariableIndex, $singleVariableIndex, [ + new Token([T_CURLY_OPEN, '{']), + new Token([T_VARIABLE, $singleVariableToken->getContent()]), + new Token([CT::T_CURLY_CLOSE, '}']), + ]); + } else { + foreach ($distinctVariableSet['tokens'] as $variablePartIndex => $variablePartToken) { + if ($variablePartToken->isGivenKind(T_NUM_STRING)) { + $tokens[$variablePartIndex] = new Token([T_LNUMBER, $variablePartToken->getContent()]); + + continue; + } + + if ($variablePartToken->isGivenKind(T_STRING) && $tokens[$variablePartIndex + 1]->equals(']')) { + $tokens[$variablePartIndex] = new Token([T_CONSTANT_ENCAPSED_STRING, "'".$variablePartToken->getContent()."'"]); + } + } + + $tokens->insertAt($distinctVariableSet['lastVariableTokenIndex'] + 1, new Token([CT::T_CURLY_CLOSE, '}'])); + $tokens->insertAt($distinctVariableSet['firstVariableTokenIndex'], new Token([T_CURLY_OPEN, '{'])); + } + } + } + } + + /** + * Check if token is a part of a string. + * + * @param Token $token The token to check + */ + private function isStringPartToken(Token $token): bool + { + return $token->isGivenKind(T_ENCAPSED_AND_WHITESPACE) + || $token->isGivenKind(T_START_HEREDOC) + || '"' === $token->getContent() + || 'b"' === strtolower($token->getContent()); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/HeredocToNowdocFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/HeredocToNowdocFixer.php new file mode 100644 index 00000000..88add2d5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/HeredocToNowdocFixer.php @@ -0,0 +1,107 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Gregor Harlan + */ +final class HeredocToNowdocFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Convert `heredoc` to `nowdoc` where possible.', + [ + new CodeSample( + <<<'EOF' + isTokenKindFound(T_START_HEREDOC); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_START_HEREDOC) || str_contains($token->getContent(), "'")) { + continue; + } + + if ($tokens[$index + 1]->isGivenKind(T_END_HEREDOC)) { + $tokens[$index] = $this->convertToNowdoc($token); + + continue; + } + + if ( + !$tokens[$index + 1]->isGivenKind(T_ENCAPSED_AND_WHITESPACE) + || !$tokens[$index + 2]->isGivenKind(T_END_HEREDOC) + ) { + continue; + } + + $content = $tokens[$index + 1]->getContent(); + // regex: odd number of backslashes, not followed by dollar + if (Preg::match('/(?convertToNowdoc($token); + $content = str_replace(['\\\\', '\\$'], ['\\', '$'], $content); + $tokens[$index + 1] = new Token([ + $tokens[$index + 1]->getId(), + $content, + ]); + } + } + + /** + * Transforms the heredoc start token to nowdoc notation. + */ + private function convertToNowdoc(Token $token): Token + { + return new Token([ + $token->getId(), + Preg::replace('/^([Bb]?<<<)(\h*)"?([^\s"]+)"?/', '$1$2\'$3\'', $token->getContent()), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoBinaryStringFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoBinaryStringFixer.php new file mode 100644 index 00000000..3c41ab5b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoBinaryStringFixer.php @@ -0,0 +1,75 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author ntzm + */ +final class NoBinaryStringFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound( + [ + T_CONSTANT_ENCAPSED_STRING, + T_START_HEREDOC, + 'b"', + ] + ); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be a binary flag before strings.', + [ + new CodeSample(" $token) { + if ($token->isGivenKind([T_CONSTANT_ENCAPSED_STRING, T_START_HEREDOC])) { + $content = $token->getContent(); + + if ('b' === strtolower($content[0])) { + $tokens[$index] = new Token([$token->getId(), substr($content, 1)]); + } + } elseif ($token->equals('b"')) { + $tokens[$index] = new Token('"'); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.php new file mode 100644 index 00000000..5e046073 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.php @@ -0,0 +1,100 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Gregor Harlan + */ +final class NoTrailingWhitespaceInStringFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE, T_INLINE_HTML]); + } + + public function isRisky(): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There must be no trailing whitespace in strings.', + [ + new CodeSample( + "count() - 1, $last = true; $index >= 0; --$index, $last = false) { + /** @var Token $token */ + $token = $tokens[$index]; + + if (!$token->isGivenKind([T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE, T_INLINE_HTML])) { + continue; + } + + $isInlineHtml = $token->isGivenKind(T_INLINE_HTML); + $regex = $isInlineHtml && $last ? '/\h+(?=\R|$)/' : '/\h+(?=\R)/'; + $content = Preg::replace($regex, '', $token->getContent()); + + if ($token->getContent() === $content) { + continue; + } + + if (!$isInlineHtml || 0 === $index) { + $this->updateContent($tokens, $index, $content); + + continue; + } + + $prev = $index - 1; + + if ($tokens[$prev]->equals([T_CLOSE_TAG, '?>']) && Preg::match('/^\R/', $content, $match)) { + $tokens[$prev] = new Token([T_CLOSE_TAG, $tokens[$prev]->getContent().$match[0]]); + $content = substr($content, \strlen($match[0])); + $content = false === $content ? '' : $content; // @phpstan-ignore-line due to https://github.com/phpstan/phpstan/issues/1215 , awaiting PHP8 as min requirement of Fixer + } + + $this->updateContent($tokens, $index, $content); + } + } + + private function updateContent(Tokens $tokens, int $index, string $content): void + { + if ('' === $content) { + $tokens->clearAt($index); + + return; + } + + $tokens[$index] = new Token([$tokens[$index]->getId(), $content]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php new file mode 100644 index 00000000..75891ac0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php @@ -0,0 +1,110 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dave van der Brugge + */ +final class SimpleToComplexStringVariableFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts explicit variables in double-quoted strings and heredoc syntax from simple to complex format (`${` to `{$`).', + [ + new CodeSample( + <<<'EOT' + isTokenKindFound(T_DOLLAR_OPEN_CURLY_BRACES); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 3; $index > 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(T_DOLLAR_OPEN_CURLY_BRACES)) { + continue; + } + + $varnameToken = $tokens[$index + 1]; + + if (!$varnameToken->isGivenKind(T_STRING_VARNAME)) { + continue; + } + + $dollarCloseToken = $tokens[$index + 2]; + + if (!$dollarCloseToken->isGivenKind(CT::T_DOLLAR_CLOSE_CURLY_BRACES)) { + continue; + } + + $tokenOfStringBeforeToken = $tokens[$index - 1]; + $stringContent = $tokenOfStringBeforeToken->getContent(); + + if (str_ends_with($stringContent, '$') && !str_ends_with($stringContent, '\\$')) { + $newContent = substr($stringContent, 0, -1).'\\$'; + $tokenOfStringBeforeToken = new Token([T_ENCAPSED_AND_WHITESPACE, $newContent]); + } + + $tokens->overrideRange($index - 1, $index + 2, [ + $tokenOfStringBeforeToken, + new Token([T_CURLY_OPEN, '{']), + new Token([T_VARIABLE, '$'.$varnameToken->getContent()]), + new Token([CT::T_CURLY_CLOSE, '}']), + ]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SingleQuoteFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SingleQuoteFixer.php new file mode 100644 index 00000000..ab3d7ddd --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SingleQuoteFixer.php @@ -0,0 +1,109 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Gregor Harlan + */ +final class SingleQuoteFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + $codeSample = <<<'EOF' + true] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoUselessConcatOperatorFixer. + * Must run after BacktickToShellExecFixer, EscapeImplicitBackslashesFixer. + */ + public function getPriority(): int + { + return 10; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_CONSTANT_ENCAPSED_STRING); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) { + continue; + } + + $content = $token->getContent(); + $prefix = ''; + + if ('b' === strtolower($content[0])) { + $prefix = $content[0]; + $content = substr($content, 1); + } + + if ( + '"' === $content[0] + && (true === $this->configuration['strings_containing_single_quote_chars'] || !str_contains($content, "'")) + // regex: odd number of backslashes, not followed by double quote or dollar + && !Preg::match('/(?setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLengthToEmptyFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLengthToEmptyFixer.php new file mode 100644 index 00000000..361cc73c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLengthToEmptyFixer.php @@ -0,0 +1,322 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class StringLengthToEmptyFixer extends AbstractFunctionReferenceFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'String tests for empty must be done against `\'\'`, not with `strlen`.', + [new CodeSample("findStrLengthCalls($tokens) as $candidate) { + [$functionNameIndex, $openParenthesisIndex, $closeParenthesisIndex] = $candidate; + $arguments = $argumentsAnalyzer->getArguments($tokens, $openParenthesisIndex, $closeParenthesisIndex); + + if (1 !== \count($arguments)) { + continue; // must be one argument + } + + // test for leading `\` before `strlen` call + + $nextIndex = $tokens->getNextMeaningfulToken($closeParenthesisIndex); + $previousIndex = $tokens->getPrevMeaningfulToken($functionNameIndex); + + if ($tokens[$previousIndex]->isGivenKind(T_NS_SEPARATOR)) { + $namespaceSeparatorIndex = $previousIndex; + $previousIndex = $tokens->getPrevMeaningfulToken($previousIndex); + } else { + $namespaceSeparatorIndex = null; + } + + // test for yoda vs non-yoda fix case + + if ($this->isOperatorOfInterest($tokens[$previousIndex])) { // test if valid yoda case to fix + $operatorIndex = $previousIndex; + $operandIndex = $tokens->getPrevMeaningfulToken($previousIndex); + + if (!$this->isOperandOfInterest($tokens[$operandIndex])) { // test if operand is `0` or `1` + continue; + } + + $replacement = $this->getReplacementYoda($tokens[$operatorIndex], $tokens[$operandIndex]); + + if (null === $replacement) { + continue; + } + + if ($this->isOfHigherPrecedence($tokens[$nextIndex])) { // is of higher precedence right; continue + continue; + } + + if ($this->isOfHigherPrecedence($tokens[$tokens->getPrevMeaningfulToken($operandIndex)])) { // is of higher precedence left; continue + continue; + } + } elseif ($this->isOperatorOfInterest($tokens[$nextIndex])) { // test if valid !yoda case to fix + $operatorIndex = $nextIndex; + $operandIndex = $tokens->getNextMeaningfulToken($nextIndex); + + if (!$this->isOperandOfInterest($tokens[$operandIndex])) { // test if operand is `0` or `1` + continue; + } + + $replacement = $this->getReplacementNotYoda($tokens[$operatorIndex], $tokens[$operandIndex]); + + if (null === $replacement) { + continue; + } + + if ($this->isOfHigherPrecedence($tokens[$tokens->getNextMeaningfulToken($operandIndex)])) { // is of higher precedence right; continue + continue; + } + + if ($this->isOfHigherPrecedence($tokens[$previousIndex])) { // is of higher precedence left; continue + continue; + } + } else { + continue; + } + + // prepare for fixing + + $keepParentheses = $this->keepParentheses($tokens, $openParenthesisIndex, $closeParenthesisIndex); + + if (T_IS_IDENTICAL === $replacement) { + $operandContent = '==='; + } else { // T_IS_NOT_IDENTICAL === $replacement + $operandContent = '!=='; + } + + // apply fixing + + $tokens[$operandIndex] = new Token([T_CONSTANT_ENCAPSED_STRING, "''"]); + $tokens[$operatorIndex] = new Token([$replacement, $operandContent]); + + if (!$keepParentheses) { + $tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesisIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesisIndex); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($functionNameIndex); + + if (null !== $namespaceSeparatorIndex) { + $tokens->clearTokenAndMergeSurroundingWhitespace($namespaceSeparatorIndex); + } + } + } + + private function getReplacementYoda(Token $operator, Token $operand): ?int + { + /* Yoda 0 + + 0 === strlen($b) | '' === $b + 0 !== strlen($b) | '' !== $b + 0 <= strlen($b) | X makes no sense, assume overridden + 0 >= strlen($b) | '' === $b + 0 < strlen($b) | '' !== $b + 0 > strlen($b) | X makes no sense, assume overridden + */ + + if ('0' === $operand->getContent()) { + if ($operator->isGivenKind([T_IS_IDENTICAL, T_IS_GREATER_OR_EQUAL])) { + return T_IS_IDENTICAL; + } + + if ($operator->isGivenKind(T_IS_NOT_IDENTICAL) || $operator->equals('<')) { + return T_IS_NOT_IDENTICAL; + } + + return null; + } + + /* Yoda 1 + + 1 === strlen($b) | X cannot simplify + 1 !== strlen($b) | X cannot simplify + 1 <= strlen($b) | '' !== $b + 1 >= strlen($b) | cannot simplify + 1 < strlen($b) | cannot simplify + 1 > strlen($b) | '' === $b + */ + + if ($operator->isGivenKind(T_IS_SMALLER_OR_EQUAL)) { + return T_IS_NOT_IDENTICAL; + } + + if ($operator->equals('>')) { + return T_IS_IDENTICAL; + } + + return null; + } + + private function getReplacementNotYoda(Token $operator, Token $operand): ?int + { + /* Not Yoda 0 + + strlen($b) === 0 | $b === '' + strlen($b) !== 0 | $b !== '' + strlen($b) <= 0 | $b === '' + strlen($b) >= 0 | X makes no sense, assume overridden + strlen($b) < 0 | X makes no sense, assume overridden + strlen($b) > 0 | $b !== '' + */ + + if ('0' === $operand->getContent()) { + if ($operator->isGivenKind([T_IS_IDENTICAL, T_IS_SMALLER_OR_EQUAL])) { + return T_IS_IDENTICAL; + } + + if ($operator->isGivenKind(T_IS_NOT_IDENTICAL) || $operator->equals('>')) { + return T_IS_NOT_IDENTICAL; + } + + return null; + } + + /* Not Yoda 1 + + strlen($b) === 1 | X cannot simplify + strlen($b) !== 1 | X cannot simplify + strlen($b) <= 1 | X cannot simplify + strlen($b) >= 1 | $b !== '' + strlen($b) < 1 | $b === '' + strlen($b) > 1 | X cannot simplify + */ + + if ($operator->isGivenKind(T_IS_GREATER_OR_EQUAL)) { + return T_IS_NOT_IDENTICAL; + } + + if ($operator->equals('<')) { + return T_IS_IDENTICAL; + } + + return null; + } + + private function isOperandOfInterest(Token $token): bool + { + if (!$token->isGivenKind(T_LNUMBER)) { + return false; + } + + $content = $token->getContent(); + + return '0' === $content || '1' === $content; + } + + private function isOperatorOfInterest(Token $token): bool + { + return + $token->isGivenKind([T_IS_IDENTICAL, T_IS_NOT_IDENTICAL, T_IS_SMALLER_OR_EQUAL, T_IS_GREATER_OR_EQUAL]) + || $token->equals('<') || $token->equals('>'); + } + + private function isOfHigherPrecedence(Token $token): bool + { + static $operatorsPerContent = [ + '!', + '%', + '*', + '+', + '-', + '.', + '/', + '~', + '?', + ]; + + return $token->isGivenKind([T_INSTANCEOF, T_POW, T_SL, T_SR]) || $token->equalsAny($operatorsPerContent); + } + + private function keepParentheses(Tokens $tokens, int $openParenthesisIndex, int $closeParenthesisIndex): bool + { + $i = $tokens->getNextMeaningfulToken($openParenthesisIndex); + + if ($tokens[$i]->isCast()) { + $i = $tokens->getNextMeaningfulToken($i); + } + + for (; $i < $closeParenthesisIndex; ++$i) { + $token = $tokens[$i]; + + if ($token->isGivenKind([T_VARIABLE, T_STRING]) || $token->isObjectOperator() || $token->isWhitespace() || $token->isComment()) { + continue; + } + + $blockType = Tokens::detectBlockType($token); + + if (null !== $blockType && $blockType['isStart']) { + $i = $tokens->findBlockEnd($blockType['type'], $i); + + continue; + } + + return true; + } + + return false; + } + + private function findStrLengthCalls(Tokens $tokens): \Generator + { + $candidates = []; + $count = \count($tokens); + + for ($i = 0; $i < $count; ++$i) { + $candidate = $this->find('strlen', $tokens, $i, $count); + + if (null === $candidate) { + break; + } + + $i = $candidate[1]; // proceed to openParenthesisIndex + $candidates[] = $candidate; + } + + foreach (array_reverse($candidates) as $candidate) { + yield $candidate; + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLineEndingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLineEndingFixer.php new file mode 100644 index 00000000..aae69262 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLineEndingFixer.php @@ -0,0 +1,76 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixes the line endings in multi-line strings. + * + * @author Ilija Tovilo + */ +final class StringLineEndingFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE, T_INLINE_HTML]); + } + + public function isRisky(): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'All multi-line strings must use correct line ending.', + [ + new CodeSample( + "whitespacesConfig->getLineEnding(); + + foreach ($tokens as $tokenIndex => $token) { + if (!$token->isGivenKind([T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE, T_INLINE_HTML])) { + continue; + } + + $tokens[$tokenIndex] = new Token([ + $token->getId(), + Preg::replace( + '#\R#u', + $ending, + $token->getContent() + ), + ]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/ArrayIndentationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/ArrayIndentationFixer.php new file mode 100644 index 00000000..80ef9ef9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/ArrayIndentationFixer.php @@ -0,0 +1,197 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\Indentation; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class ArrayIndentationFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + use Indentation; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Each element of an array must be indented exactly once.', + [ + new CodeSample(" [\n 'baz' => true,\n ],\n];\n"), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([T_ARRAY, T_LIST, CT::T_ARRAY_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN]); + } + + /** + * {@inheritdoc} + * + * Must run before AlignMultilineCommentFixer, BinaryOperatorSpacesFixer. + * Must run after MethodArgumentSpaceFixer. + */ + public function getPriority(): int + { + return 29; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $lastIndent = ''; + $scopes = []; + $previousLineInitialIndent = ''; + $previousLineNewIndent = ''; + + foreach ($tokens as $index => $token) { + $currentScope = [] !== $scopes ? \count($scopes) - 1 : null; + + if ($token->isComment()) { + continue; + } + + if ( + $token->isGivenKind([CT::T_ARRAY_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN]) + || ($token->equals('(') && $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind([T_ARRAY, T_LIST])) + ) { + $blockType = Tokens::detectBlockType($token); + $endIndex = $tokens->findBlockEnd($blockType['type'], $index); + + $scopes[] = [ + 'type' => 'array', + 'end_index' => $endIndex, + 'initial_indent' => $lastIndent, + ]; + + continue; + } + + if ($this->isNewLineToken($tokens, $index)) { + $lastIndent = $this->extractIndent($this->computeNewLineContent($tokens, $index)); + } + + if (null === $currentScope) { + continue; + } + + if ($token->isWhitespace()) { + if (!Preg::match('/\R/', $token->getContent())) { + continue; + } + + if ('array' === $scopes[$currentScope]['type']) { + $indent = false; + + for ($searchEndIndex = $index + 1; $searchEndIndex < $scopes[$currentScope]['end_index']; ++$searchEndIndex) { + $searchEndToken = $tokens[$searchEndIndex]; + + if ( + (!$searchEndToken->isWhitespace() && !$searchEndToken->isComment()) + || ($searchEndToken->isWhitespace() && Preg::match('/\R/', $searchEndToken->getContent())) + ) { + $indent = true; + + break; + } + } + + $content = Preg::replace( + '/(\R+)\h*$/', + '$1'.$scopes[$currentScope]['initial_indent'].($indent ? $this->whitespacesConfig->getIndent() : ''), + $token->getContent() + ); + + $previousLineInitialIndent = $this->extractIndent($token->getContent()); + $previousLineNewIndent = $this->extractIndent($content); + } else { + $content = Preg::replace( + '/(\R)'.preg_quote($scopes[$currentScope]['initial_indent'], '/').'(\h*)$/', + '$1'.$scopes[$currentScope]['new_indent'].'$2', + $token->getContent() + ); + } + + $tokens[$index] = new Token([T_WHITESPACE, $content]); + $lastIndent = $this->extractIndent($content); + + continue; + } + + if ($index === $scopes[$currentScope]['end_index']) { + while ([] !== $scopes && $index === $scopes[$currentScope]['end_index']) { + array_pop($scopes); + --$currentScope; + } + + continue; + } + + if ($token->equals(',')) { + continue; + } + + if ('expression' !== $scopes[$currentScope]['type']) { + $endIndex = $this->findExpressionEndIndex($tokens, $index, $scopes[$currentScope]['end_index']); + + if ($endIndex === $index) { + continue; + } + + $scopes[] = [ + 'type' => 'expression', + 'end_index' => $endIndex, + 'initial_indent' => $previousLineInitialIndent, + 'new_indent' => $previousLineNewIndent, + ]; + } + } + } + + private function findExpressionEndIndex(Tokens $tokens, int $index, int $parentScopeEndIndex): int + { + $endIndex = null; + + for ($searchEndIndex = $index + 1; $searchEndIndex < $parentScopeEndIndex; ++$searchEndIndex) { + $searchEndToken = $tokens[$searchEndIndex]; + + if ($searchEndToken->equalsAny(['(', '{']) + || $searchEndToken->isGivenKind([CT::T_ARRAY_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN]) + ) { + $type = Tokens::detectBlockType($searchEndToken); + $searchEndIndex = $tokens->findBlockEnd( + $type['type'], + $searchEndIndex + ); + + continue; + } + + if ($searchEndToken->equals(',')) { + $endIndex = $tokens->getPrevMeaningfulToken($searchEndIndex); + + break; + } + } + + return $endIndex ?? $tokens->getPrevMeaningfulToken($parentScopeEndIndex); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php new file mode 100644 index 00000000..8434490f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php @@ -0,0 +1,368 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Dariusz Rumiński + * @author Andreas Möller + */ +final class BlankLineBeforeStatementFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @var array + */ + private static array $tokenMap = [ + 'break' => T_BREAK, + 'case' => T_CASE, + 'continue' => T_CONTINUE, + 'declare' => T_DECLARE, + 'default' => T_DEFAULT, + 'do' => T_DO, + 'exit' => T_EXIT, + 'for' => T_FOR, + 'foreach' => T_FOREACH, + 'goto' => T_GOTO, + 'if' => T_IF, + 'include' => T_INCLUDE, + 'include_once' => T_INCLUDE_ONCE, + 'phpdoc' => T_DOC_COMMENT, + 'require' => T_REQUIRE, + 'require_once' => T_REQUIRE_ONCE, + 'return' => T_RETURN, + 'switch' => T_SWITCH, + 'throw' => T_THROW, + 'try' => T_TRY, + 'while' => T_WHILE, + 'yield' => T_YIELD, + 'yield_from' => T_YIELD_FROM, + ]; + + /** + * @var list + */ + private array $fixTokenMap = []; + + public function configure(array $configuration): void + { + parent::configure($configuration); + + $this->fixTokenMap = []; + + foreach ($this->configuration['statements'] as $key) { + $this->fixTokenMap[$key] = self::$tokenMap[$key]; + } + + $this->fixTokenMap = array_values($this->fixTokenMap); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'An empty line feed must precede any configured statement.', + [ + new CodeSample( + 'process(); + break; + case 44: + break; +} +', + [ + 'statements' => ['break'], + ] + ), + new CodeSample( + 'isTired()) { + $bar->sleep(); + continue; + } +} +', + [ + 'statements' => ['continue'], + ] + ), + new CodeSample( + ' 0); +', + [ + 'statements' => ['do'], + ] + ), + new CodeSample( + ' ['exit'], + ] + ), + new CodeSample( + ' ['goto'], + ] + ), + new CodeSample( + ' ['if'], + ] + ), + new CodeSample( + ' ['return'], + ] + ), + new CodeSample( + ' ['switch'], + ] + ), + new CodeSample( + 'bar(); + throw new \UnexpectedValueException("A cannot be null."); +} +', + [ + 'statements' => ['throw'], + ] + ), + new CodeSample( + 'bar(); +} catch (\Exception $exception) { + $a = -1; +} +', + [ + 'statements' => ['try'], + ] + ), + new CodeSample( + ' ['yield'], + ] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run after NoExtraBlankLinesFixer, NoUselessElseFixer, NoUselessReturnFixer, ReturnAssignmentFixer, YieldFromArrayToYieldsFixer. + */ + public function getPriority(): int + { + return -21; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound($this->fixTokenMap); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $analyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind($this->fixTokenMap)) { + continue; + } + + if ($token->isGivenKind(T_WHILE) && $analyzer->isWhilePartOfDoWhile($index)) { + continue; + } + + if ($token->isGivenKind(T_CASE) && $analyzer->isEnumCase($index)) { + continue; + } + + $insertBlankLineIndex = $this->getInsertBlankLineIndex($tokens, $index); + $prevNonWhitespace = $tokens->getPrevNonWhitespace($insertBlankLineIndex); + + if ($this->shouldAddBlankLine($tokens, $prevNonWhitespace)) { + $this->insertBlankLine($tokens, $insertBlankLineIndex); + } + + $index = $prevNonWhitespace; + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('statements', 'List of statements which must be preceded by an empty line.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset(array_keys(self::$tokenMap))]) + ->setDefault([ + 'break', + 'continue', + 'declare', + 'return', + 'throw', + 'try', + ]) + ->getOption(), + ]); + } + + private function getInsertBlankLineIndex(Tokens $tokens, int $index): int + { + while ($index > 0) { + if ($tokens[$index - 1]->isWhitespace() && substr_count($tokens[$index - 1]->getContent(), "\n") > 1) { + break; + } + + $prevIndex = $tokens->getPrevNonWhitespace($index); + + if (!$tokens[$prevIndex]->isComment()) { + break; + } + + if (!$tokens[$prevIndex - 1]->isWhitespace()) { + break; + } + + if (1 !== substr_count($tokens[$prevIndex - 1]->getContent(), "\n")) { + break; + } + + $index = $prevIndex; + } + + return $index; + } + + private function shouldAddBlankLine(Tokens $tokens, int $prevNonWhitespace): bool + { + $prevNonWhitespaceToken = $tokens[$prevNonWhitespace]; + + if ($prevNonWhitespaceToken->isComment()) { + for ($j = $prevNonWhitespace - 1; $j >= 0; --$j) { + if (str_contains($tokens[$j]->getContent(), "\n")) { + return false; + } + + if ($tokens[$j]->isWhitespace() || $tokens[$j]->isComment()) { + continue; + } + + return $tokens[$j]->equalsAny([';', '}']); + } + } + + return $prevNonWhitespaceToken->equalsAny([';', '}']); + } + + private function insertBlankLine(Tokens $tokens, int $index): void + { + $prevIndex = $index - 1; + $prevToken = $tokens[$prevIndex]; + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + if ($prevToken->isWhitespace()) { + $newlinesCount = substr_count($prevToken->getContent(), "\n"); + + if (0 === $newlinesCount) { + $tokens[$prevIndex] = new Token([T_WHITESPACE, rtrim($prevToken->getContent(), " \t").$lineEnding.$lineEnding]); + } elseif (1 === $newlinesCount) { + $tokens[$prevIndex] = new Token([T_WHITESPACE, $lineEnding.$prevToken->getContent()]); + } + } else { + $tokens->insertAt($index, new Token([T_WHITESPACE, $lineEnding.$lineEnding])); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBetweenImportGroupsFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBetweenImportGroupsFixer.php new file mode 100644 index 00000000..1976aefb --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBetweenImportGroupsFixer.php @@ -0,0 +1,180 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Sander Verkuil + */ +final class BlankLineBetweenImportGroupsFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + private const IMPORT_TYPE_CLASS = 'class'; + + private const IMPORT_TYPE_CONST = 'const'; + + private const IMPORT_TYPE_FUNCTION = 'function'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Putting blank lines between `use` statement groups.', + [ + new CodeSample( + 'isTokenKindFound(T_USE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $namespacesImports = $tokensAnalyzer->getImportUseIndexes(true); + + foreach (array_reverse($namespacesImports) as $uses) { + $this->walkOverUses($tokens, $uses); + } + } + + /** + * @param int[] $uses + */ + private function walkOverUses(Tokens $tokens, array $uses): void + { + $usesCount = \count($uses); + + if ($usesCount < 2) { + return; // nothing to fix + } + + $previousType = null; + + for ($i = $usesCount - 1; $i >= 0; --$i) { + $index = $uses[$i]; + $startIndex = $tokens->getNextMeaningfulToken($index + 1); + $endIndex = $tokens->getNextTokenOfKind($startIndex, [';', [T_CLOSE_TAG]]); + + if ($tokens[$startIndex]->isGivenKind(CT::T_CONST_IMPORT)) { + $type = self::IMPORT_TYPE_CONST; + } elseif ($tokens[$startIndex]->isGivenKind(CT::T_FUNCTION_IMPORT)) { + $type = self::IMPORT_TYPE_FUNCTION; + } else { + $type = self::IMPORT_TYPE_CLASS; + } + + if (null !== $previousType && $type !== $previousType) { + $this->ensureLine($tokens, $endIndex + 1); + } + + $previousType = $type; + } + } + + private function ensureLine(Tokens $tokens, int $index): void + { + static $lineEnding; + + if (null === $lineEnding) { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + $lineEnding .= $lineEnding; + } + + $index = $this->getInsertIndex($tokens, $index); + $indent = WhitespacesAnalyzer::detectIndent($tokens, $index); + + $tokens->ensureWhitespaceAtIndex($index, 1, $lineEnding.$indent); + } + + private function getInsertIndex(Tokens $tokens, int $index): int + { + $tokensCount = \count($tokens); + + for (; $index < $tokensCount - 1; ++$index) { + if (!$tokens[$index]->isWhitespace() && !$tokens[$index]->isComment()) { + return $index - 1; + } + + $content = $tokens[$index]->getContent(); + + if (str_contains($content, "\n")) { + return $index; + } + } + + return $index; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypeDeclarationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypeDeclarationFixer.php new file mode 100644 index 00000000..e1af647e --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypeDeclarationFixer.php @@ -0,0 +1,72 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Jack Cherng + */ +final class CompactNullableTypeDeclarationFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Remove extra spaces in a nullable type declaration.', + [ + new CodeSample( + "isTokenKindFound(CT::T_NULLABLE_TYPE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + static $typehintKinds = [ + CT::T_ARRAY_TYPEHINT, + T_CALLABLE, + T_NS_SEPARATOR, + T_STATIC, + T_STRING, + ]; + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (!$tokens[$index]->isGivenKind(CT::T_NULLABLE_TYPE)) { + continue; + } + + // remove whitespaces only if there are only whitespaces + // between '?' and the variable type + if ( + $tokens[$index + 1]->isWhitespace() + && $tokens[$index + 2]->isGivenKind($typehintKinds) + ) { + $tokens->removeTrailingWhitespace($index); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypehintFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypehintFixer.php new file mode 100644 index 00000000..89c4ec65 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypehintFixer.php @@ -0,0 +1,63 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @author Jack Cherng + * + * @deprecated + */ +final class CompactNullableTypehintFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + private CompactNullableTypeDeclarationFixer $compactNullableTypeDeclarationFixer; + + public function __construct() + { + $this->compactNullableTypeDeclarationFixer = new CompactNullableTypeDeclarationFixer(); + + parent::__construct(); + } + + public function getDefinition(): FixerDefinitionInterface + { + $fixerDefinition = $this->compactNullableTypeDeclarationFixer->getDefinition(); + + return new FixerDefinition( + 'Remove extra spaces in a nullable typehint.', + $fixerDefinition->getCodeSamples(), + $fixerDefinition->getDescription(), + $fixerDefinition->getRiskyDescription(), + ); + } + + public function getSuccessorsNames(): array + { + return [ + $this->compactNullableTypeDeclarationFixer->getName(), + ]; + } + + protected function createProxyFixers(): array + { + return [ + $this->compactNullableTypeDeclarationFixer, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/HeredocIndentationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/HeredocIndentationFixer.php new file mode 100644 index 00000000..c526d6dd --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/HeredocIndentationFixer.php @@ -0,0 +1,165 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Gregor Harlan + */ +final class HeredocIndentationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Heredoc/nowdoc content must be properly indented.', + [ + new CodeSample( + <<<'SAMPLE' + 'same_as_start'] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run after BracesFixer, StatementIndentationFixer. + */ + public function getPriority(): int + { + return -26; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(T_START_HEREDOC); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('indentation', 'Whether the indentation should be the same as in the start token line or one level more.')) + ->setAllowedValues(['start_plus_one', 'same_as_start']) + ->setDefault('start_plus_one') + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; 0 <= $index; --$index) { + if (!$tokens[$index]->isGivenKind(T_END_HEREDOC)) { + continue; + } + + $end = $index; + $index = $tokens->getPrevTokenOfKind($index, [[T_START_HEREDOC]]); + + $this->fixIndentation($tokens, $index, $end); + } + } + + private function fixIndentation(Tokens $tokens, int $start, int $end): void + { + $indent = WhitespacesAnalyzer::detectIndent($tokens, $start); + + if ('start_plus_one' === $this->configuration['indentation']) { + $indent .= $this->whitespacesConfig->getIndent(); + } + + Preg::match('/^\h*/', $tokens[$end]->getContent(), $matches); + $currentIndent = $matches[0]; + $currentIndentLength = \strlen($currentIndent); + + $content = $indent.substr($tokens[$end]->getContent(), $currentIndentLength); + $tokens[$end] = new Token([T_END_HEREDOC, $content]); + + if ($end === $start + 1) { + return; + } + + for ($index = $end - 1, $last = true; $index > $start; --$index, $last = false) { + if (!$tokens[$index]->isGivenKind([T_ENCAPSED_AND_WHITESPACE, T_WHITESPACE])) { + continue; + } + + $content = $tokens[$index]->getContent(); + + if ('' !== $currentIndent) { + $content = Preg::replace('/(?<=\v)(?!'.$currentIndent.')\h+/', '', $content); + } + + $regexEnd = $last && !$currentIndent ? '(?!\v|$)' : '(?!\v)'; + $content = Preg::replace('/(?<=\v)'.$currentIndent.$regexEnd.'/', $indent, $content); + + $tokens[$index] = new Token([$tokens[$index]->getId(), $content]); + } + + ++$index; + + if (!$tokens[$index]->isGivenKind(T_ENCAPSED_AND_WHITESPACE)) { + $tokens->insertAt($index, new Token([T_ENCAPSED_AND_WHITESPACE, $indent])); + + return; + } + + $content = $tokens[$index]->getContent(); + + if (!\in_array($content[0], ["\r", "\n"], true) && (!$currentIndent || str_starts_with($content, $currentIndent))) { + $content = $indent.substr($content, $currentIndentLength); + } elseif ($currentIndent) { + $content = Preg::replace('/^(?!'.$currentIndent.')\h+/', '', $content); + } + + $tokens[$index] = new Token([T_ENCAPSED_AND_WHITESPACE, $content]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/IndentationTypeFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/IndentationTypeFixer.php new file mode 100644 index 00000000..d88c74ba --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/IndentationTypeFixer.php @@ -0,0 +1,142 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶2.4. + * + * @author Dariusz Rumiński + */ +final class IndentationTypeFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + /** + * @var string + */ + private $indent; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Code MUST use configured indentation type.', + [ + new CodeSample("isAnyTokenKindsFound([T_COMMENT, T_DOC_COMMENT, T_WHITESPACE]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->indent = $this->whitespacesConfig->getIndent(); + + foreach ($tokens as $index => $token) { + if ($token->isComment()) { + $tokens[$index] = $this->fixIndentInComment($tokens, $index); + + continue; + } + + if ($token->isWhitespace()) { + $tokens[$index] = $this->fixIndentToken($tokens, $index); + + continue; + } + } + } + + private function fixIndentInComment(Tokens $tokens, int $index): Token + { + $content = Preg::replace('/^(?:(?getContent(), -1, $count); + + // Also check for more tabs. + while (0 !== $count) { + $content = Preg::replace('/^(\ +)?\t/m', '\1 ', $content, -1, $count); + } + + $indent = $this->indent; + + // change indent to expected one + $content = Preg::replaceCallback('/^(?: )+/m', fn (array $matches): string => $this->getExpectedIndent($matches[0], $indent), $content); + + return new Token([$tokens[$index]->getId(), $content]); + } + + private function fixIndentToken(Tokens $tokens, int $index): Token + { + $content = $tokens[$index]->getContent(); + $previousTokenHasTrailingLinebreak = false; + + // @TODO this can be removed when we have a transformer for "T_OPEN_TAG" to "T_OPEN_TAG + T_WHITESPACE" + if (str_contains($tokens[$index - 1]->getContent(), "\n")) { + $content = "\n".$content; + $previousTokenHasTrailingLinebreak = true; + } + + $indent = $this->indent; + $newContent = Preg::replaceCallback( + '/(\R)(\h+)/', // find indent + function (array $matches) use ($indent): string { + // normalize mixed indent + $content = Preg::replace('/(?:(?getExpectedIndent($content, $indent); + }, + $content + ); + + if ($previousTokenHasTrailingLinebreak) { + $newContent = substr($newContent, 1); + } + + return new Token([T_WHITESPACE, $newContent]); + } + + /** + * @return string mixed + */ + private function getExpectedIndent(string $content, string $indent): string + { + if ("\t" === $indent) { + $content = str_replace(' ', $indent, $content); + } + + return $content; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/LineEndingFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/LineEndingFixer.php new file mode 100644 index 00000000..adc2016f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/LineEndingFixer.php @@ -0,0 +1,85 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶2.2. + * + * @author Fabien Potencier + * @author Dariusz Rumiński + */ +final class LineEndingFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'All PHP files must use same line ending.', + [ + new CodeSample( + "whitespacesConfig->getLineEnding(); + + for ($index = 0, $count = \count($tokens); $index < $count; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(T_ENCAPSED_AND_WHITESPACE)) { + if ($tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(T_END_HEREDOC)) { + $tokens[$index] = new Token([ + $token->getId(), + Preg::replace( + '#\R#', + $ending, + $token->getContent() + ), + ]); + } + + continue; + } + + if ($token->isGivenKind([T_CLOSE_TAG, T_COMMENT, T_DOC_COMMENT, T_OPEN_TAG, T_START_HEREDOC, T_WHITESPACE])) { + $tokens[$index] = new Token([ + $token->getId(), + Preg::replace( + '#\R#', + $ending, + $token->getContent() + ), + ]); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/MethodChainingIndentationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/MethodChainingIndentationFixer.php new file mode 100644 index 00000000..2830246a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/MethodChainingIndentationFixer.php @@ -0,0 +1,211 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Vladimir Boliev + */ +final class MethodChainingIndentationFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Method chaining MUST be properly indented. Method chaining with different levels of indentation is not supported.', + [new CodeSample("setEmail('voff.web@gmail.com')\n ->setPassword('233434');\n")] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getObjectOperatorKinds()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + for ($index = 1, $count = \count($tokens); $index < $count; ++$index) { + if (!$tokens[$index]->isObjectOperator()) { + continue; + } + + $endParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(', ';', ',', [T_CLOSE_TAG]]); + + if (null === $endParenthesisIndex || !$tokens[$endParenthesisIndex]->equals('(')) { + continue; + } + + if ($this->canBeMovedToNextLine($index, $tokens)) { + $newline = new Token([T_WHITESPACE, $lineEnding]); + + if ($tokens[$index - 1]->isWhitespace()) { + $tokens[$index - 1] = $newline; + } else { + $tokens->insertAt($index, $newline); + ++$index; + ++$endParenthesisIndex; + } + } + + $currentIndent = $this->getIndentAt($tokens, $index - 1); + + if (null === $currentIndent) { + continue; + } + + $expectedIndent = $this->getExpectedIndentAt($tokens, $index); + + if ($currentIndent !== $expectedIndent) { + $tokens[$index - 1] = new Token([T_WHITESPACE, $lineEnding.$expectedIndent]); + } + + $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endParenthesisIndex); + + for ($searchIndex = $index + 1; $searchIndex < $endParenthesisIndex; ++$searchIndex) { + $searchToken = $tokens[$searchIndex]; + + if (!$searchToken->isWhitespace()) { + continue; + } + + $content = $searchToken->getContent(); + + if (!Preg::match('/\R/', $content)) { + continue; + } + + $content = Preg::replace( + '/(\R)'.$currentIndent.'(\h*)$/D', + '$1'.$expectedIndent.'$2', + $content + ); + + $tokens[$searchIndex] = new Token([$searchToken->getId(), $content]); + } + } + } + + /** + * @param int $index index of the first token on the line to indent + */ + private function getExpectedIndentAt(Tokens $tokens, int $index): string + { + $index = $tokens->getPrevMeaningfulToken($index); + $indent = $this->whitespacesConfig->getIndent(); + + for ($i = $index; $i >= 0; --$i) { + if ($tokens[$i]->equals(')')) { + $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $i); + } + + $currentIndent = $this->getIndentAt($tokens, $i); + if (null === $currentIndent) { + continue; + } + + if ($this->currentLineRequiresExtraIndentLevel($tokens, $i, $index)) { + return $currentIndent.$indent; + } + + return $currentIndent; + } + + return $indent; + } + + /** + * @param int $index position of the object operator token ("->" or "?->") + */ + private function canBeMovedToNextLine(int $index, Tokens $tokens): bool + { + $prevMeaningful = $tokens->getPrevMeaningfulToken($index); + $hasCommentBefore = false; + + for ($i = $index - 1; $i > $prevMeaningful; --$i) { + if ($tokens[$i]->isComment()) { + $hasCommentBefore = true; + + continue; + } + + if ($tokens[$i]->isWhitespace() && Preg::match('/\R/', $tokens[$i]->getContent())) { + return $hasCommentBefore; + } + } + + return false; + } + + /** + * @param int $index index of the indentation token + */ + private function getIndentAt(Tokens $tokens, int $index): ?string + { + if (Preg::match('/\R{1}(\h*)$/', $this->getIndentContentAt($tokens, $index), $matches)) { + return $matches[1]; + } + + return null; + } + + private function getIndentContentAt(Tokens $tokens, int $index): string + { + if (!$tokens[$index]->isGivenKind([T_WHITESPACE, T_INLINE_HTML])) { + return ''; + } + + $content = $tokens[$index]->getContent(); + + if ($tokens[$index]->isWhitespace() && $tokens[$index - 1]->isGivenKind(T_OPEN_TAG)) { + $content = $tokens[$index - 1]->getContent().$content; + } + + if (Preg::match('/\R/', $content)) { + return $content; + } + + return ''; + } + + /** + * @param int $start index of first meaningful token on previous line + * @param int $end index of last token on previous line + */ + private function currentLineRequiresExtraIndentLevel(Tokens $tokens, int $start, int $end): bool + { + $firstMeaningful = $tokens->getNextMeaningfulToken($start); + + if ($tokens[$firstMeaningful]->isObjectOperator()) { + $thirdMeaningful = $tokens->getNextMeaningfulToken($tokens->getNextMeaningfulToken($firstMeaningful)); + + return + $tokens[$thirdMeaningful]->equals('(') + && $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $thirdMeaningful) > $end; + } + + return + !$tokens[$end]->equals(')') + || $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $end) >= $start; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php new file mode 100644 index 00000000..f01db92b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php @@ -0,0 +1,470 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\SwitchAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; + +/** + * @author Dariusz Rumiński + */ +final class NoExtraBlankLinesFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @var string[] + */ + private static array $availableTokens = [ + 'attribute', + 'break', + 'case', + 'continue', + 'curly_brace_block', + 'default', + 'extra', + 'parenthesis_brace_block', + 'return', + 'square_brace_block', + 'switch', + 'throw', + 'use', + 'use_trait', + ]; + + /** + * @var array key is token id, value is name of callback + */ + private array $tokenKindCallbackMap; + + /** + * @var array token prototype, value is name of callback + */ + private array $tokenEqualsMap; + + private Tokens $tokens; + + private TokensAnalyzer $tokensAnalyzer; + + public function configure(array $configuration): void + { + if (isset($configuration['tokens']) && \in_array('use_trait', $configuration['tokens'], true)) { + Utils::triggerDeprecation(new \RuntimeException('Option "tokens: use_trait" used in `no_extra_blank_lines` rule is deprecated, use the rule `class_attributes_separation` with `elements: trait_import` instead.')); + } + + parent::configure($configuration); + + $tokensConfiguration = $this->configuration['tokens']; + + $this->tokenEqualsMap = []; + + if (\in_array('curly_brace_block', $tokensConfiguration, true)) { + $this->tokenEqualsMap['{'] = 'fixStructureOpenCloseIfMultiLine'; // i.e. not: CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN + } + + if (\in_array('parenthesis_brace_block', $tokensConfiguration, true)) { + $this->tokenEqualsMap['('] = 'fixStructureOpenCloseIfMultiLine'; // i.e. not: CT::T_BRACE_CLASS_INSTANTIATION_OPEN + } + + static $configMap = [ + 'attribute' => [CT::T_ATTRIBUTE_CLOSE, 'fixAfterToken'], + 'break' => [T_BREAK, 'fixAfterToken'], + 'case' => [T_CASE, 'fixAfterCaseToken'], + 'continue' => [T_CONTINUE, 'fixAfterToken'], + 'default' => [T_DEFAULT, 'fixAfterToken'], + 'extra' => [T_WHITESPACE, 'removeMultipleBlankLines'], + 'return' => [T_RETURN, 'fixAfterToken'], + 'square_brace_block' => [CT::T_ARRAY_SQUARE_BRACE_OPEN, 'fixStructureOpenCloseIfMultiLine'], + 'switch' => [T_SWITCH, 'fixAfterToken'], + 'throw' => [T_THROW, 'fixAfterThrowToken'], + 'use' => [T_USE, 'removeBetweenUse'], + 'use_trait' => [CT::T_USE_TRAIT, 'removeBetweenUse'], + ]; + + $this->tokenKindCallbackMap = []; + + foreach ($tokensConfiguration as $config) { + if (isset($configMap[$config])) { + $this->tokenKindCallbackMap[$configMap[$config][0]] = $configMap[$config][1]; + } + } + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes extra blank lines and/or blank lines following configuration.', + [ + new CodeSample( + ' ['break']] + ), + new CodeSample( + ' ['continue']] + ), + new CodeSample( + ' ['curly_brace_block']] + ), + new CodeSample( + ' ['extra']] + ), + new CodeSample( + ' ['parenthesis_brace_block']] + ), + new CodeSample( + ' ['return']] + ), + new CodeSample( + ' ['square_brace_block']] + ), + new CodeSample( + ' ['throw']] + ), + new CodeSample( + ' ['use']] + ), + new CodeSample( + ' ['switch', 'case', 'default']] + ), + ] + ); + } + + /** + * {@inheritdoc} + * + * Must run before BlankLineBeforeStatementFixer. + * Must run after ClassAttributesSeparationFixer, CombineConsecutiveUnsetsFixer, EmptyLoopBodyFixer, EmptyLoopConditionFixer, FunctionToConstantFixer, LongToShorthandOperatorFixer, ModernizeStrposFixer, NoEmptyCommentFixer, NoEmptyPhpdocFixer, NoEmptyStatementFixer, NoUnusedImportsFixer, NoUselessElseFixer, NoUselessReturnFixer, NoUselessSprintfFixer, PhpdocReadonlyClassCommentToKeywordFixer, StringLengthToEmptyFixer, YieldFromArrayToYieldsFixer. + */ + public function getPriority(): int + { + return -20; + } + + public function isCandidate(Tokens $tokens): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->tokens = $tokens; + $this->tokensAnalyzer = new TokensAnalyzer($this->tokens); + + for ($index = $tokens->getSize() - 1; $index > 0; --$index) { + $this->fixByToken($tokens[$index], $index); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('tokens', 'List of tokens to fix.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset(self::$availableTokens)]) + ->setDefault(['extra']) + ->getOption(), + ]); + } + + private function fixByToken(Token $token, int $index): void + { + foreach ($this->tokenKindCallbackMap as $kind => $callback) { + if (!$token->isGivenKind($kind)) { + continue; + } + + $this->{$callback}($index); + + return; + } + + foreach ($this->tokenEqualsMap as $equals => $callback) { + if (!$token->equals($equals)) { + continue; + } + + $this->{$callback}($index); + + return; + } + } + + private function removeBetweenUse(int $index): void + { + $next = $this->tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]); + + if (null === $next || $this->tokens[$next]->isGivenKind(T_CLOSE_TAG)) { + return; + } + + $nextUseCandidate = $this->tokens->getNextMeaningfulToken($next); + + if (null === $nextUseCandidate || !$this->tokens[$nextUseCandidate]->isGivenKind($this->tokens[$index]->getId()) || !$this->containsLinebreak($index, $nextUseCandidate)) { + return; + } + + $this->removeEmptyLinesAfterLineWithTokenAt($next); + } + + private function removeMultipleBlankLines(int $index): void + { + $expected = $this->tokens[$index - 1]->isGivenKind(T_OPEN_TAG) && Preg::match('/\R$/', $this->tokens[$index - 1]->getContent()) ? 1 : 2; + + $parts = Preg::split('/(.*\R)/', $this->tokens[$index]->getContent(), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); + $count = \count($parts); + + if ($count > $expected) { + $this->tokens[$index] = new Token([T_WHITESPACE, implode('', \array_slice($parts, 0, $expected)).rtrim($parts[$count - 1], "\r\n")]); + } + } + + private function fixAfterToken(int $index): void + { + for ($i = $index - 1; $i > 0; --$i) { + if ($this->tokens[$i]->isGivenKind(T_FUNCTION) && $this->tokensAnalyzer->isLambda($i)) { + return; + } + + if ($this->tokens[$i]->isGivenKind(T_CLASS) && $this->tokensAnalyzer->isAnonymousClass($i)) { + return; + } + + if ($this->tokens[$i]->isWhitespace() && str_contains($this->tokens[$i]->getContent(), "\n")) { + break; + } + } + + $this->removeEmptyLinesAfterLineWithTokenAt($index); + } + + private function fixAfterCaseToken(int $index): void + { + if (\defined('T_ENUM')) { // @TODO: drop condition when PHP 8.1+ is required + $enumSwitchIndex = $this->tokens->getPrevTokenOfKind($index, [[T_SWITCH], [T_ENUM]]); + + if (!$this->tokens[$enumSwitchIndex]->isGivenKind(T_SWITCH)) { + return; + } + } + + $this->removeEmptyLinesAfterLineWithTokenAt($index); + } + + private function fixAfterThrowToken(int $index): void + { + $prevIndex = $this->tokens->getPrevMeaningfulToken($index); + + if (!$this->tokens[$prevIndex]->equalsAny([';', '{', '}', ':', [T_OPEN_TAG]])) { + return; + } + + if ($this->tokens[$prevIndex]->equals(':') && !SwitchAnalyzer::belongsToSwitch($this->tokens, $prevIndex)) { + return; + } + + $this->fixAfterToken($index); + } + + /** + * Remove white line(s) after the index of a block type, + * but only if the block is not on one line. + * + * @param int $index body start + */ + private function fixStructureOpenCloseIfMultiLine(int $index): void + { + $blockTypeInfo = Tokens::detectBlockType($this->tokens[$index]); + $bodyEnd = $this->tokens->findBlockEnd($blockTypeInfo['type'], $index); + + for ($i = $bodyEnd - 1; $i >= $index; --$i) { + if (str_contains($this->tokens[$i]->getContent(), "\n")) { + $this->removeEmptyLinesAfterLineWithTokenAt($i); + $this->removeEmptyLinesAfterLineWithTokenAt($index); + + break; + } + } + } + + private function removeEmptyLinesAfterLineWithTokenAt(int $index): void + { + // find the line break + $parenthesesDepth = 0; + $tokenCount = \count($this->tokens); + for ($end = $index; $end < $tokenCount; ++$end) { + if ($this->tokens[$end]->equals('(')) { + ++$parenthesesDepth; + + continue; + } + + if ($this->tokens[$end]->equals(')')) { + --$parenthesesDepth; + if ($parenthesesDepth < 0) { + return; + } + + continue; + } + + if ( + $this->tokens[$end]->equals('}') + || str_contains($this->tokens[$end]->getContent(), "\n") + ) { + break; + } + } + + if ($end === $tokenCount) { + return; // not found, early return + } + + $ending = $this->whitespacesConfig->getLineEnding(); + + for ($i = $end; $i < $tokenCount && $this->tokens[$i]->isWhitespace(); ++$i) { + $content = $this->tokens[$i]->getContent(); + + if (substr_count($content, "\n") < 1) { + continue; + } + + $newContent = Preg::replace('/^.*\R(\h*)$/s', $ending.'$1', $content); + + $this->tokens[$i] = new Token([T_WHITESPACE, $newContent]); + } + } + + private function containsLinebreak(int $startIndex, int $endIndex): bool + { + for ($i = $endIndex; $i > $startIndex; --$i) { + if (Preg::match('/\R/', $this->tokens[$i]->getContent())) { + return true; + } + } + + return false; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php new file mode 100644 index 00000000..b3a0849f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php @@ -0,0 +1,99 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Javier Spagnoletti + */ +final class NoSpacesAroundOffsetFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There MUST NOT be spaces around offset braces.', + [ + new CodeSample(" ['inside']]), + new CodeSample(" ['outside']]), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(['[', CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->equalsAny(['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN]])) { + continue; + } + + if (\in_array('inside', $this->configuration['positions'], true)) { + if ($token->equals('[')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index); + } else { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE, $index); + } + + // remove space after opening `[` or `{` + if ($tokens[$index + 1]->isWhitespace(" \t")) { + $tokens->clearAt($index + 1); + } + + // remove space before closing `]` or `}` + if ($tokens[$endIndex - 1]->isWhitespace(" \t")) { + $tokens->clearAt($endIndex - 1); + } + } + + if (\in_array('outside', $this->configuration['positions'], true)) { + $prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($index); + if ($tokens[$prevNonWhitespaceIndex]->isComment()) { + continue; + } + + $tokens->removeLeadingWhitespace($index); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $values = ['inside', 'outside']; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('positions', 'Whether spacing should be fixed inside and/or outside the offset braces.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset($values)]) + ->setDefault($values) + ->getOption(), + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php new file mode 100644 index 00000000..d8507512 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php @@ -0,0 +1,75 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶4.3, ¶4.6, ¶5. + * + * @author Marc Aubé + * @author Dariusz Rumiński + * + * @deprecated in favor of SpacesInsideParenthesisFixer + */ +final class NoSpacesInsideParenthesisFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There MUST NOT be a space after the opening parenthesis. There MUST NOT be a space before the closing parenthesis.', + [ + new CodeSample("proxyFixers); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound('('); + } + + protected function createProxyFixers(): array + { + return [new SpacesInsideParenthesesFixer()]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php new file mode 100644 index 00000000..c21ff39f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php @@ -0,0 +1,104 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶2.3. + * + * Don't add trailing spaces at the end of non-blank lines. + * + * @author Fabien Potencier + * @author Dariusz Rumiński + */ +final class NoTrailingWhitespaceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Remove trailing whitespace at the end of non-blank lines.', + [new CodeSample("= 0; --$index) { + $token = $tokens[$index]; + if ( + $token->isGivenKind(T_OPEN_TAG) + && $tokens->offsetExists($index + 1) + && $tokens[$index + 1]->isWhitespace() + && Preg::match('/(.*)\h$/', $token->getContent(), $openTagMatches) + && Preg::match('/^(\R)(.*)$/s', $tokens[$index + 1]->getContent(), $whitespaceMatches) + ) { + $tokens[$index] = new Token([T_OPEN_TAG, $openTagMatches[1].$whitespaceMatches[1]]); + $tokens->ensureWhitespaceAtIndex($index + 1, 0, $whitespaceMatches[2]); + + continue; + } + + if (!$token->isWhitespace()) { + continue; + } + + $lines = Preg::split('/(\\R+)/', $token->getContent(), -1, PREG_SPLIT_DELIM_CAPTURE); + $linesSize = \count($lines); + + // fix only multiline whitespaces or singleline whitespaces at the end of file + if ($linesSize > 1 || !isset($tokens[$index + 1])) { + if (!$tokens[$index - 1]->isGivenKind(T_OPEN_TAG) || !Preg::match('/(.*)\R$/', $tokens[$index - 1]->getContent())) { + $lines[0] = rtrim($lines[0], " \t"); + } + + for ($i = 1; $i < $linesSize; ++$i) { + $trimmedLine = rtrim($lines[$i], " \t"); + if ('' !== $trimmedLine) { + $lines[$i] = $trimmedLine; + } + } + + $content = implode('', $lines); + if ('' !== $content) { + $tokens[$index] = new Token([$token->getId(), $content]); + } else { + $tokens->clearAt($index); + } + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php new file mode 100644 index 00000000..60217e17 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + */ +final class NoWhitespaceInBlankLineFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Remove trailing whitespace at the end of blank lines.', + [new CodeSample("isWhitespace()) { + $this->fixWhitespaceToken($tokens, $i); + } + } + } + + private function fixWhitespaceToken(Tokens $tokens, int $index): void + { + $content = $tokens[$index]->getContent(); + $lines = Preg::split("/(\r\n|\n)/", $content); + $lineCount = \count($lines); + + if ( + // fix T_WHITESPACES with at least 3 lines (eg `\n \n`) + $lineCount > 2 + // and T_WHITESPACES with at least 2 lines at the end of file or after open tag with linebreak + || ($lineCount > 0 && (!isset($tokens[$index + 1]) || $tokens[$index - 1]->isGivenKind(T_OPEN_TAG))) + ) { + $lMax = isset($tokens[$index + 1]) ? $lineCount - 1 : $lineCount; + + $lStart = 1; + if ($tokens[$index - 1]->isGivenKind(T_OPEN_TAG) && "\n" === substr($tokens[$index - 1]->getContent(), -1)) { + $lStart = 0; + } + + for ($l = $lStart; $l < $lMax; ++$l) { + $lines[$l] = Preg::replace('/^\h+$/', '', $lines[$l]); + } + $content = implode($this->whitespacesConfig->getLineEnding(), $lines); + $tokens->ensureWhitespaceAtIndex($index, 0, $content); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php new file mode 100644 index 00000000..6fbea69d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php @@ -0,0 +1,64 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * A file must always end with a line endings character. + * + * Fixer for rules defined in PSR2 ¶2.2. + * + * @author Fabien Potencier + * @author Dariusz Rumiński + */ +final class SingleBlankLineAtEofFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'A PHP file without end tag must always end with a single empty line feed.', + [ + new CodeSample("count(); + + if ($count > 0 && !$tokens[$count - 1]->isGivenKind([T_INLINE_HTML, T_CLOSE_TAG, T_OPEN_TAG])) { + $tokens->ensureWhitespaceAtIndex($count - 1, 1, $this->whitespacesConfig->getLineEnding()); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SpacesInsideParenthesesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SpacesInsideParenthesesFixer.php new file mode 100644 index 00000000..cf862876 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SpacesInsideParenthesesFixer.php @@ -0,0 +1,208 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶4.3, ¶4.6, ¶5. + * + * @author Marc Aubé + * @author Dariusz Rumiński + */ +final class SpacesInsideParenthesesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Parentheses must be declared using the configured whitespace.', + [ + new CodeSample(" 'none'] + ), + new CodeSample( + " 'single'] + ), + new CodeSample( + " 'single'] + ), + ], + 'By default there are not any additional spaces inside parentheses, however with `space=single` configuration option whitespace inside parentheses will be unified to single space.' + ); + } + + /** + * {@inheritdoc} + * + * Must run before FunctionToConstantFixer, GetClassToClassKeywordFixer, StringLengthToEmptyFixer. + * Must run after CombineConsecutiveIssetsFixer, CombineNestedDirnameFixer, IncrementStyleFixer, LambdaNotUsedImportFixer, ModernizeStrposFixer, NoUselessSprintfFixer, PowToExponentiationFixer. + */ + public function getPriority(): int + { + return 3; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound('('); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if ('none' === $this->configuration['space']) { + foreach ($tokens as $index => $token) { + if (!$token->equals('(')) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + // ignore parenthesis for T_ARRAY + if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(T_ARRAY)) { + continue; + } + + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + + // remove space after opening `(` + if (!$tokens[$tokens->getNextNonWhitespace($index)]->isComment()) { + $this->removeSpaceAroundToken($tokens, $index + 1); + } + + // remove space before closing `)` if it is not `list($a, $b, )` case + if (!$tokens[$tokens->getPrevMeaningfulToken($endIndex)]->equals(',')) { + $this->removeSpaceAroundToken($tokens, $endIndex - 1); + } + } + } + + if ('single' === $this->configuration['space']) { + foreach ($tokens as $index => $token) { + if (!$token->equals('(')) { + continue; + } + + $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + + // if not other content than spaces in block remove spaces + $blockContent = $this->getBlockContent($index, $endParenthesisIndex, $tokens); + if (1 === \count($blockContent) && \in_array(' ', $blockContent, true)) { + $this->removeSpaceAroundToken($tokens, $index + 1); + + continue; + } + + // don't process if the next token is `)` + $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index); + if (')' === $tokens[$nextMeaningfulTokenIndex]->getContent()) { + continue; + } + + $afterParenthesisIndex = $tokens->getNextNonWhitespace($endParenthesisIndex); + $afterParenthesisToken = $tokens[$afterParenthesisIndex]; + + if ($afterParenthesisToken->isGivenKind(CT::T_USE_LAMBDA)) { + $useStartParenthesisIndex = $tokens->getNextTokenOfKind($afterParenthesisIndex, ['(']); + $useEndParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $useStartParenthesisIndex); + + // add single-line edge whitespaces inside use parentheses + $this->fixParenthesisInnerEdge($tokens, $useStartParenthesisIndex, $useEndParenthesisIndex); + } + + // add single-line edge whitespaces inside parameters list parentheses + $this->fixParenthesisInnerEdge($tokens, $index, $endParenthesisIndex); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('space', 'Whether to have `single` or `none` space inside parentheses.')) + ->setAllowedValues(['none', 'single']) + ->setDefault('none') + ->getOption(), + ]); + } + + /** + * Remove spaces from token at a given index. + */ + private function removeSpaceAroundToken(Tokens $tokens, int $index): void + { + $token = $tokens[$index]; + + if ($token->isWhitespace() && !str_contains($token->getContent(), "\n")) { + $tokens->clearAt($index); + } + } + + private function fixParenthesisInnerEdge(Tokens $tokens, int $start, int $end): void + { + // fix white space before ')' + if ($tokens[$end - 1]->isWhitespace()) { + $content = $tokens[$end - 1]->getContent(); + if (' ' !== $content && !str_contains($content, "\n") && !$tokens[$tokens->getPrevNonWhitespace($end - 1)]->isComment()) { + $tokens[$end - 1] = new Token([T_WHITESPACE, ' ']); + } + } else { + $tokens->insertAt($end, new Token([T_WHITESPACE, ' '])); + } + + // fix white space after '(' + if ($tokens[$start + 1]->isWhitespace()) { + $content = $tokens[$start + 1]->getContent(); + if (' ' !== $content && !str_contains($content, "\n") && !$tokens[$tokens->getNextNonWhitespace($start + 1)]->isComment()) { + $tokens[$start + 1] = new Token([T_WHITESPACE, ' ']); + } + } else { + $tokens->insertAt($start + 1, new Token([T_WHITESPACE, ' '])); + } + } + + /** + * @return list + */ + private function getBlockContent(int $startIndex, int $endIndex, Tokens $tokens): array + { + // + 1 for ( + $contents = []; + for ($i = ($startIndex + 1); $i < $endIndex; ++$i) { + $contents[] = $tokens[$i]->getContent(); + } + + return $contents; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/StatementIndentationFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/StatementIndentationFixer.php new file mode 100644 index 00000000..d22d50dd --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/StatementIndentationFixer.php @@ -0,0 +1,658 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\Indentation; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class StatementIndentationFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + use Indentation; + + private AlternativeSyntaxAnalyzer $alternativeSyntaxAnalyzer; + + private bool $bracesFixerCompatibility; + + public function __construct(bool $bracesFixerCompatibility = false) + { + parent::__construct(); + + $this->bracesFixerCompatibility = $bracesFixerCompatibility; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Each statement must be indented.', + [ + new CodeSample( + 'alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer(); + + $blockSignatureFirstTokens = [ + T_USE, + T_IF, + T_ELSE, + T_ELSEIF, + T_FOR, + T_FOREACH, + T_WHILE, + T_SWITCH, + T_CASE, + T_DEFAULT, + T_TRY, + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_EXTENDS, + T_IMPLEMENTS, + ]; + if (\defined('T_MATCH')) { // @TODO: drop condition when PHP 8.0+ is required + $blockSignatureFirstTokens[] = T_MATCH; + } + + $blockFirstTokens = ['{', [CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN], [CT::T_USE_TRAIT], [CT::T_GROUP_IMPORT_BRACE_OPEN]]; + if (\defined('T_ATTRIBUTE')) { // @TODO: drop condition when PHP 8.0+ is required + $blockFirstTokens[] = [T_ATTRIBUTE]; + } + + $endIndex = \count($tokens) - 1; + if ($tokens[$endIndex]->isWhitespace()) { + --$endIndex; + } + + $lastIndent = $this->getLineIndentationWithBracesCompatibility( + $tokens, + 0, + $this->extractIndent($this->computeNewLineContent($tokens, 0)), + ); + + $methodModifierTokens = [ + // https://github.com/php/php-langspec/blob/master/spec/19-grammar.md#grammar-visibility-modifier + T_PUBLIC, + T_PROTECTED, + T_PRIVATE, + // https://github.com/php/php-langspec/blob/master/spec/19-grammar.md#grammar-static-modifier + T_STATIC, + // https://github.com/php/php-langspec/blob/master/spec/19-grammar.md#grammar-class-modifier + T_ABSTRACT, + T_FINAL, + ]; + + $methodModifierIndents = []; + + /** + * @var list $scopes + */ + $scopes = [ + [ + 'type' => 'block', + 'skip' => false, + 'end_index' => $endIndex, + 'end_index_inclusive' => true, + 'initial_indent' => $lastIndent, + 'is_indented_block' => false, + ], + ]; + + $previousLineInitialIndent = ''; + $previousLineNewIndent = ''; + $alternativeBlockStarts = []; + $caseBlockStarts = []; + + foreach ($tokens as $index => $token) { + $currentScope = \count($scopes) - 1; + + if ( + $token->equalsAny($blockFirstTokens) + || ($token->equals('(') && !$tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_ARRAY)) + || isset($alternativeBlockStarts[$index]) + || isset($caseBlockStarts[$index]) + ) { + $endIndexInclusive = true; + + if ($token->isGivenKind([T_EXTENDS, T_IMPLEMENTS])) { + $endIndex = $tokens->getNextTokenOfKind($index, ['{']); + } elseif ($token->isGivenKind(CT::T_USE_TRAIT)) { + $endIndex = $tokens->getNextTokenOfKind($index, [';']); + } elseif ($token->equals(':')) { + if (isset($caseBlockStarts[$index])) { + [$endIndex, $endIndexInclusive] = $this->findCaseBlockEnd($tokens, $index); + } else { + $endIndex = $this->alternativeSyntaxAnalyzer->findAlternativeSyntaxBlockEnd($tokens, $alternativeBlockStarts[$index]); + } + } elseif ($token->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN)) { + $endIndex = $tokens->getNextTokenOfKind($index, [[CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE]]); + } elseif ($token->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + $endIndex = $tokens->getNextTokenOfKind($index, [[CT::T_GROUP_IMPORT_BRACE_CLOSE]]); + } elseif ($token->equals('{')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + } elseif ($token->equals('(')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + } else { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + } + + if ('block_signature' === $scopes[$currentScope]['type']) { + $initialIndent = $scopes[$currentScope]['initial_indent']; + } else { + $initialIndent = $this->getLineIndentationWithBracesCompatibility($tokens, $index, $lastIndent); + } + + $skip = false; + if ($this->bracesFixerCompatibility) { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (null !== $prevIndex) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + } + if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind([T_FUNCTION, T_FN])) { + $skip = true; + } + } + + $scopes[] = [ + 'type' => 'block', + 'skip' => $skip, + 'end_index' => $endIndex, + 'end_index_inclusive' => $endIndexInclusive, + 'initial_indent' => $initialIndent, + 'is_indented_block' => true, + ]; + ++$currentScope; + + while ($index >= $scopes[$currentScope]['end_index']) { + array_pop($scopes); + + --$currentScope; + } + + continue; + } + + if ($token->isGivenKind($blockSignatureFirstTokens)) { + for ($endIndex = $index + 1, $max = \count($tokens); $endIndex < $max; ++$endIndex) { + if ($tokens[$endIndex]->equals('(')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endIndex); + + continue; + } + + if ($tokens[$endIndex]->equalsAny(['{', ';', [T_DOUBLE_ARROW], [T_IMPLEMENTS]])) { + break; + } + + if ($tokens[$endIndex]->equals(':')) { + if ($token->isGivenKind([T_CASE, T_DEFAULT])) { + $caseBlockStarts[$endIndex] = $index; + } else { + $alternativeBlockStarts[$endIndex] = $index; + } + + break; + } + } + + $scopes[] = [ + 'type' => 'block_signature', + 'skip' => false, + 'end_index' => $endIndex, + 'end_index_inclusive' => true, + 'initial_indent' => $this->getLineIndentationWithBracesCompatibility($tokens, $index, $lastIndent), + 'is_indented_block' => $token->isGivenKind([T_EXTENDS, T_IMPLEMENTS]), + ]; + + continue; + } + + if ($token->isGivenKind($methodModifierTokens)) { + $methodModifierIndents[$index] = $lastIndent; + + continue; + } + + if ($token->isGivenKind(T_FUNCTION)) { + $x = $tokens->getPrevMeaningfulToken($index); + while ( + null !== $x + && $tokens[$x]->isGivenKind($methodModifierTokens) + && \array_key_exists($x, $methodModifierIndents) + ) { + $lastIndent = $methodModifierIndents[$x]; + $x = $tokens->getPrevMeaningfulToken($x); + } + + $methodModifierIndents = []; + $endIndex = $index + 1; + + for ($max = \count($tokens); $endIndex < $max; ++$endIndex) { + if ($tokens[$endIndex]->equals('(')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endIndex); + + continue; + } + + if ($tokens[$endIndex]->equalsAny(['{', ';'])) { + break; + } + } + + $scopes[] = [ + 'type' => 'block_signature', + 'skip' => false, + 'end_index' => $endIndex, + 'end_index_inclusive' => true, + 'initial_indent' => $this->getLineIndentationWithBracesCompatibility($tokens, $index, $lastIndent), + 'is_indented_block' => $token->isGivenKind([T_EXTENDS, T_IMPLEMENTS]), + ]; + + continue; + } + + if ( + $token->isWhitespace() + || ($index > 0 && $tokens[$index - 1]->isGivenKind(T_OPEN_TAG)) + ) { + $previousOpenTagContent = $tokens[$index - 1]->isGivenKind(T_OPEN_TAG) + ? Preg::replace('/\S/', '', $tokens[$index - 1]->getContent()) + : ''; + + $content = $previousOpenTagContent.($token->isWhitespace() ? $token->getContent() : ''); + + if (!Preg::match('/\R/', $content)) { + continue; + } + + $nextToken = $tokens[$index + 1] ?? null; + + if ( + $this->bracesFixerCompatibility + && null !== $nextToken + && $nextToken->isComment() + && !$this->isCommentWithFixableIndentation($tokens, $index + 1) + ) { + continue; + } + + if ('block' === $scopes[$currentScope]['type'] || 'block_signature' === $scopes[$currentScope]['type']) { + $indent = false; + + if ($scopes[$currentScope]['is_indented_block']) { + $firstNonWhitespaceTokenIndex = null; + $nextNewlineIndex = null; + for ($searchIndex = $index + 1, $max = \count($tokens); $searchIndex < $max; ++$searchIndex) { + $searchToken = $tokens[$searchIndex]; + + if (!$searchToken->isWhitespace()) { + if (null === $firstNonWhitespaceTokenIndex) { + $firstNonWhitespaceTokenIndex = $searchIndex; + } + + continue; + } + + if (Preg::match('/\R/', $searchToken->getContent())) { + $nextNewlineIndex = $searchIndex; + + break; + } + } + + $endIndex = $scopes[$currentScope]['end_index']; + + if (!$scopes[$currentScope]['end_index_inclusive']) { + ++$endIndex; + } + + if ( + (null !== $firstNonWhitespaceTokenIndex && $firstNonWhitespaceTokenIndex < $endIndex) + || (null !== $nextNewlineIndex && $nextNewlineIndex < $endIndex) + ) { + if ( + // do we touch whitespace directly before comment... + $tokens[$firstNonWhitespaceTokenIndex]->isGivenKind(T_COMMENT) + // ...and afterwards, there is only comment or `}` + && $tokens[$tokens->getNextMeaningfulToken($firstNonWhitespaceTokenIndex)]->equals('}') + ) { + if ( + // ... and the comment was only content in docblock + $tokens[$tokens->getPrevMeaningfulToken($firstNonWhitespaceTokenIndex)]->equals('{') + ) { + $indent = true; + } else { + // or it was dedicated comment for next control loop + // ^^ we need to check if there is a control group afterwards, and in that case don't make extra indent level + $nextIndex = $tokens->getNextMeaningfulToken($firstNonWhitespaceTokenIndex); + $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); + + if (null !== $nextNextIndex && $tokens[$nextNextIndex]->isGivenKind([T_ELSE, T_ELSEIF])) { + $indent = false; + } else { + $indent = true; + } + } + } else { + $indent = true; + } + } + } + + $previousLineInitialIndent = $this->extractIndent($content); + + if ($scopes[$currentScope]['skip']) { + $whitespaces = $previousLineInitialIndent; + } else { + $whitespaces = $scopes[$currentScope]['initial_indent'].($indent ? $this->whitespacesConfig->getIndent() : ''); + } + + $content = Preg::replace( + '/(\R+)\h*$/', + '$1'.$whitespaces, + $content + ); + + $previousLineNewIndent = $this->extractIndent($content); + } else { + $content = Preg::replace( + '/(\R)'.$scopes[$currentScope]['initial_indent'].'(\h*)$/D', + '$1'.$scopes[$currentScope]['new_indent'].'$2', + $content + ); + } + + $lastIndent = $this->extractIndent($content); + + if ('' !== $previousOpenTagContent) { + $content = Preg::replace("/^{$previousOpenTagContent}/", '', $content); + } + + if ('' !== $content) { + $tokens->ensureWhitespaceAtIndex($index, 0, $content); + } elseif ($token->isWhitespace()) { + $tokens->clearAt($index); + } + + if (null !== $nextToken && $nextToken->isComment()) { + $tokens[$index + 1] = new Token([ + $nextToken->getId(), + Preg::replace( + '/(\R)'.preg_quote($previousLineInitialIndent, '/').'(\h*\S+.*)/', + '$1'.$previousLineNewIndent.'$2', + $nextToken->getContent() + ), + ]); + } + + if ($token->isWhitespace()) { + continue; + } + } + + if ($this->isNewLineToken($tokens, $index)) { + $lastIndent = $this->extractIndent($this->computeNewLineContent($tokens, $index)); + } + + while ($index >= $scopes[$currentScope]['end_index']) { + array_pop($scopes); + + if ([] === $scopes) { + return; + } + + --$currentScope; + } + + if ($token->isComment() || $token->equalsAny([';', ',', '}', [T_OPEN_TAG], [T_CLOSE_TAG], [CT::T_ATTRIBUTE_CLOSE]])) { + continue; + } + + if ('statement' !== $scopes[$currentScope]['type'] && 'block_signature' !== $scopes[$currentScope]['type']) { + $endIndex = $this->findStatementEndIndex($tokens, $index, $scopes[$currentScope]['end_index']); + + if ($endIndex === $index) { + continue; + } + + $scopes[] = [ + 'type' => 'statement', + 'skip' => false, + 'end_index' => $endIndex, + 'end_index_inclusive' => false, + 'initial_indent' => $previousLineInitialIndent, + 'new_indent' => $previousLineNewIndent, + ]; + } + } + } + + private function findStatementEndIndex(Tokens $tokens, int $index, int $parentScopeEndIndex): int + { + $endIndex = null; + + for ($searchEndIndex = $index; $searchEndIndex <= $parentScopeEndIndex; ++$searchEndIndex) { + $searchEndToken = $tokens[$searchEndIndex]; + + if ($searchEndToken->equalsAny(['(', '{', [CT::T_ARRAY_SQUARE_BRACE_OPEN]])) { + if ($searchEndToken->equals('(')) { + $blockType = Tokens::BLOCK_TYPE_PARENTHESIS_BRACE; + } elseif ($searchEndToken->equals('{')) { + $blockType = Tokens::BLOCK_TYPE_CURLY_BRACE; + } else { + $blockType = Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE; + } + + $searchEndIndex = $tokens->findBlockEnd($blockType, $searchEndIndex); + + continue; + } + + if ($searchEndToken->equalsAny([';', ',', '}', [T_CLOSE_TAG]])) { + $endIndex = $tokens->getPrevNonWhitespace($searchEndIndex); + + break; + } + } + + return $endIndex ?? $tokens->getPrevMeaningfulToken($parentScopeEndIndex); + } + + /** + * @return array{int, bool} + */ + private function findCaseBlockEnd(Tokens $tokens, int $index): array + { + for ($max = \count($tokens); $index < $max; ++$index) { + if ($tokens[$index]->isGivenKind(T_SWITCH)) { + $braceIndex = $tokens->getNextMeaningfulToken( + $tokens->findBlockEnd( + Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, + $tokens->getNextMeaningfulToken($index) + ) + ); + + if ($tokens[$braceIndex]->equals(':')) { + $index = $this->alternativeSyntaxAnalyzer->findAlternativeSyntaxBlockEnd($tokens, $index); + } else { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $braceIndex); + } + + continue; + } + + if ($tokens[$index]->equals('{')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + + continue; + } + + if ($tokens[$index]->equalsAny([[T_CASE], [T_DEFAULT]])) { + return [$index, true]; + } + + if ($tokens[$index]->equalsAny(['}', [T_ENDSWITCH]])) { + return [$tokens->getPrevNonWhitespace($index), false]; + } + } + + throw new \LogicException('End of case block not found.'); + } + + private function getLineIndentationWithBracesCompatibility(Tokens $tokens, int $index, string $regularIndent): string + { + if ( + $this->bracesFixerCompatibility + && $tokens[$index]->isGivenKind(T_OPEN_TAG) + && Preg::match('/\R/', $tokens[$index]->getContent()) + && isset($tokens[$index + 1]) + && $tokens[$index + 1]->isWhitespace() + && Preg::match('/\h+$/D', $tokens[$index + 1]->getContent()) + ) { + return Preg::replace('/.*?(\h+)$/sD', '$1', $tokens[$index + 1]->getContent()); + } + + return $regularIndent; + } + + /** + * Returns whether the token at given index is a comment whose indentation + * can be fixed. + * + * Indentation of a comment is not changed when the comment is part of a + * multi-line message whose lines are all single-line comments and at least + * one line has meaningful content. + */ + private function isCommentWithFixableIndentation(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->isComment()) { + return false; + } + + if (str_starts_with($tokens[$index]->getContent(), '/*')) { + return true; + } + + $indent = preg_quote($this->whitespacesConfig->getIndent(), '~'); + + if (Preg::match("~^(//|#)({$indent}.*)?$~", $tokens[$index]->getContent())) { + return false; + } + + $firstCommentIndex = $index; + while (true) { + $i = $this->getSiblingContinuousSingleLineComment($tokens, $firstCommentIndex, false); + if (null === $i) { + break; + } + + $firstCommentIndex = $i; + } + + $lastCommentIndex = $index; + while (true) { + $i = $this->getSiblingContinuousSingleLineComment($tokens, $lastCommentIndex, true); + if (null === $i) { + break; + } + + $lastCommentIndex = $i; + } + + if ($firstCommentIndex === $lastCommentIndex) { + return true; + } + + for ($i = $firstCommentIndex + 1; $i < $lastCommentIndex; ++$i) { + if (!$tokens[$i]->isWhitespace() && !$tokens[$i]->isComment()) { + return false; + } + } + + return true; + } + + private function getSiblingContinuousSingleLineComment(Tokens $tokens, int $index, bool $after): ?int + { + $siblingIndex = $index; + do { + if ($after) { + $siblingIndex = $tokens->getNextTokenOfKind($siblingIndex, [[T_COMMENT]]); + } else { + $siblingIndex = $tokens->getPrevTokenOfKind($siblingIndex, [[T_COMMENT]]); + } + + if (null === $siblingIndex) { + return null; + } + } while (str_starts_with($tokens[$siblingIndex]->getContent(), '/*')); + + $newLines = 0; + for ($i = min($siblingIndex, $index) + 1, $max = max($siblingIndex, $index); $i < $max; ++$i) { + if ($tokens[$i]->isWhitespace() && Preg::match('/\R/', $tokens[$i]->getContent())) { + if (1 === $newLines || Preg::match('/\R.*\R/', $tokens[$i]->getContent())) { + return null; + } + + ++$newLines; + } + } + + return $siblingIndex; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypeDeclarationSpacesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypeDeclarationSpacesFixer.php new file mode 100644 index 00000000..29cd7f5a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypeDeclarationSpacesFixer.php @@ -0,0 +1,199 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Dariusz Rumiński + * @author John Paul E. Balandan, CPA + */ +final class TypeDeclarationSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Ensure single space between a variable and its type declaration in function arguments and properties.', + [ + new CodeSample( + ' (string) $c; + } +} +', + ['elements' => ['function']] + ), + new CodeSample( + ' ['property']] + ), + ] + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([...Token::getClassyTokenKinds(), T_FN, T_FUNCTION]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('elements', 'Structural elements where the spacing after the type declaration should be fixed.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([new AllowedValueSubset(['function', 'property'])]) + ->setDefault(['function', 'property']) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + foreach (array_reverse($this->getElements($tokens), true) as $index => $type) { + if ('property' === $type && \in_array('property', $this->configuration['elements'], true)) { + $this->ensureSingleSpaceAtPropertyTypehint($tokens, $index); + + continue; + } + + if ('method' === $type && \in_array('function', $this->configuration['elements'], true)) { + $this->ensureSingleSpaceAtFunctionArgumentTypehint($functionsAnalyzer, $tokens, $index); + + // implicit continue; + } + } + } + + /** + * @return array + * + * @phpstan-return array + */ + private function getElements(Tokens $tokens): array + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $elements = array_map( + static fn (array $element): string => $element['type'], + array_filter( + $tokensAnalyzer->getClassyElements(), + static fn (array $element): bool => \in_array($element['type'], ['method', 'property'], true) + ) + ); + + foreach ($tokens as $index => $token) { + if ( + $token->isGivenKind(T_FN) + || ($token->isGivenKind(T_FUNCTION) && !isset($elements[$index])) + ) { + $elements[$index] = 'method'; + } + } + + return $elements; + } + + private function ensureSingleSpaceAtFunctionArgumentTypehint(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void + { + foreach (array_reverse($functionsAnalyzer->getFunctionArguments($tokens, $index)) as $argumentInfo) { + $argumentType = $argumentInfo->getTypeAnalysis(); + + if (null === $argumentType) { + continue; + } + + $tokens->ensureWhitespaceAtIndex($argumentType->getEndIndex() + 1, 0, ' '); + } + } + + private function ensureSingleSpaceAtPropertyTypehint(Tokens $tokens, int $index): void + { + $propertyIndex = $index; + $propertyModifiers = [T_PRIVATE, T_PROTECTED, T_PUBLIC, T_STATIC, T_VAR]; + + if (\defined('T_READONLY')) { + $propertyModifiers[] = T_READONLY; // @TODO drop condition when PHP 8.1 is supported + } + + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while (!$tokens[$index]->isGivenKind($propertyModifiers)); + + $propertyType = $this->collectTypeAnalysis($tokens, $index, $propertyIndex); + + if (null === $propertyType) { + return; + } + + $tokens->ensureWhitespaceAtIndex($propertyType->getEndIndex() + 1, 0, ' '); + } + + private function collectTypeAnalysis(Tokens $tokens, int $startIndex, int $endIndex): ?TypeAnalysis + { + $type = ''; + $typeStartIndex = $tokens->getNextMeaningfulToken($startIndex); + $typeEndIndex = $typeStartIndex; + + for ($i = $typeStartIndex; $i < $endIndex; ++$i) { + if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { + continue; + } + + $type .= $tokens[$i]->getContent(); + $typeEndIndex = $i; + } + + return '' !== $type ? new TypeAnalysis($type, $typeStartIndex, $typeEndIndex) : null; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypesSpacesFixer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypesSpacesFixer.php new file mode 100644 index 00000000..72d8e77e --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypesSpacesFixer.php @@ -0,0 +1,156 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +final class TypesSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function configure(array $configuration): void + { + parent::configure($configuration); + + if (!isset($this->configuration['space_multiple_catch'])) { + $this->configuration['space_multiple_catch'] = $this->configuration['space']; + } + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'A single space or none should be around union type and intersection type operators.', + [ + new CodeSample( + " 'single'] + ), + new VersionSpecificCodeSample( + "isAnyTokenKindsFound([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('space', 'Spacing to apply around union type and intersection type operators.')) + ->setAllowedValues(['none', 'single']) + ->setDefault('none') + ->getOption(), + (new FixerOptionBuilder('space_multiple_catch', 'Spacing to apply around type operator when catching exceptions of multiple types, use `null` to follow the value configured for `space`.')) + ->setAllowedValues(['none', 'single', null]) + ->setDefault(null) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokenCount = $tokens->count() - 1; + + for ($index = 0; $index < $tokenCount; ++$index) { + if ($tokens[$index]->isGivenKind([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION])) { + $tokenCount += $this->fixSpacing($tokens, $index, 'single' === $this->configuration['space']); + + continue; + } + + if ($tokens[$index]->isGivenKind(T_CATCH)) { + while (true) { + $index = $tokens->getNextTokenOfKind($index, [')', [CT::T_TYPE_ALTERNATION]]); + + if ($tokens[$index]->equals(')')) { + break; + } + + $tokenCount += $this->fixSpacing($tokens, $index, 'single' === $this->configuration['space_multiple_catch']); + } + + // implicit continue + } + } + } + + private function fixSpacing(Tokens $tokens, int $index, bool $singleSpace): int + { + if (!$singleSpace) { + $this->ensureNoSpace($tokens, $index + 1); + $this->ensureNoSpace($tokens, $index - 1); + + return 0; + } + + $addedTokenCount = 0; + $addedTokenCount += $this->ensureSingleSpace($tokens, $index + 1, 0); + $addedTokenCount += $this->ensureSingleSpace($tokens, $index - 1, 1); + + return $addedTokenCount; + } + + private function ensureSingleSpace(Tokens $tokens, int $index, int $offset): int + { + if (!$tokens[$index]->isWhitespace()) { + $tokens->insertSlices([$index + $offset => new Token([T_WHITESPACE, ' '])]); + + return 1; + } + + if (' ' !== $tokens[$index]->getContent() && !Preg::match('/\R/', $tokens[$index]->getContent())) { + $tokens[$index] = new Token([T_WHITESPACE, ' ']); + } + + return 0; + } + + private function ensureNoSpace(Tokens $tokens, int $index): void + { + if ($tokens[$index]->isWhitespace() && !Preg::match('/\R/', $tokens[$index]->getContent())) { + $tokens->clearAt($index); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/WhitespacesAwareFixerInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/WhitespacesAwareFixerInterface.php new file mode 100644 index 00000000..c03a3e78 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Fixer/WhitespacesAwareFixerInterface.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\WhitespacesFixerConfig; + +/** + * @author Dariusz Rumiński + */ +interface WhitespacesAwareFixerInterface extends FixerInterface +{ + public function setWhitespacesConfig(WhitespacesFixerConfig $config): void; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOption.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOption.php new file mode 100644 index 00000000..65a7a3b3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOption.php @@ -0,0 +1,73 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +/** + * @author ntzm + * + * @internal + */ +final class AliasedFixerOption implements FixerOptionInterface +{ + private FixerOptionInterface $fixerOption; + + private string $alias; + + public function __construct(FixerOptionInterface $fixerOption, string $alias) + { + $this->fixerOption = $fixerOption; + $this->alias = $alias; + } + + public function getAlias(): string + { + return $this->alias; + } + + public function getName(): string + { + return $this->fixerOption->getName(); + } + + public function getDescription(): string + { + return $this->fixerOption->getDescription(); + } + + public function hasDefault(): bool + { + return $this->fixerOption->hasDefault(); + } + + public function getDefault() + { + return $this->fixerOption->getDefault(); + } + + public function getAllowedTypes(): ?array + { + return $this->fixerOption->getAllowedTypes(); + } + + public function getAllowedValues(): ?array + { + return $this->fixerOption->getAllowedValues(); + } + + public function getNormalizer(): ?\Closure + { + return $this->fixerOption->getNormalizer(); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOptionBuilder.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOptionBuilder.php new file mode 100644 index 00000000..13bb3faa --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOptionBuilder.php @@ -0,0 +1,78 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +/** + * @author ntzm + * + * @internal + */ +final class AliasedFixerOptionBuilder +{ + private FixerOptionBuilder $optionBuilder; + + private string $alias; + + public function __construct(FixerOptionBuilder $optionBuilder, string $alias) + { + $this->optionBuilder = $optionBuilder; + $this->alias = $alias; + } + + /** + * @param mixed $default + */ + public function setDefault($default): self + { + $this->optionBuilder->setDefault($default); + + return $this; + } + + /** + * @param list $allowedTypes + */ + public function setAllowedTypes(array $allowedTypes): self + { + $this->optionBuilder->setAllowedTypes($allowedTypes); + + return $this; + } + + /** + * @param list $allowedValues + */ + public function setAllowedValues(array $allowedValues): self + { + $this->optionBuilder->setAllowedValues($allowedValues); + + return $this; + } + + public function setNormalizer(\Closure $normalizer): self + { + $this->optionBuilder->setNormalizer($normalizer); + + return $this; + } + + public function getOption(): AliasedFixerOption + { + return new AliasedFixerOption( + $this->optionBuilder->getOption(), + $this->alias + ); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AllowedValueSubset.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AllowedValueSubset.php new file mode 100644 index 00000000..fad56516 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AllowedValueSubset.php @@ -0,0 +1,63 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +/** + * @internal + */ +final class AllowedValueSubset +{ + /** + * @var list + */ + private array $allowedValues; + + /** + * @param list $allowedValues + */ + public function __construct(array $allowedValues) + { + $this->allowedValues = $allowedValues; + sort($this->allowedValues, SORT_FLAG_CASE | SORT_STRING); + } + + /** + * Checks whether the given values are a subset of the allowed ones. + * + * @param mixed $values the value to validate + */ + public function __invoke($values): bool + { + if (!\is_array($values)) { + return false; + } + + foreach ($values as $value) { + if (!\in_array($value, $this->allowedValues, true)) { + return false; + } + } + + return true; + } + + /** + * @return list + */ + public function getAllowedValues(): array + { + return $this->allowedValues; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOption.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOption.php new file mode 100644 index 00000000..7224a673 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOption.php @@ -0,0 +1,68 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +final class DeprecatedFixerOption implements DeprecatedFixerOptionInterface +{ + private FixerOptionInterface $option; + + private string $deprecationMessage; + + public function __construct(FixerOptionInterface $option, string $deprecationMessage) + { + $this->option = $option; + $this->deprecationMessage = $deprecationMessage; + } + + public function getName(): string + { + return $this->option->getName(); + } + + public function getDescription(): string + { + return $this->option->getDescription(); + } + + public function hasDefault(): bool + { + return $this->option->hasDefault(); + } + + public function getDefault() + { + return $this->option->getDefault(); + } + + public function getAllowedTypes(): ?array + { + return $this->option->getAllowedTypes(); + } + + public function getAllowedValues(): ?array + { + return $this->option->getAllowedValues(); + } + + public function getNormalizer(): ?\Closure + { + return $this->option->getNormalizer(); + } + + public function getDeprecationMessage(): string + { + return $this->deprecationMessage; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOptionInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOptionInterface.php new file mode 100644 index 00000000..d847aea3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOptionInterface.php @@ -0,0 +1,20 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +interface DeprecatedFixerOptionInterface extends FixerOptionInterface +{ + public function getDeprecationMessage(): string; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolver.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolver.php new file mode 100644 index 00000000..ea073f25 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolver.php @@ -0,0 +1,125 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use Symfony\Component\OptionsResolver\OptionsResolver; + +final class FixerConfigurationResolver implements FixerConfigurationResolverInterface +{ + /** + * @var list + */ + private array $options = []; + + /** + * @var list + */ + private array $registeredNames = []; + + /** + * @param iterable $options + */ + public function __construct(iterable $options) + { + $fixerOptionSorter = new FixerOptionSorter(); + + foreach ($fixerOptionSorter->sort($options) as $option) { + $this->addOption($option); + } + + if (0 === \count($this->registeredNames)) { + throw new \LogicException('Options cannot be empty.'); + } + } + + public function getOptions(): array + { + return $this->options; + } + + public function resolve(array $configuration): array + { + $resolver = new OptionsResolver(); + + foreach ($this->options as $option) { + $name = $option->getName(); + + if ($option instanceof AliasedFixerOption) { + $alias = $option->getAlias(); + + if (\array_key_exists($alias, $configuration)) { + if (\array_key_exists($name, $configuration)) { + throw new InvalidOptionsException(sprintf('Aliased option "%s"/"%s" is passed multiple times.', $name, $alias)); + } + + Utils::triggerDeprecation(new \RuntimeException(sprintf( + 'Option "%s" is deprecated, use "%s" instead.', + $alias, + $name + ))); + + $configuration[$name] = $configuration[$alias]; + unset($configuration[$alias]); + } + } + + if ($option->hasDefault()) { + $resolver->setDefault($name, $option->getDefault()); + } else { + $resolver->setRequired($name); + } + + $allowedValues = $option->getAllowedValues(); + if (null !== $allowedValues) { + foreach ($allowedValues as &$allowedValue) { + if (\is_object($allowedValue) && \is_callable($allowedValue)) { + $allowedValue = static fn (/* mixed */ $values) => $allowedValue($values); + } + } + + $resolver->setAllowedValues($name, $allowedValues); + } + + $allowedTypes = $option->getAllowedTypes(); + if (null !== $allowedTypes) { + $resolver->setAllowedTypes($name, $allowedTypes); + } + + $normalizer = $option->getNormalizer(); + if (null !== $normalizer) { + $resolver->setNormalizer($name, $normalizer); + } + } + + return $resolver->resolve($configuration); + } + + /** + * @throws \LogicException when the option is already defined + */ + private function addOption(FixerOptionInterface $option): void + { + $name = $option->getName(); + + if (\in_array($name, $this->registeredNames, true)) { + throw new \LogicException(sprintf('The "%s" option is defined multiple times.', $name)); + } + + $this->options[] = $option; + $this->registeredNames[] = $name; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolverInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolverInterface.php new file mode 100644 index 00000000..284cdbd3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolverInterface.php @@ -0,0 +1,30 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +interface FixerConfigurationResolverInterface +{ + /** + * @return list + */ + public function getOptions(): array; + + /** + * @param array $configuration + * + * @return array + */ + public function resolve(array $configuration): array; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOption.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOption.php new file mode 100644 index 00000000..2866bdc1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOption.php @@ -0,0 +1,141 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +final class FixerOption implements FixerOptionInterface +{ + private string $name; + + private string $description; + + private bool $isRequired; + + /** + * @var mixed + */ + private $default; + + /** + * @var null|list + */ + private $allowedTypes; + + /** + * @var null|list + */ + private $allowedValues; + + /** + * @var null|\Closure + */ + private $normalizer; + + /** + * @param mixed $default + * @param null|list $allowedTypes + * @param null|list $allowedValues + */ + public function __construct( + string $name, + string $description, + bool $isRequired = true, + $default = null, + ?array $allowedTypes = null, + ?array $allowedValues = null, + ?\Closure $normalizer = null + ) { + if ($isRequired && null !== $default) { + throw new \LogicException('Required options cannot have a default value.'); + } + + if (null !== $allowedValues) { + foreach ($allowedValues as &$allowedValue) { + if ($allowedValue instanceof \Closure) { + $allowedValue = $this->unbind($allowedValue); + } + } + } + + $this->name = $name; + $this->description = $description; + $this->isRequired = $isRequired; + $this->default = $default; + $this->allowedTypes = $allowedTypes; + $this->allowedValues = $allowedValues; + + if (null !== $normalizer) { + $this->normalizer = $this->unbind($normalizer); + } + } + + public function getName(): string + { + return $this->name; + } + + public function getDescription(): string + { + return $this->description; + } + + public function hasDefault(): bool + { + return !$this->isRequired; + } + + public function getDefault() + { + if (!$this->hasDefault()) { + throw new \LogicException('No default value defined.'); + } + + return $this->default; + } + + public function getAllowedTypes(): ?array + { + return $this->allowedTypes; + } + + public function getAllowedValues(): ?array + { + return $this->allowedValues; + } + + public function getNormalizer(): ?\Closure + { + return $this->normalizer; + } + + /** + * Unbinds the given closure to avoid memory leaks. + * + * The closures provided to this class were probably defined in a fixer + * class and thus bound to it by default. The configuration will then be + * stored in {@see AbstractFixer::$configurationDefinition}, leading to the + * following cyclic reference: + * + * fixer -> configuration definition -> options -> closures -> fixer + * + * This cyclic reference prevent the garbage collector to free memory as + * all elements are still referenced. + * + * See {@see https://bugs.php.net/bug.php?id=69639 Bug #69639} for details. + */ + private function unbind(\Closure $closure): \Closure + { + return $closure->bindTo(null); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionBuilder.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionBuilder.php new file mode 100644 index 00000000..307518dc --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionBuilder.php @@ -0,0 +1,131 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +final class FixerOptionBuilder +{ + private string $name; + + private string $description; + + /** + * @var mixed + */ + private $default; + + private bool $isRequired = true; + + /** + * @var null|list + */ + private $allowedTypes; + + /** + * @var null|list + */ + private $allowedValues; + + /** + * @var null|\Closure + */ + private $normalizer; + + /** + * @var null|string + */ + private $deprecationMessage; + + public function __construct(string $name, string $description) + { + $this->name = $name; + $this->description = $description; + } + + /** + * @param mixed $default + * + * @return $this + */ + public function setDefault($default): self + { + $this->default = $default; + $this->isRequired = false; + + return $this; + } + + /** + * @param list $allowedTypes + * + * @return $this + */ + public function setAllowedTypes(array $allowedTypes): self + { + $this->allowedTypes = $allowedTypes; + + return $this; + } + + /** + * @param list $allowedValues + * + * @return $this + */ + public function setAllowedValues(array $allowedValues): self + { + $this->allowedValues = $allowedValues; + + return $this; + } + + /** + * @return $this + */ + public function setNormalizer(\Closure $normalizer): self + { + $this->normalizer = $normalizer; + + return $this; + } + + /** + * @return $this + */ + public function setDeprecationMessage(?string $deprecationMessage): self + { + $this->deprecationMessage = $deprecationMessage; + + return $this; + } + + public function getOption(): FixerOptionInterface + { + $option = new FixerOption( + $this->name, + $this->description, + $this->isRequired, + $this->default, + $this->allowedTypes, + $this->allowedValues, + $this->normalizer + ); + + if (null !== $this->deprecationMessage) { + $option = new DeprecatedFixerOption($option, $this->deprecationMessage); + } + + return $option; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionInterface.php new file mode 100644 index 00000000..d760e4df --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionInterface.php @@ -0,0 +1,43 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +interface FixerOptionInterface +{ + public function getName(): string; + + public function getDescription(): string; + + public function hasDefault(): bool; + + /** + * @return mixed + * + * @throws \LogicException when no default value is defined + */ + public function getDefault(); + + /** + * @return null|list + */ + public function getAllowedTypes(): ?array; + + /** + * @return null|list + */ + public function getAllowedValues(): ?array; + + public function getNormalizer(): ?\Closure; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionSorter.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionSorter.php new file mode 100644 index 00000000..bb526874 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionSorter.php @@ -0,0 +1,37 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +/** + * @internal + */ +final class FixerOptionSorter +{ + /** + * @param iterable $options + * + * @return list + */ + public function sort(iterable $options): array + { + if (!\is_array($options)) { + $options = iterator_to_array($options, false); + } + + usort($options, static fn (FixerOptionInterface $a, FixerOptionInterface $b): int => $a->getName() <=> $b->getName()); + + return $options; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/InvalidOptionsForEnvException.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/InvalidOptionsForEnvException.php new file mode 100644 index 00000000..4c12d5da --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/InvalidOptionsForEnvException.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class InvalidOptionsForEnvException extends InvalidOptionsException {} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSample.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSample.php new file mode 100644 index 00000000..b0dd2fed --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSample.php @@ -0,0 +1,47 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + */ +final class CodeSample implements CodeSampleInterface +{ + private string $code; + + /** + * @var null|array + */ + private ?array $configuration; + + /** + * @param null|array $configuration + */ + public function __construct(string $code, ?array $configuration = null) + { + $this->code = $code; + $this->configuration = $configuration; + } + + public function getCode(): string + { + return $this->code; + } + + public function getConfiguration(): ?array + { + return $this->configuration; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSampleInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSampleInterface.php new file mode 100644 index 00000000..9bce5eb8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSampleInterface.php @@ -0,0 +1,28 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + */ +interface CodeSampleInterface +{ + public function getCode(): string; + + /** + * @return null|array + */ + public function getConfiguration(): ?array; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSample.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSample.php new file mode 100644 index 00000000..effd0e52 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSample.php @@ -0,0 +1,54 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class FileSpecificCodeSample implements FileSpecificCodeSampleInterface +{ + private CodeSampleInterface $codeSample; + + private \SplFileInfo $splFileInfo; + + /** + * @param null|array $configuration + */ + public function __construct( + string $code, + \SplFileInfo $splFileInfo, + ?array $configuration = null + ) { + $this->codeSample = new CodeSample($code, $configuration); + $this->splFileInfo = $splFileInfo; + } + + public function getCode(): string + { + return $this->codeSample->getCode(); + } + + public function getConfiguration(): ?array + { + return $this->codeSample->getConfiguration(); + } + + public function getSplFileInfo(): \SplFileInfo + { + return $this->splFileInfo; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSampleInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSampleInterface.php new file mode 100644 index 00000000..df6f092f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSampleInterface.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +interface FileSpecificCodeSampleInterface extends CodeSampleInterface +{ + public function getSplFileInfo(): \SplFileInfo; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinition.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinition.php new file mode 100644 index 00000000..f4ae9159 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinition.php @@ -0,0 +1,74 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + */ +final class FixerDefinition implements FixerDefinitionInterface +{ + private string $summary; + + /** + * @var list + */ + private array $codeSamples; + + /** + * Description of Fixer and benefit of using it. + */ + private ?string $description; + + /** + * Description why Fixer is risky. + */ + private ?string $riskyDescription; + + /** + * @param list $codeSamples array of samples, where single sample is [code, configuration] + * @param null|string $riskyDescription null for non-risky fixer + */ + public function __construct( + string $summary, + array $codeSamples, + ?string $description = null, + ?string $riskyDescription = null + ) { + $this->summary = $summary; + $this->codeSamples = $codeSamples; + $this->description = $description; + $this->riskyDescription = $riskyDescription; + } + + public function getSummary(): string + { + return $this->summary; + } + + public function getDescription(): ?string + { + return $this->description; + } + + public function getRiskyDescription(): ?string + { + return $this->riskyDescription; + } + + public function getCodeSamples(): array + { + return $this->codeSamples; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinitionInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinitionInterface.php new file mode 100644 index 00000000..5bc2f934 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinitionInterface.php @@ -0,0 +1,37 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + */ +interface FixerDefinitionInterface +{ + public function getSummary(): string; + + public function getDescription(): ?string; + + /** + * @return null|string null for non-risky fixer + */ + public function getRiskyDescription(): ?string; + + /** + * Array of samples, where single sample is [code, configuration]. + * + * @return list + */ + public function getCodeSamples(): array; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSample.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSample.php new file mode 100644 index 00000000..f4b98111 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSample.php @@ -0,0 +1,52 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Andreas Möller + */ +final class VersionSpecificCodeSample implements VersionSpecificCodeSampleInterface +{ + private CodeSampleInterface $codeSample; + + private VersionSpecificationInterface $versionSpecification; + + /** + * @param null|array $configuration + */ + public function __construct( + string $code, + VersionSpecificationInterface $versionSpecification, + ?array $configuration = null + ) { + $this->codeSample = new CodeSample($code, $configuration); + $this->versionSpecification = $versionSpecification; + } + + public function getCode(): string + { + return $this->codeSample->getCode(); + } + + public function getConfiguration(): ?array + { + return $this->codeSample->getConfiguration(); + } + + public function isSuitableFor(int $version): bool + { + return $this->versionSpecification->isSatisfiedBy($version); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSampleInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSampleInterface.php new file mode 100644 index 00000000..74e4f446 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSampleInterface.php @@ -0,0 +1,23 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Andreas Moeller + */ +interface VersionSpecificCodeSampleInterface extends CodeSampleInterface +{ + public function isSuitableFor(int $version): bool; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecification.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecification.php new file mode 100644 index 00000000..2910fe72 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecification.php @@ -0,0 +1,74 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Andreas Möller + */ +final class VersionSpecification implements VersionSpecificationInterface +{ + /** + * @var null|int<1, max> + */ + private ?int $minimum; + + /** + * @var null|int<1, max> + */ + private ?int $maximum; + + /** + * @param null|int<1, max> $minimum + * @param null|int<1, max> $maximum + * + * @throws \InvalidArgumentException + */ + public function __construct(?int $minimum = null, ?int $maximum = null) + { + if (null === $minimum && null === $maximum) { + throw new \InvalidArgumentException('Minimum or maximum need to be specified.'); + } + + if (null !== $minimum && 1 > $minimum) { + throw new \InvalidArgumentException('Minimum needs to be either null or an integer greater than 0.'); + } + + if (null !== $maximum) { + if (1 > $maximum) { + throw new \InvalidArgumentException('Maximum needs to be either null or an integer greater than 0.'); + } + + if (null !== $minimum && $maximum < $minimum) { + throw new \InvalidArgumentException('Maximum should not be lower than the minimum.'); + } + } + + $this->minimum = $minimum; + $this->maximum = $maximum; + } + + public function isSatisfiedBy(int $version): bool + { + if (null !== $this->minimum && $version < $this->minimum) { + return false; + } + + if (null !== $this->maximum && $version > $this->maximum) { + return false; + } + + return true; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificationInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificationInterface.php new file mode 100644 index 00000000..502cdc4a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificationInterface.php @@ -0,0 +1,23 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Andreas Möller + */ +interface VersionSpecificationInterface +{ + public function isSatisfiedBy(int $version): bool; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerFactory.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerFactory.php new file mode 100644 index 00000000..7ee99bf2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerFactory.php @@ -0,0 +1,238 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\RuleSet\RuleSetInterface; +use Symfony\Component\Finder\Finder as SymfonyFinder; +use Symfony\Component\Finder\SplFileInfo; + +/** + * Class provides a way to create a group of fixers. + * + * Fixers may be registered (made the factory aware of them) by + * registering a custom fixer and default, built in fixers. + * Then, one can attach Config instance to fixer instances. + * + * Finally factory creates a ready to use group of fixers. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class FixerFactory +{ + private FixerNameValidator $nameValidator; + + /** + * @var list + */ + private array $fixers = []; + + /** + * @var array + */ + private array $fixersByName = []; + + public function __construct() + { + $this->nameValidator = new FixerNameValidator(); + } + + public function setWhitespacesConfig(WhitespacesFixerConfig $config): self + { + foreach ($this->fixers as $fixer) { + if ($fixer instanceof WhitespacesAwareFixerInterface) { + $fixer->setWhitespacesConfig($config); + } + } + + return $this; + } + + /** + * @return list + */ + public function getFixers(): array + { + $this->fixers = Utils::sortFixers($this->fixers); + + return $this->fixers; + } + + /** + * @return $this + */ + public function registerBuiltInFixers(): self + { + static $builtInFixers = null; + + if (null === $builtInFixers) { + $builtInFixers = []; + + /** @var SplFileInfo $file */ + foreach (SymfonyFinder::create()->files()->in(__DIR__.'/Fixer')->name('*Fixer.php')->depth(1) as $file) { + $relativeNamespace = $file->getRelativePath(); + $fixerClass = 'PhpCsFixer\\Fixer\\'.('' !== $relativeNamespace ? $relativeNamespace.'\\' : '').$file->getBasename('.php'); + $builtInFixers[] = $fixerClass; + } + } + + foreach ($builtInFixers as $class) { + $this->registerFixer(new $class(), false); + } + + return $this; + } + + /** + * @param FixerInterface[] $fixers + * + * @return $this + */ + public function registerCustomFixers(iterable $fixers): self + { + foreach ($fixers as $fixer) { + $this->registerFixer($fixer, true); + } + + return $this; + } + + /** + * @return $this + */ + public function registerFixer(FixerInterface $fixer, bool $isCustom): self + { + $name = $fixer->getName(); + + if (isset($this->fixersByName[$name])) { + throw new \UnexpectedValueException(sprintf('Fixer named "%s" is already registered.', $name)); + } + + if (!$this->nameValidator->isValid($name, $isCustom)) { + throw new \UnexpectedValueException(sprintf('Fixer named "%s" has invalid name.', $name)); + } + + $this->fixers[] = $fixer; + $this->fixersByName[$name] = $fixer; + + return $this; + } + + /** + * Apply RuleSet on fixers to filter out all unwanted fixers. + * + * @return $this + */ + public function useRuleSet(RuleSetInterface $ruleSet): self + { + $fixers = []; + $fixersByName = []; + $fixerConflicts = []; + + $fixerNames = array_keys($ruleSet->getRules()); + foreach ($fixerNames as $name) { + if (!\array_key_exists($name, $this->fixersByName)) { + throw new \UnexpectedValueException(sprintf('Rule "%s" does not exist.', $name)); + } + + $fixer = $this->fixersByName[$name]; + $config = $ruleSet->getRuleConfiguration($name); + + if (null !== $config) { + if ($fixer instanceof ConfigurableFixerInterface) { + if (\count($config) < 1) { + throw new InvalidFixerConfigurationException($fixer->getName(), 'Configuration must be an array and may not be empty.'); + } + + $fixer->configure($config); + } else { + throw new InvalidFixerConfigurationException($fixer->getName(), 'Is not configurable.'); + } + } + + $fixers[] = $fixer; + $fixersByName[$name] = $fixer; + $conflicts = array_intersect($this->getFixersConflicts($fixer), $fixerNames); + + if (\count($conflicts) > 0) { + $fixerConflicts[$name] = $conflicts; + } + } + + if (\count($fixerConflicts) > 0) { + throw new \UnexpectedValueException($this->generateConflictMessage($fixerConflicts)); + } + + $this->fixers = $fixers; + $this->fixersByName = $fixersByName; + + return $this; + } + + /** + * Check if fixer exists. + */ + public function hasRule(string $name): bool + { + return isset($this->fixersByName[$name]); + } + + /** + * @return string[] + */ + private function getFixersConflicts(FixerInterface $fixer): array + { + static $conflictMap = [ + 'blank_lines_before_namespace' => [ + 'no_blank_lines_before_namespace', + 'single_blank_line_before_namespace', + ], + 'no_blank_lines_before_namespace' => ['single_blank_line_before_namespace'], + 'single_import_per_statement' => ['group_import'], + ]; + + $fixerName = $fixer->getName(); + + return \array_key_exists($fixerName, $conflictMap) ? $conflictMap[$fixerName] : []; + } + + /** + * @param array $fixerConflicts + */ + private function generateConflictMessage(array $fixerConflicts): string + { + $message = 'Rule contains conflicting fixers:'; + $report = []; + + foreach ($fixerConflicts as $fixer => $fixers) { + // filter mutual conflicts + $report[$fixer] = array_filter( + $fixers, + static fn (string $candidate): bool => !\array_key_exists($candidate, $report) || !\in_array($fixer, $report[$candidate], true) + ); + + if (\count($report[$fixer]) > 0) { + $message .= sprintf("\n- \"%s\" with %s", $fixer, Utils::naturalLanguageJoin($report[$fixer])); + } + } + + return $message; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerFileProcessedEvent.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerFileProcessedEvent.php new file mode 100644 index 00000000..b609da49 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerFileProcessedEvent.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use Symfony\Contracts\EventDispatcher\Event; + +/** + * Event that is fired when file was processed by Fixer. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class FixerFileProcessedEvent extends Event +{ + /** + * Event name. + */ + public const NAME = 'fixer.file_processed'; + + public const STATUS_INVALID = 1; + public const STATUS_SKIPPED = 2; + public const STATUS_NO_CHANGES = 3; + public const STATUS_FIXED = 4; + public const STATUS_EXCEPTION = 5; + public const STATUS_LINT = 6; + + private int $status; + + public function __construct(int $status) + { + $this->status = $status; + } + + public function getStatus(): int + { + return $this->status; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerNameValidator.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerNameValidator.php new file mode 100644 index 00000000..8f19cb06 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/FixerNameValidator.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class FixerNameValidator +{ + public function isValid(string $name, bool $isCustom): bool + { + if (!$isCustom) { + return Preg::match('/^[a-z][a-z0-9_]*$/', $name); + } + + return Preg::match('/^[A-Z][a-zA-Z0-9]*\/[a-z][a-z0-9_]*$/', $name); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Indicator/PhpUnitTestCaseIndicator.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Indicator/PhpUnitTestCaseIndicator.php new file mode 100644 index 00000000..44d05c27 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Indicator/PhpUnitTestCaseIndicator.php @@ -0,0 +1,90 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Indicator; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + */ +final class PhpUnitTestCaseIndicator +{ + public function isPhpUnitClass(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->isGivenKind(T_CLASS)) { + throw new \LogicException(sprintf('No "T_CLASS" at given index %d, got "%s".', $index, $tokens[$index]->getName())); + } + + $index = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$index]->isGivenKind(T_STRING)) { + return false; + } + + $extendsIndex = $tokens->getNextTokenOfKind($index, ['{', [T_EXTENDS]]); + + if (!$tokens[$extendsIndex]->isGivenKind(T_EXTENDS)) { + return false; + } + + if (Preg::match('/(?:Test|TestCase)$/', $tokens[$index]->getContent())) { + return true; + } + + while (null !== $index = $tokens->getNextMeaningfulToken($index)) { + if ($tokens[$index]->equals('{')) { + break; // end of class signature + } + + if (!$tokens[$index]->isGivenKind(T_STRING)) { + continue; // not part of extends nor part of implements; so continue + } + + if (Preg::match('/(?:Test|TestCase)(?:Interface)?$/', $tokens[$index]->getContent())) { + return true; + } + } + + return false; + } + + /** + * Returns an indices of PHPUnit classes in reverse appearance order. + * Order is important - it's reverted, so if we inject tokens into collection, + * we do it for bottom of file first, and then to the top of the file, so we + * mitigate risk of not visiting whole collections (final indices). + * + * @return iterable array of [int start, int end] indices from later to earlier classes + */ + public function findPhpUnitClasses(Tokens $tokens): iterable + { + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(T_CLASS) || !$this->isPhpUnitClass($tokens, $index)) { + continue; + } + + $startIndex = $tokens->getNextTokenOfKind($index, ['{']); + + if (null === $startIndex) { + return; + } + + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex); + + yield [$startIndex, $endIndex]; + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/CachingLinter.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/CachingLinter.php new file mode 100644 index 00000000..b8590600 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/CachingLinter.php @@ -0,0 +1,62 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class CachingLinter implements LinterInterface +{ + private LinterInterface $sublinter; + + /** + * @var array + */ + private array $cache = []; + + public function __construct(LinterInterface $linter) + { + $this->sublinter = $linter; + } + + public function isAsync(): bool + { + return $this->sublinter->isAsync(); + } + + public function lintFile(string $path): LintingResultInterface + { + $checksum = md5(file_get_contents($path)); + + if (!isset($this->cache[$checksum])) { + $this->cache[$checksum] = $this->sublinter->lintFile($path); + } + + return $this->cache[$checksum]; + } + + public function lintSource(string $source): LintingResultInterface + { + $checksum = md5($source); + + if (!isset($this->cache[$checksum])) { + $this->cache[$checksum] = $this->sublinter->lintSource($source); + } + + return $this->cache[$checksum]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/Linter.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/Linter.php new file mode 100644 index 00000000..b8619b44 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/Linter.php @@ -0,0 +1,47 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +/** + * Handle PHP code linting process. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class Linter implements LinterInterface +{ + private LinterInterface $subLinter; + + public function __construct() + { + $this->subLinter = new TokenizerLinter(); + } + + public function isAsync(): bool + { + return $this->subLinter->isAsync(); + } + + public function lintFile(string $path): LintingResultInterface + { + return $this->subLinter->lintFile($path); + } + + public function lintSource(string $source): LintingResultInterface + { + return $this->subLinter->lintSource($source); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/LinterInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/LinterInterface.php new file mode 100644 index 00000000..1b5c2db6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/LinterInterface.php @@ -0,0 +1,35 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +/** + * Interface for PHP code linting process manager. + * + * @author Dariusz Rumiński + */ +interface LinterInterface +{ + public function isAsync(): bool; + + /** + * Lint PHP file. + */ + public function lintFile(string $path): LintingResultInterface; + + /** + * Lint PHP code. + */ + public function lintSource(string $source): LintingResultInterface; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingException.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingException.php new file mode 100644 index 00000000..1874bac1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingException.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +/** + * @author Dariusz Rumiński + * + * @final + * + * @TODO 4.0 make class "final" + */ +class LintingException extends \RuntimeException {} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingResultInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingResultInterface.php new file mode 100644 index 00000000..855d695b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingResultInterface.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +/** + * @author Dariusz Rumiński + */ +interface LintingResultInterface +{ + /** + * Check if linting process was successful and raise LintingException if not. + */ + public function check(): void; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinter.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinter.php new file mode 100644 index 00000000..1808a17e --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinter.php @@ -0,0 +1,151 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +use PhpCsFixer\FileReader; +use PhpCsFixer\FileRemoval; +use Symfony\Component\Filesystem\Exception\IOException; +use Symfony\Component\Process\PhpExecutableFinder; +use Symfony\Component\Process\Process; + +/** + * Handle PHP code linting using separated process of `php -l _file_`. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class ProcessLinter implements LinterInterface +{ + private FileRemoval $fileRemoval; + + private ProcessLinterProcessBuilder $processBuilder; + + /** + * Temporary file for code linting. + * + * @var null|string + */ + private $temporaryFile; + + /** + * @param null|string $executable PHP executable, null for autodetection + */ + public function __construct(?string $executable = null) + { + if (null === $executable) { + $executableFinder = new PhpExecutableFinder(); + $executable = $executableFinder->find(false); + + if (false === $executable) { + throw new UnavailableLinterException('Cannot find PHP executable.'); + } + + if ('phpdbg' === \PHP_SAPI) { + if (!str_contains($executable, 'phpdbg')) { + throw new UnavailableLinterException('Automatically found PHP executable is non-standard phpdbg. Could not find proper PHP executable.'); + } + + // automatically found executable is `phpdbg`, let us try to fallback to regular `php` + $executable = str_replace('phpdbg', 'php', $executable); + + if (!is_executable($executable)) { + throw new UnavailableLinterException('Automatically found PHP executable is phpdbg. Could not find proper PHP executable.'); + } + } + } + + $this->processBuilder = new ProcessLinterProcessBuilder($executable); + $this->fileRemoval = new FileRemoval(); + } + + public function __destruct() + { + if (null !== $this->temporaryFile) { + $this->fileRemoval->delete($this->temporaryFile); + } + } + + /** + * This class is not intended to be serialized, + * and cannot be deserialized (see __wakeup method). + */ + public function __sleep(): array + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + /** + * Disable the deserialization of the class to prevent attacker executing + * code by leveraging the __destruct method. + * + * @see https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection + */ + public function __wakeup(): void + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + public function isAsync(): bool + { + return true; + } + + public function lintFile(string $path): LintingResultInterface + { + return new ProcessLintingResult($this->createProcessForFile($path), $path); + } + + public function lintSource(string $source): LintingResultInterface + { + return new ProcessLintingResult($this->createProcessForSource($source), $this->temporaryFile); + } + + /** + * @param string $path path to file + */ + private function createProcessForFile(string $path): Process + { + // in case php://stdin + if (!is_file($path)) { + return $this->createProcessForSource(FileReader::createSingleton()->read($path)); + } + + $process = $this->processBuilder->build($path); + $process->setTimeout(10); + $process->start(); + + return $process; + } + + /** + * Create process that lint PHP code. + * + * @param string $source code + */ + private function createProcessForSource(string $source): Process + { + if (null === $this->temporaryFile) { + $this->temporaryFile = tempnam(sys_get_temp_dir(), 'cs_fixer_tmp_'); + $this->fileRemoval->observe($this->temporaryFile); + } + + if (false === @file_put_contents($this->temporaryFile, $source)) { + throw new IOException(sprintf('Failed to write file "%s".', $this->temporaryFile), 0, null, $this->temporaryFile); + } + + return $this->createProcessForFile($this->temporaryFile); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinterProcessBuilder.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinterProcessBuilder.php new file mode 100644 index 00000000..ee9a555e --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinterProcessBuilder.php @@ -0,0 +1,44 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +use Symfony\Component\Process\Process; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class ProcessLinterProcessBuilder +{ + private string $executable; + + /** + * @param string $executable PHP executable + */ + public function __construct(string $executable) + { + $this->executable = $executable; + } + + public function build(string $path): Process + { + return new Process([ + $this->executable, + '-l', + $path, + ]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLintingResult.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLintingResult.php new file mode 100644 index 00000000..7d282d16 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLintingResult.php @@ -0,0 +1,86 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +use Symfony\Component\Process\Process; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class ProcessLintingResult implements LintingResultInterface +{ + private Process $process; + + private ?string $path; + + private ?bool $isSuccessful = null; + + public function __construct(Process $process, ?string $path = null) + { + $this->process = $process; + $this->path = $path; + } + + public function check(): void + { + if (!$this->isSuccessful()) { + // on some systems stderr is used, but on others, it's not + throw new LintingException($this->getProcessErrorMessage(), $this->process->getExitCode()); + } + } + + private function getProcessErrorMessage(): string + { + $errorOutput = $this->process->getErrorOutput(); + $output = strtok(ltrim('' !== $errorOutput ? $errorOutput : $this->process->getOutput()), "\n"); + + if (false === $output) { + return 'Fatal error: Unable to lint file.'; + } + + if (null !== $this->path) { + $needle = sprintf('in %s ', $this->path); + $pos = strrpos($output, $needle); + + if (false !== $pos) { + $output = sprintf('%s%s', substr($output, 0, $pos), substr($output, $pos + \strlen($needle))); + } + } + + $prefix = substr($output, 0, 18); + + if ('PHP Parse error: ' === $prefix) { + return sprintf('Parse error: %s.', substr($output, 18)); + } + + if ('PHP Fatal error: ' === $prefix) { + return sprintf('Fatal error: %s.', substr($output, 18)); + } + + return sprintf('%s.', $output); + } + + private function isSuccessful(): bool + { + if (null === $this->isSuccessful) { + $this->process->wait(); + $this->isSuccessful = $this->process->isSuccessful(); + } + + return $this->isSuccessful; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLinter.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLinter.php new file mode 100644 index 00000000..b0920d30 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLinter.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +use PhpCsFixer\FileReader; +use PhpCsFixer\Tokenizer\CodeHasher; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Handle PHP code linting. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class TokenizerLinter implements LinterInterface +{ + public function isAsync(): bool + { + return false; + } + + public function lintFile(string $path): LintingResultInterface + { + return $this->lintSource(FileReader::createSingleton()->read($path)); + } + + public function lintSource(string $source): LintingResultInterface + { + try { + // To lint, we will parse the source into Tokens. + // During that process, it might throw a ParseError or CompileError. + // If it won't, cache of tokenized version of source will be kept, which is great for Runner. + // Yet, first we need to clear already existing cache to not hit it and lint the code indeed. + $codeHash = CodeHasher::calculateCodeHash($source); + Tokens::clearCache($codeHash); + Tokens::fromCode($source); + + return new TokenizerLintingResult(); + } catch (\CompileError|\ParseError $e) { + return new TokenizerLintingResult($e); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLintingResult.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLintingResult.php new file mode 100644 index 00000000..4880d928 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLintingResult.php @@ -0,0 +1,46 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class TokenizerLintingResult implements LintingResultInterface +{ + private ?\Error $error; + + public function __construct(?\Error $error = null) + { + $this->error = $error; + } + + public function check(): void + { + if (null !== $this->error) { + throw new LintingException( + sprintf('%s: %s on line %d.', $this->getMessagePrefix(), $this->error->getMessage(), $this->error->getLine()), + $this->error->getCode(), + $this->error + ); + } + } + + private function getMessagePrefix(): string + { + return $this->error instanceof \ParseError ? 'Parse error' : 'Fatal error'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/UnavailableLinterException.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/UnavailableLinterException.php new file mode 100644 index 00000000..df67b5f0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Linter/UnavailableLinterException.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +/** + * Exception that is thrown when the chosen linter is not available on the environment. + * + * @author Dariusz Rumiński + * + * @final + * + * @TODO 4.0 make class "final" + */ +class UnavailableLinterException extends \RuntimeException {} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/PharChecker.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/PharChecker.php new file mode 100644 index 00000000..b7cb356c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/PharChecker.php @@ -0,0 +1,38 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @internal + */ +final class PharChecker implements PharCheckerInterface +{ + public function checkFileValidity(string $filename): ?string + { + try { + $phar = new \Phar($filename); + // free the variable to unlock the file + unset($phar); + } catch (\Exception $e) { + if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) { + throw $e; + } + + return 'Failed to create Phar instance. '.$e->getMessage(); + } + + return null; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/PharCheckerInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/PharCheckerInterface.php new file mode 100644 index 00000000..6ae22088 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/PharCheckerInterface.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @internal + */ +interface PharCheckerInterface +{ + /** + * @return null|string the invalidity reason if any, null otherwise + */ + public function checkFileValidity(string $filename): ?string; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Preg.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Preg.php new file mode 100644 index 00000000..ad90176d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Preg.php @@ -0,0 +1,201 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * This class replaces preg_* functions to better handling UTF8 strings, + * ensuring no matter "u" modifier is present or absent subject will be handled correctly. + * + * @author Kuba Werłos + * + * @internal + */ +final class Preg +{ + /** + * @param null|string[] $matches + * @param int-mask<0, 256, 512> $flags + * + * @throws PregException + */ + public static function match(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): bool + { + $result = @preg_match(self::addUtf8Modifier($pattern), $subject, $matches, $flags, $offset); + if (false !== $result && PREG_NO_ERROR === preg_last_error()) { + return 1 === $result; + } + + $result = @preg_match(self::removeUtf8Modifier($pattern), $subject, $matches, $flags, $offset); + if (false !== $result && PREG_NO_ERROR === preg_last_error()) { + return 1 === $result; + } + + throw self::newPregException(preg_last_error(), preg_last_error_msg(), __METHOD__, (array) $pattern); + } + + /** + * @param null|string[] $matches + * + * @throws PregException + */ + public static function matchAll(string $pattern, string $subject, ?array &$matches = null, int $flags = PREG_PATTERN_ORDER, int $offset = 0): int + { + $result = @preg_match_all(self::addUtf8Modifier($pattern), $subject, $matches, $flags, $offset); + if (false !== $result && PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + $result = @preg_match_all(self::removeUtf8Modifier($pattern), $subject, $matches, $flags, $offset); + if (false !== $result && PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + throw self::newPregException(preg_last_error(), preg_last_error_msg(), __METHOD__, (array) $pattern); + } + + /** + * @param string|string[] $subject + * + * @throws PregException + */ + public static function replace(string $pattern, string $replacement, $subject, int $limit = -1, ?int &$count = null): string + { + $result = @preg_replace(self::addUtf8Modifier($pattern), $replacement, $subject, $limit, $count); + if (null !== $result && PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + $result = @preg_replace(self::removeUtf8Modifier($pattern), $replacement, $subject, $limit, $count); + if (null !== $result && PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + throw self::newPregException(preg_last_error(), preg_last_error_msg(), __METHOD__, (array) $pattern); + } + + /** + * @throws PregException + */ + public static function replaceCallback(string $pattern, callable $callback, string $subject, int $limit = -1, ?int &$count = null): string + { + $result = @preg_replace_callback(self::addUtf8Modifier($pattern), $callback, $subject, $limit, $count); + if (null !== $result && PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + $result = @preg_replace_callback(self::removeUtf8Modifier($pattern), $callback, $subject, $limit, $count); + if (null !== $result && PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + throw self::newPregException(preg_last_error(), preg_last_error_msg(), __METHOD__, (array) $pattern); + } + + /** + * @return string[] + * + * @throws PregException + */ + public static function split(string $pattern, string $subject, int $limit = -1, int $flags = 0): array + { + $result = @preg_split(self::addUtf8Modifier($pattern), $subject, $limit, $flags); + if (false !== $result && PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + $result = @preg_split(self::removeUtf8Modifier($pattern), $subject, $limit, $flags); + if (false !== $result && PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + throw self::newPregException(preg_last_error(), preg_last_error_msg(), __METHOD__, (array) $pattern); + } + + /** + * @param string|string[] $pattern + * + * @return string|string[] + */ + private static function addUtf8Modifier($pattern) + { + if (\is_array($pattern)) { + return array_map(__METHOD__, $pattern); + } + + return $pattern.'u'; + } + + /** + * @param string|string[] $pattern + * + * @return string|string[] + */ + private static function removeUtf8Modifier($pattern) + { + if (\is_array($pattern)) { + return array_map(__METHOD__, $pattern); + } + + if ('' === $pattern) { + return ''; + } + + $delimiter = $pattern[0]; + + $endDelimiterPosition = strrpos($pattern, $delimiter); + + return substr($pattern, 0, $endDelimiterPosition).str_replace('u', '', substr($pattern, $endDelimiterPosition)); + } + + /** + * Create PregException. + * + * Create the generic PregException message and if possible due to finding + * an invalid pattern, tell more about such kind of error in the message. + * + * @param string[] $patterns + */ + private static function newPregException(int $error, string $errorMsg, string $method, array $patterns): PregException + { + foreach ($patterns as $pattern) { + $last = error_get_last(); + $result = @preg_match($pattern, ''); + + if (false !== $result) { + continue; + } + + $code = preg_last_error(); + $next = error_get_last(); + + if ($last !== $next) { + $message = sprintf( + '(code: %d) %s', + $code, + preg_replace('~preg_[a-z_]+[()]{2}: ~', '', $next['message']) + ); + } else { + $message = sprintf('(code: %d)', $code); + } + + return new PregException( + sprintf('%s(): Invalid PCRE pattern "%s": %s (version: %s)', $method, $pattern, $message, PCRE_VERSION), + $code + ); + } + + return new PregException(sprintf('Error occurred when calling %s: %s.', $method, $errorMsg), $error); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/PregException.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/PregException.php new file mode 100644 index 00000000..57519e8a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/PregException.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * Exception that is thrown when PCRE function encounters an error. + * + * @author Kuba Werłos + * + * @internal + */ +final class PregException extends \RuntimeException {} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractMigrationSetDescription.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractMigrationSetDescription.php new file mode 100644 index 00000000..57e1911b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractMigrationSetDescription.php @@ -0,0 +1,38 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +use PhpCsFixer\Preg; + +/** + * @internal + */ +abstract class AbstractMigrationSetDescription extends AbstractRuleSetDescription +{ + public function getDescription(): string + { + $name = $this->getName(); + + if (Preg::match('#^@PHPUnit(\d+)(\d)Migration.*$#', $name, $matches)) { + return sprintf('Rules to improve tests code for PHPUnit %d.%d compatibility.', $matches[1], $matches[2]); + } + + if (Preg::match('#^@PHP([\d]{2})Migration.*$#', $name, $matches)) { + return sprintf('Rules to improve code for PHP %d.%d compatibility.', $matches[1][0], $matches[1][1]); + } + + throw new \RuntimeException(sprintf('Cannot generate description for "%s" "%s".', static::class, $name)); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractRuleSetDescription.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractRuleSetDescription.php new file mode 100644 index 00000000..db565b41 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractRuleSetDescription.php @@ -0,0 +1,35 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +/** + * @internal + */ +abstract class AbstractRuleSetDescription implements RuleSetDescriptionInterface +{ + public function __construct() {} + + public function getName(): string + { + $name = substr(static::class, 1 + strrpos(static::class, '\\'), -3); + + return '@'.str_replace('Risky', ':risky', $name); + } + + public function isRisky(): bool + { + return str_contains(static::class, 'Risky'); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSet.php new file mode 100644 index 00000000..19f48c09 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSet.php @@ -0,0 +1,141 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; + +/** + * Set of rules to be used by fixer. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class RuleSet implements RuleSetInterface +{ + /** + * Group of rules generated from input set. + * + * The key is name of rule, value is bool if the rule/set should be used. + * The key must not point to any set. + * + * @var array|bool> + */ + private array $rules; + + public function __construct(array $set = []) + { + foreach ($set as $name => $value) { + if ('' === $name) { + throw new \InvalidArgumentException('Rule/set name must not be empty.'); + } + + if (\is_int($name)) { + throw new \InvalidArgumentException(sprintf('Missing value for "%s" rule/set.', $value)); + } + + if (!\is_bool($value) && !\is_array($value)) { + $message = str_starts_with($name, '@') ? 'Set must be enabled (true) or disabled (false). Other values are not allowed.' : 'Rule must be enabled (true), disabled (false) or configured (non-empty, assoc array). Other values are not allowed.'; + + if (null === $value) { + $message .= ' To disable the '.(str_starts_with($name, '@') ? 'set' : 'rule').', use "FALSE" instead of "NULL".'; + } + + throw new InvalidFixerConfigurationException($name, $message); + } + } + + $this->resolveSet($set); + } + + public function hasRule(string $rule): bool + { + return \array_key_exists($rule, $this->rules); + } + + public function getRuleConfiguration(string $rule): ?array + { + if (!$this->hasRule($rule)) { + throw new \InvalidArgumentException(sprintf('Rule "%s" is not in the set.', $rule)); + } + + if (true === $this->rules[$rule]) { + return null; + } + + return $this->rules[$rule]; + } + + public function getRules(): array + { + return $this->rules; + } + + /** + * Resolve input set into group of rules. + * + * @param array|bool> $rules + */ + private function resolveSet(array $rules): void + { + $resolvedRules = []; + + // expand sets + foreach ($rules as $name => $value) { + if (str_starts_with($name, '@')) { + if (!\is_bool($value)) { + throw new \UnexpectedValueException(sprintf('Nested rule set "%s" configuration must be a boolean.', $name)); + } + + $set = $this->resolveSubset($name, $value); + $resolvedRules = array_merge($resolvedRules, $set); + } else { + $resolvedRules[$name] = $value; + } + } + + // filter out all resolvedRules that are off + $resolvedRules = array_filter($resolvedRules); + + $this->rules = $resolvedRules; + } + + /** + * Resolve set rules as part of another set. + * + * If set value is false then disable all fixers in set, + * if not then get value from set item. + * + * @return array|bool> + */ + private function resolveSubset(string $setName, bool $setValue): array + { + $rules = RuleSets::getSetDefinition($setName)->getRules(); + + foreach ($rules as $name => $value) { + if (str_starts_with($name, '@')) { + $set = $this->resolveSubset($name, $setValue); + unset($rules[$name]); + $rules = array_merge($rules, $set); + } elseif (!$setValue) { + $rules[$name] = false; + } else { + $rules[$name] = $value; + } + } + + return $rules; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetDescriptionInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetDescriptionInterface.php new file mode 100644 index 00000000..156aed3a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetDescriptionInterface.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +/** + * @internal + */ +interface RuleSetDescriptionInterface +{ + public function getDescription(): string; + + public function getName(): string; + + /** + * Get all rules from rules set. + * + * @return array|bool> + */ + public function getRules(): array; + + public function isRisky(): bool; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetInterface.php new file mode 100644 index 00000000..eb83b6b4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetInterface.php @@ -0,0 +1,49 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +/** + * Set of rules to be used by fixer. + * + * Example of set: ["@PSR2" => true, "@PSR1" => false, "strict" => true]. + * + * @author Dariusz Rumiński + */ +interface RuleSetInterface +{ + /** + * @param array|bool> $set + */ + public function __construct(array $set = []); + + /** + * Get configuration for given rule. + * + * @return null|array + */ + public function getRuleConfiguration(string $rule): ?array; + + /** + * Get all rules from rules set. + * + * @return array|bool> + */ + public function getRules(): array; + + /** + * Check given rule is in rules set. + */ + public function hasRule(string $rule): bool; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSets.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSets.php new file mode 100644 index 00000000..d10ff8c6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSets.php @@ -0,0 +1,70 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +use Symfony\Component\Finder\Finder; + +/** + * Set of rule sets to be used by fixer. + * + * @internal + */ +final class RuleSets +{ + /** + * @var array + */ + private static $setDefinitions; + + /** + * @return array + */ + public static function getSetDefinitions(): array + { + if (null === self::$setDefinitions) { + self::$setDefinitions = []; + + foreach (Finder::create()->files()->in(__DIR__.'/Sets') as $file) { + $class = 'PhpCsFixer\RuleSet\Sets\\'.$file->getBasename('.php'); + $set = new $class(); + + self::$setDefinitions[$set->getName()] = $set; + } + + uksort(self::$setDefinitions, static fn (string $x, string $y): int => strnatcmp($x, $y)); + } + + return self::$setDefinitions; + } + + /** + * @return string[] + */ + public static function getSetDefinitionNames(): array + { + return array_keys(self::getSetDefinitions()); + } + + public static function getSetDefinition(string $name): RuleSetDescriptionInterface + { + $definitions = self::getSetDefinitions(); + + if (!isset($definitions[$name])) { + throw new \InvalidArgumentException(sprintf('Set "%s" does not exist.', $name)); + } + + return $definitions[$name]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/DoctrineAnnotationSet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/DoctrineAnnotationSet.php new file mode 100644 index 00000000..53535465 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/DoctrineAnnotationSet.php @@ -0,0 +1,42 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + */ +final class DoctrineAnnotationSet extends AbstractRuleSetDescription +{ + public function getRules(): array + { + return [ + 'doctrine_annotation_array_assignment' => [ + 'operator' => ':', + ], + 'doctrine_annotation_braces' => true, + 'doctrine_annotation_indentation' => true, + 'doctrine_annotation_spaces' => [ + 'before_array_assignments_colon' => false, + ], + ]; + } + + public function getDescription(): string + { + return 'Rules covering Doctrine annotations with configuration based on examples found in `Doctrine Annotation documentation `_ and `Symfony documentation `_.'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0RiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0RiskySet.php new file mode 100644 index 00000000..30d1582b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0RiskySet.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + * + * PER Coding Style v1.0. + * + * @TODO 4.0 Remove this class + * + * @deprecated Use `@PER-CS2.0:risky` instead. + * @see https://github.com/php-fig/per-coding-style/blob/1.0.0/spec.md + */ +final class PERCS1x0RiskySet extends AbstractRuleSetDescription +{ + public function getName(): string + { + return '@PER-CS1.0:risky'; + } + + public function getRules(): array + { + return [ + '@PSR12:risky' => true, + ]; + } + + public function getDescription(): string + { + return <<<'DESC' + **This ruleset is deprecated** in favour of ``@PER-CS2.0:risky``. + + Rules that follow `PER Coding Style 1.0 `_. + DESC; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0Set.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0Set.php new file mode 100644 index 00000000..59d4441a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0Set.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + * + * PER Coding Style v1.0. + * + * @TODO 4.0 Remove this class + * + * @deprecated Use `@PER-CS2.0` instead. + * @see https://github.com/php-fig/per-coding-style/blob/1.0.0/spec.md + */ +final class PERCS1x0Set extends AbstractRuleSetDescription +{ + public function getName(): string + { + return '@PER-CS1.0'; + } + + public function getRules(): array + { + return [ + '@PSR12' => true, + ]; + } + + public function getDescription(): string + { + return <<<'DESC' + **This ruleset is deprecated** in favour of ``@PER-CS2.0``. + + Rules that follow `PER Coding Style 1.0 `_. + DESC; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS2x0RiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS2x0RiskySet.php new file mode 100644 index 00000000..4a75a93d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS2x0RiskySet.php @@ -0,0 +1,44 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + * + * PER Coding Style v2.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/2.0.0/spec.md + */ +final class PERCS2x0RiskySet extends AbstractRuleSetDescription +{ + public function getName(): string + { + return '@PER-CS2.0:risky'; + } + + public function getRules(): array + { + return [ + '@PER-CS1.0:risky' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PER Coding Style 2.0 `_.'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS2x0Set.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS2x0Set.php new file mode 100644 index 00000000..5a6df0fe --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS2x0Set.php @@ -0,0 +1,50 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + * + * PER Coding Style v2.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/2.0.0/spec.md + */ +final class PERCS2x0Set extends AbstractRuleSetDescription +{ + public function getName(): string + { + return '@PER-CS2.0'; + } + + public function getRules(): array + { + return [ + '@PER-CS1.0' => true, + 'concat_space' => ['spacing' => 'one'], + 'function_declaration' => [ + 'closure_fn_spacing' => 'none', + ], + 'method_argument_space' => true, + 'single_line_empty_body' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PER Coding Style 2.0 `_.'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCSRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCSRiskySet.php new file mode 100644 index 00000000..6e6f7908 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCSRiskySet.php @@ -0,0 +1,40 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + */ +final class PERCSRiskySet extends AbstractRuleSetDescription +{ + public function getName(): string + { + return '@PER-CS:risky'; + } + + public function getRules(): array + { + return [ + '@PER-CS2.0:risky' => true, + ]; + } + + public function getDescription(): string + { + return 'Alias for the latest revision of PER-CS risky rules. Use it if you always want to be in sync with newest PER-CS standard.'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCSSet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCSSet.php new file mode 100644 index 00000000..0fe59349 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCSSet.php @@ -0,0 +1,40 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + */ +final class PERCSSet extends AbstractRuleSetDescription +{ + public function getName(): string + { + return '@PER-CS'; + } + + public function getRules(): array + { + return [ + '@PER-CS2.0' => true, + ]; + } + + public function getDescription(): string + { + return 'Alias for the latest revision of PER-CS rules. Use it if you always want to be in sync with newest PER-CS standard.'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERRiskySet.php new file mode 100644 index 00000000..e700d4c3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERRiskySet.php @@ -0,0 +1,46 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + * + * @deprecated Use `@PER-CS2.0:risky` instead. + * + * @TODO 4.0 remove me + * + * Last updated to PER Coding Style v2.0. + */ +final class PERRiskySet extends AbstractRuleSetDescription +{ + public function getName(): string + { + return '@PER:risky'; + } + + public function getRules(): array + { + return [ + '@PER-CS2.0:risky' => true, + ]; + } + + public function getDescription(): string + { + return 'Alias for the PER-CS risky rules. It is recommended you use ``@PER-CS2.0:risky`` instead.'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERSet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERSet.php new file mode 100644 index 00000000..3b2d0b80 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERSet.php @@ -0,0 +1,41 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + * + * @deprecated Use `@PER-CS2.0` instead. + * + * @TODO 4.0 remove me + * + * Last updated to PER Coding Style v2.0. + */ +final class PERSet extends AbstractRuleSetDescription +{ + public function getRules(): array + { + return [ + '@PER-CS2.0' => true, + ]; + } + + public function getDescription(): string + { + return 'Alias for the PER-CS rules. It is recommended you use ``@PER-CS2.0`` instead.'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP54MigrationSet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP54MigrationSet.php new file mode 100644 index 00000000..bb877922 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP54MigrationSet.php @@ -0,0 +1,30 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHP54MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + 'array_syntax' => true, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP56MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP56MigrationRiskySet.php new file mode 100644 index 00000000..848b3501 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP56MigrationRiskySet.php @@ -0,0 +1,30 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHP56MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + 'pow_to_exponentiation' => true, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationRiskySet.php new file mode 100644 index 00000000..a7fcb211 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationRiskySet.php @@ -0,0 +1,39 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHP70MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHP56Migration:risky' => true, + 'combine_nested_dirname' => true, + 'declare_strict_types' => true, + 'non_printable_character' => true, + 'random_api_migration' => [ + 'replacements' => [ + 'mt_rand' => 'random_int', + 'rand' => 'random_int', + ], + ], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationSet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationSet.php new file mode 100644 index 00000000..62b0ad99 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationSet.php @@ -0,0 +1,31 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHP70MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHP54Migration' => true, + 'ternary_to_null_coalescing' => true, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationRiskySet.php new file mode 100644 index 00000000..5a57f262 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationRiskySet.php @@ -0,0 +1,31 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHP71MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHP70Migration:risky' => true, + 'void_return' => true, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationSet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationSet.php new file mode 100644 index 00000000..9379628d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationSet.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHP71MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHP70Migration' => true, + 'list_syntax' => true, + 'visibility_required' => true, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP73MigrationSet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP73MigrationSet.php new file mode 100644 index 00000000..aa0ed8fb --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP73MigrationSet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHP73MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHP71Migration' => true, + 'heredoc_indentation' => true, + 'method_argument_space' => ['after_heredoc' => true], + 'no_whitespace_before_comma_in_array' => ['after_heredoc' => true], + 'trailing_comma_in_multiline' => ['after_heredoc' => true], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationRiskySet.php new file mode 100644 index 00000000..0a1bc17d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationRiskySet.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHP74MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHP71Migration:risky' => true, + 'implode_call' => true, + 'no_alias_functions' => true, + 'use_arrow_functions' => true, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationSet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationSet.php new file mode 100644 index 00000000..8af7296a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationSet.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHP74MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHP73Migration' => true, + 'assign_null_coalescing_to_coalesce_equal' => true, + 'normalize_index_brace' => true, + 'short_scalar_cast' => true, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationRiskySet.php new file mode 100644 index 00000000..4027b6ed --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationRiskySet.php @@ -0,0 +1,40 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHP80MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHP74Migration:risky' => true, + 'get_class_to_class_keyword' => true, + 'modernize_strpos' => true, + 'no_alias_functions' => [ + 'sets' => [ + '@all', + ], + ], + 'no_php4_constructor' => true, + 'no_unneeded_final_method' => true, // final private method (not constructor) are no longer allowed >= PHP8.0 + 'no_unreachable_default_argument_value' => true, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationSet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationSet.php new file mode 100644 index 00000000..8b49a55c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationSet.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHP80MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHP74Migration' => true, + 'clean_namespace' => true, + 'no_unset_cast' => true, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP81MigrationSet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP81MigrationSet.php new file mode 100644 index 00000000..eaa27e9d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP81MigrationSet.php @@ -0,0 +1,31 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHP81MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHP80Migration' => true, + 'octal_notation' => true, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP82MigrationSet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP82MigrationSet.php new file mode 100644 index 00000000..6a9da7db --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP82MigrationSet.php @@ -0,0 +1,31 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHP82MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHP81Migration' => true, + 'simple_to_complex_string_variable' => true, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP83MigrationSet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP83MigrationSet.php new file mode 100644 index 00000000..a2bdfbd9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP83MigrationSet.php @@ -0,0 +1,30 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHP83MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHP82Migration' => true, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit100MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit100MigrationRiskySet.php new file mode 100644 index 00000000..433fa7ac --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit100MigrationRiskySet.php @@ -0,0 +1,31 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHPUnit100MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHPUnit84Migration:risky' => true, + 'php_unit_data_provider_static' => ['force' => true], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php new file mode 100644 index 00000000..1cabfc04 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHPUnit30MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + 'php_unit_dedicate_assert' => [ + 'target' => PhpUnitTargetVersion::VERSION_3_0, + ], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php new file mode 100644 index 00000000..fb4cbfb5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHPUnit32MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHPUnit30Migration:risky' => true, + 'php_unit_no_expectation_annotation' => [ + 'target' => PhpUnitTargetVersion::VERSION_3_2, + ], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php new file mode 100644 index 00000000..6a52afac --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHPUnit35MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHPUnit32Migration:risky' => true, + 'php_unit_dedicate_assert' => [ + 'target' => PhpUnitTargetVersion::VERSION_3_5, + ], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php new file mode 100644 index 00000000..13927970 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHPUnit43MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHPUnit35Migration:risky' => true, + 'php_unit_no_expectation_annotation' => [ + 'target' => PhpUnitTargetVersion::VERSION_4_3, + ], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php new file mode 100644 index 00000000..fcb1b57e --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHPUnit48MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHPUnit43Migration:risky' => true, + 'php_unit_namespaced' => [ + 'target' => PhpUnitTargetVersion::VERSION_4_8, + ], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php new file mode 100644 index 00000000..38474584 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHPUnit50MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHPUnit48Migration:risky' => true, + 'php_unit_dedicate_assert' => [ + 'target' => PhpUnitTargetVersion::VERSION_5_0, + ], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php new file mode 100644 index 00000000..d0f71ee3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHPUnit52MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHPUnit50Migration:risky' => true, + 'php_unit_expectation' => [ + 'target' => PhpUnitTargetVersion::VERSION_5_2, + ], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php new file mode 100644 index 00000000..b7c87922 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHPUnit54MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHPUnit52Migration:risky' => true, + 'php_unit_mock' => [ + 'target' => PhpUnitTargetVersion::VERSION_5_4, + ], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php new file mode 100644 index 00000000..e3c1647d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHPUnit55MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHPUnit54Migration:risky' => true, + 'php_unit_mock' => [ + 'target' => PhpUnitTargetVersion::VERSION_5_5, + ], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php new file mode 100644 index 00000000..a1038bf8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php @@ -0,0 +1,37 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHPUnit56MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHPUnit55Migration:risky' => true, + 'php_unit_dedicate_assert' => [ + 'target' => PhpUnitTargetVersion::VERSION_5_6, + ], + 'php_unit_expectation' => [ + 'target' => PhpUnitTargetVersion::VERSION_5_6, + ], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php new file mode 100644 index 00000000..84076e11 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHPUnit57MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHPUnit56Migration:risky' => true, + 'php_unit_namespaced' => [ + 'target' => PhpUnitTargetVersion::VERSION_5_7, + ], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php new file mode 100644 index 00000000..6bc7f711 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHPUnit60MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHPUnit57Migration:risky' => true, + 'php_unit_namespaced' => [ + 'target' => PhpUnitTargetVersion::VERSION_6_0, + ], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php new file mode 100644 index 00000000..a7efa234 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHPUnit75MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHPUnit60Migration:risky' => true, + 'php_unit_dedicate_assert_internal_type' => [ + 'target' => PhpUnitTargetVersion::VERSION_7_5, + ], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit84MigrationRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit84MigrationRiskySet.php new file mode 100644 index 00000000..aaf5fc31 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit84MigrationRiskySet.php @@ -0,0 +1,35 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; + +/** + * @internal + */ +final class PHPUnit84MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules(): array + { + return [ + '@PHPUnit60Migration:risky' => true, + '@PHPUnit75Migration:risky' => true, + 'php_unit_expectation' => [ + 'target' => PhpUnitTargetVersion::VERSION_8_4, + ], + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12RiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12RiskySet.php new file mode 100644 index 00000000..84fd3efa --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12RiskySet.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + */ +final class PSR12RiskySet extends AbstractRuleSetDescription +{ + public function getRules(): array + { + return [ + 'no_trailing_whitespace_in_string' => true, + 'no_unreachable_default_argument_value' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PSR-12 `_ standard.'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12Set.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12Set.php new file mode 100644 index 00000000..322d82cc --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12Set.php @@ -0,0 +1,76 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + */ +final class PSR12Set extends AbstractRuleSetDescription +{ + public function getRules(): array + { + return [ + '@PSR2' => true, + 'binary_operator_spaces' => [ + 'default' => 'at_least_single_space', + ], + 'blank_line_after_opening_tag' => true, + 'blank_line_between_import_groups' => true, + 'blank_lines_before_namespace' => true, + 'braces_position' => [ + 'allow_single_line_empty_anonymous_classes' => true, + ], + 'class_definition' => [ + 'inline_constructor_arguments' => false, // handled by method_argument_space fixer + 'space_before_parenthesis' => true, // defined in PSR12 ¶8. Anonymous Classes + ], + 'compact_nullable_type_declaration' => true, + 'declare_equal_normalize' => true, + 'lowercase_cast' => true, + 'lowercase_static_reference' => true, + 'new_with_parentheses' => true, + 'no_blank_lines_after_class_opening' => true, + 'no_leading_import_slash' => true, + 'no_whitespace_in_blank_line' => true, + 'ordered_class_elements' => [ + 'order' => [ + 'use_trait', + ], + ], + 'ordered_imports' => [ + 'imports_order' => [ + 'class', + 'function', + 'const', + ], + 'sort_algorithm' => 'none', + ], + 'return_type_declaration' => true, + 'short_scalar_cast' => true, + 'single_import_per_statement' => ['group_to_single_imports' => false], + 'single_trait_insert_per_statement' => true, + 'ternary_operator_spaces' => true, + 'unary_operator_spaces' => true, + 'visibility_required' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PSR-12 `_ standard.'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR1Set.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR1Set.php new file mode 100644 index 00000000..3c82ea56 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR1Set.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + */ +final class PSR1Set extends AbstractRuleSetDescription +{ + public function getRules(): array + { + return [ + 'encoding' => true, + 'full_opening_tag' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PSR-1 `_ standard.'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR2Set.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR2Set.php new file mode 100644 index 00000000..19d023d7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR2Set.php @@ -0,0 +1,70 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + */ +final class PSR2Set extends AbstractRuleSetDescription +{ + public function getRules(): array + { + return [ + '@PSR1' => true, + 'blank_line_after_namespace' => true, + 'braces_position' => true, + 'class_definition' => true, + 'constant_case' => true, + 'control_structure_braces' => true, + 'control_structure_continuation_position' => true, + 'elseif' => true, + 'function_declaration' => true, + 'indentation_type' => true, + 'line_ending' => true, + 'lowercase_keywords' => true, + 'method_argument_space' => [ + 'attribute_placement' => 'ignore', + 'on_multiline' => 'ensure_fully_multiline', + ], + 'no_break_comment' => true, + 'no_closing_tag' => true, + 'no_multiple_statements_per_line' => true, + 'no_space_around_double_colon' => true, + 'no_spaces_after_function_name' => true, + 'no_trailing_whitespace' => true, + 'no_trailing_whitespace_in_comment' => true, + 'single_blank_line_at_eof' => true, + 'single_class_element_per_statement' => [ + 'elements' => [ + 'property', + ], + ], + 'single_import_per_statement' => true, + 'single_line_after_imports' => true, + 'spaces_inside_parentheses' => true, + 'statement_indentation' => true, + 'switch_case_semicolon_to_colon' => true, + 'switch_case_space' => true, + 'visibility_required' => ['elements' => ['method', 'property']], + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PSR-2 `_ standard.'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerRiskySet.php new file mode 100644 index 00000000..b90dcbad --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerRiskySet.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + */ +final class PhpCsFixerRiskySet extends AbstractRuleSetDescription +{ + public function getRules(): array + { + return [ + '@PER-CS:risky' => true, + '@Symfony:risky' => true, + 'comment_to_phpdoc' => true, + 'final_internal_class' => true, + 'get_class_to_class_keyword' => false, + 'modernize_strpos' => false, + // @TODO: consider switching to `true`, like in @Symfony + 'native_constant_invocation' => [ + 'fix_built_in' => false, + 'include' => [ + 'DIRECTORY_SEPARATOR', + 'PHP_INT_SIZE', + 'PHP_SAPI', + 'PHP_VERSION_ID', + ], + 'scope' => 'namespaced', + 'strict' => true, + ], + 'no_alias_functions' => [ + 'sets' => [ + '@all', + ], + ], + 'no_unreachable_default_argument_value' => true, + 'no_unset_on_property' => true, + 'php_unit_data_provider_name' => true, + 'php_unit_data_provider_return_type' => true, + 'php_unit_strict' => true, + 'php_unit_test_case_static_method_calls' => ['call_type' => 'self'], + 'static_lambda' => true, + 'strict_comparison' => true, + 'strict_param' => true, + 'yield_from_array_to_yields' => true, + ]; + } + + public function getDescription(): string + { + return 'Rule set as used by the PHP-CS-Fixer development team, highly opinionated.'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerSet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerSet.php new file mode 100644 index 00000000..f9fa314f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerSet.php @@ -0,0 +1,128 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + */ +final class PhpCsFixerSet extends AbstractRuleSetDescription +{ + public function getRules(): array + { + return [ + '@PER-CS' => true, + '@Symfony' => true, + 'array_indentation' => true, + 'blank_line_before_statement' => [ + 'statements' => [ + 'break', + 'case', + 'continue', + 'declare', + 'default', + 'exit', + 'goto', + 'include', + 'include_once', + 'phpdoc', + 'require', + 'require_once', + 'return', + 'switch', + 'throw', + 'try', + 'yield', + 'yield_from', + ], + ], + 'combine_consecutive_issets' => true, + 'combine_consecutive_unsets' => true, + 'empty_loop_body' => true, + 'escape_implicit_backslashes' => true, + 'explicit_indirect_variable' => true, + 'explicit_string_variable' => true, + 'heredoc_to_nowdoc' => true, + 'method_argument_space' => [ + 'on_multiline' => 'ensure_fully_multiline', + ], + 'method_chaining_indentation' => true, + 'multiline_comment_opening_closing' => true, + 'multiline_whitespace_before_semicolons' => [ + 'strategy' => 'new_line_for_chained_calls', + ], + 'no_extra_blank_lines' => [ + 'tokens' => [ + 'attribute', + 'break', + 'case', + 'continue', + 'curly_brace_block', + 'default', + 'extra', + 'parenthesis_brace_block', + 'return', + 'square_brace_block', + 'switch', + 'throw', + 'use', + ], + ], + 'no_superfluous_elseif' => true, + 'no_superfluous_phpdoc_tags' => [ + 'allow_mixed' => true, + 'remove_inheritdoc' => true, + ], + 'no_unneeded_control_parentheses' => [ + 'statements' => [ + 'break', + 'clone', + 'continue', + 'echo_print', + 'negative_instanceof', + 'others', + 'return', + 'switch_case', + 'yield', + 'yield_from', + ], + ], + 'no_useless_else' => true, + 'no_useless_return' => true, + 'nullable_type_declaration_for_default_null_value' => false, + 'ordered_class_elements' => true, + 'ordered_types' => true, + 'php_unit_internal_class' => true, + 'php_unit_test_class_requires_covers' => true, + 'phpdoc_add_missing_param_annotation' => true, + 'phpdoc_no_empty_return' => true, + 'phpdoc_order_by_value' => true, + 'phpdoc_types_order' => true, + 'phpdoc_var_annotation_correct_order' => true, + 'protected_to_private' => true, + 'return_assignment' => true, + 'self_static_accessor' => true, + 'single_line_comment_style' => true, + 'single_line_throw' => false, + 'whitespace_after_comma_in_array' => ['ensure_single_space' => true], + ]; + } + + public function getDescription(): string + { + return 'Rule set as used by the PHP-CS-Fixer development team, highly opinionated.'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonyRiskySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonyRiskySet.php new file mode 100644 index 00000000..bd9221bf --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonyRiskySet.php @@ -0,0 +1,79 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + */ +final class SymfonyRiskySet extends AbstractRuleSetDescription +{ + public function getRules(): array + { + return [ + '@PHP56Migration:risky' => true, + '@PSR12:risky' => true, + 'array_push' => true, + 'combine_nested_dirname' => true, + 'dir_constant' => true, + 'ereg_to_preg' => true, + 'error_suppression' => true, + 'fopen_flag_order' => true, + 'fopen_flags' => [ + 'b_mode' => false, + ], + 'function_to_constant' => true, + 'get_class_to_class_keyword' => true, + 'implode_call' => true, + 'is_null' => true, + 'logical_operators' => true, + 'long_to_shorthand_operator' => true, + 'modernize_strpos' => true, + 'modernize_types_casting' => true, + 'native_constant_invocation' => ['strict' => false], + 'native_function_invocation' => [ + 'include' => [ + '@compiler_optimized', + ], + 'scope' => 'namespaced', + 'strict' => true, + ], + 'no_alias_functions' => true, + 'no_homoglyph_names' => true, + 'no_php4_constructor' => true, + 'no_unneeded_final_method' => true, + 'no_unreachable_default_argument_value' => false, + 'no_useless_sprintf' => true, + 'non_printable_character' => true, + 'ordered_traits' => true, + 'php_unit_construct' => true, + 'php_unit_mock_short_will_return' => true, + 'php_unit_set_up_tear_down_visibility' => true, + 'php_unit_test_annotation' => true, + 'psr_autoloading' => true, + 'self_accessor' => true, + 'set_type_to_cast' => true, + 'string_length_to_empty' => true, + 'string_line_ending' => true, + 'ternary_to_elvis_operator' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow the official `Symfony Coding Standards `_.'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonySet.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonySet.php new file mode 100644 index 00000000..d2b1f177 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonySet.php @@ -0,0 +1,223 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\Phpdoc\PhpdocSeparationFixer; +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; + +/** + * @internal + */ +final class SymfonySet extends AbstractRuleSetDescription +{ + public function getRules(): array + { + return [ + '@PSR12' => true, + 'align_multiline_comment' => true, + 'array_syntax' => true, + 'backtick_to_shell_exec' => true, + 'binary_operator_spaces' => true, + 'blank_line_before_statement' => [ + 'statements' => [ + 'return', + ], + ], + 'braces_position' => [ + 'allow_single_line_anonymous_functions' => true, + 'allow_single_line_empty_anonymous_classes' => true, + ], + 'cast_spaces' => true, + 'class_attributes_separation' => [ + 'elements' => [ + 'method' => 'one', + ], + ], + 'class_definition' => [ + 'single_line' => true, + ], + 'class_reference_name_casing' => true, + 'clean_namespace' => true, + 'concat_space' => true, + 'declare_parentheses' => true, + 'echo_tag_syntax' => true, + 'empty_loop_body' => ['style' => 'braces'], + 'empty_loop_condition' => true, + 'fully_qualified_strict_types' => true, + 'general_phpdoc_tag_rename' => [ + 'replacements' => [ + 'inheritDocs' => 'inheritDoc', + ], + ], + 'global_namespace_import' => [ + 'import_classes' => false, + 'import_constants' => false, + 'import_functions' => false, + ], + 'include' => true, + 'increment_style' => true, + 'integer_literal_case' => true, + 'lambda_not_used_import' => true, + 'linebreak_after_opening_tag' => true, + 'magic_constant_casing' => true, + 'magic_method_casing' => true, + 'method_argument_space' => [ + 'on_multiline' => 'ignore', + ], + 'native_function_casing' => true, + 'native_type_declaration_casing' => true, + 'no_alias_language_construct_call' => true, + 'no_alternative_syntax' => true, + 'no_binary_string' => true, + 'no_blank_lines_after_phpdoc' => true, + 'no_empty_comment' => true, + 'no_empty_phpdoc' => true, + 'no_empty_statement' => true, + 'no_extra_blank_lines' => [ + 'tokens' => [ + 'attribute', + 'case', + 'continue', + 'curly_brace_block', + 'default', + 'extra', + 'parenthesis_brace_block', + 'square_brace_block', + 'switch', + 'throw', + 'use', + ], + ], + 'no_leading_namespace_whitespace' => true, + 'no_mixed_echo_print' => true, + 'no_multiline_whitespace_around_double_arrow' => true, + 'no_null_property_initialization' => true, + 'no_short_bool_cast' => true, + 'no_singleline_whitespace_before_semicolons' => true, + 'no_spaces_around_offset' => true, + 'no_superfluous_phpdoc_tags' => [ + 'remove_inheritdoc' => true, + ], + 'no_trailing_comma_in_singleline' => true, + 'no_unneeded_braces' => [ + 'namespaces' => true, + ], + 'no_unneeded_control_parentheses' => [ + 'statements' => [ + 'break', + 'clone', + 'continue', + 'echo_print', + 'others', + 'return', + 'switch_case', + 'yield', + 'yield_from', + ], + ], + 'no_unneeded_import_alias' => true, + 'no_unset_cast' => true, + 'no_unused_imports' => true, + 'no_useless_concat_operator' => true, + 'no_useless_nullsafe_operator' => true, + 'no_whitespace_before_comma_in_array' => true, + 'normalize_index_brace' => true, + 'nullable_type_declaration_for_default_null_value' => ['use_nullable_type_declaration' => false], + 'object_operator_without_whitespace' => true, + 'operator_linebreak' => [ + 'only_booleans' => true, + ], + 'ordered_imports' => [ + 'imports_order' => [ + 'class', + 'function', + 'const', + ], + 'sort_algorithm' => 'alpha', + ], + 'php_unit_fqcn_annotation' => true, + 'php_unit_method_casing' => true, + 'phpdoc_align' => true, + 'phpdoc_annotation_without_dot' => true, + 'phpdoc_indent' => true, + 'phpdoc_inline_tag_normalizer' => true, + 'phpdoc_no_access' => true, + 'phpdoc_no_alias_tag' => true, + 'phpdoc_no_package' => true, + 'phpdoc_no_useless_inheritdoc' => true, + 'phpdoc_order' => [ + 'order' => [ + 'param', + 'return', + 'throws', + ], + ], + 'phpdoc_return_self_reference' => true, + 'phpdoc_scalar' => true, + 'phpdoc_separation' => [ + 'groups' => [ + ['Annotation', 'NamedArgumentConstructor', 'Target'], + ...PhpdocSeparationFixer::OPTION_GROUPS_DEFAULT, + ], + ], + 'phpdoc_single_line_var_spacing' => true, + 'phpdoc_summary' => true, + 'phpdoc_tag_type' => [ + 'tags' => [ + 'inheritDoc' => 'inline', + ], + ], + 'phpdoc_to_comment' => true, + 'phpdoc_trim' => true, + 'phpdoc_trim_consecutive_blank_line_separation' => true, + 'phpdoc_types' => true, + 'phpdoc_types_order' => [ + 'null_adjustment' => 'always_last', + 'sort_algorithm' => 'none', + ], + 'phpdoc_var_without_name' => true, + 'semicolon_after_instruction' => true, + 'simple_to_complex_string_variable' => true, + 'single_class_element_per_statement' => true, + 'single_import_per_statement' => true, + 'single_line_comment_spacing' => true, + 'single_line_comment_style' => [ + 'comment_types' => [ + 'hash', + ], + ], + 'single_line_throw' => true, + 'single_quote' => true, + 'single_space_around_construct' => true, + 'space_after_semicolon' => [ + 'remove_in_empty_for_expressions' => true, + ], + 'standardize_increment' => true, + 'standardize_not_equals' => true, + 'switch_continue_to_break' => true, + 'trailing_comma_in_multiline' => true, + 'trim_array_spaces' => true, + 'type_declaration_spaces' => true, + 'types_spaces' => true, + 'whitespace_after_comma_in_array' => true, + 'yoda_style' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow the official `Symfony Coding Standards `_.'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Runner/FileCachingLintingIterator.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Runner/FileCachingLintingIterator.php new file mode 100644 index 00000000..c07dbbd2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Runner/FileCachingLintingIterator.php @@ -0,0 +1,84 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner; + +use PhpCsFixer\Linter\LinterInterface; +use PhpCsFixer\Linter\LintingResultInterface; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @extends \CachingIterator> + */ +final class FileCachingLintingIterator extends \CachingIterator +{ + private LinterInterface $linter; + + /** + * @var LintingResultInterface + */ + private $currentResult; + + /** + * @var LintingResultInterface + */ + private $nextResult; + + /** + * @param \Iterator $iterator + */ + public function __construct(\Iterator $iterator, LinterInterface $linter) + { + parent::__construct($iterator); + + $this->linter = $linter; + } + + public function currentLintingResult(): LintingResultInterface + { + return $this->currentResult; + } + + public function next(): void + { + parent::next(); + + $this->currentResult = $this->nextResult; + + if ($this->hasNext()) { + $this->nextResult = $this->handleItem($this->getInnerIterator()->current()); + } + } + + public function rewind(): void + { + parent::rewind(); + + if ($this->valid()) { + $this->currentResult = $this->handleItem($this->current()); + } + + if ($this->hasNext()) { + $this->nextResult = $this->handleItem($this->getInnerIterator()->current()); + } + } + + private function handleItem(\SplFileInfo $file): LintingResultInterface + { + return $this->linter->lintFile($file->getRealPath()); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Runner/FileFilterIterator.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Runner/FileFilterIterator.php new file mode 100644 index 00000000..c0f736fd --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Runner/FileFilterIterator.php @@ -0,0 +1,111 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner; + +use PhpCsFixer\Cache\CacheManagerInterface; +use PhpCsFixer\FileReader; +use PhpCsFixer\FixerFileProcessedEvent; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Contracts\EventDispatcher\Event; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @extends \FilterIterator> + */ +final class FileFilterIterator extends \FilterIterator +{ + private ?EventDispatcherInterface $eventDispatcher; + + private CacheManagerInterface $cacheManager; + + /** + * @var array + */ + private array $visitedElements = []; + + /** + * @param \Traversable<\SplFileInfo> $iterator + */ + public function __construct( + \Traversable $iterator, + ?EventDispatcherInterface $eventDispatcher, + CacheManagerInterface $cacheManager + ) { + if (!$iterator instanceof \Iterator) { + $iterator = new \IteratorIterator($iterator); + } + + parent::__construct($iterator); + + $this->eventDispatcher = $eventDispatcher; + $this->cacheManager = $cacheManager; + } + + public function accept(): bool + { + $file = $this->current(); + if (!$file instanceof \SplFileInfo) { + throw new \RuntimeException( + sprintf( + 'Expected instance of "\SplFileInfo", got "%s".', + get_debug_type($file) + ) + ); + } + + $path = $file->isLink() ? $file->getPathname() : $file->getRealPath(); + + if (isset($this->visitedElements[$path])) { + return false; + } + + $this->visitedElements[$path] = true; + + if (!$file->isFile() || $file->isLink()) { + return false; + } + + $content = FileReader::createSingleton()->read($path); + + // mark as skipped: + if ( + // empty file + '' === $content + // file that does not need fixing due to cache + || !$this->cacheManager->needFixing($file->getPathname(), $content) + ) { + $this->dispatchEvent( + FixerFileProcessedEvent::NAME, + new FixerFileProcessedEvent(FixerFileProcessedEvent::STATUS_SKIPPED) + ); + + return false; + } + + return true; + } + + private function dispatchEvent(string $name, Event $event): void + { + if (null === $this->eventDispatcher) { + return; + } + + $this->eventDispatcher->dispatch($event, $name); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Runner/FileLintingIterator.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Runner/FileLintingIterator.php new file mode 100644 index 00000000..09f5913e --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Runner/FileLintingIterator.php @@ -0,0 +1,69 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner; + +use PhpCsFixer\Linter\LinterInterface; +use PhpCsFixer\Linter\LintingResultInterface; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @extends \IteratorIterator> + */ +final class FileLintingIterator extends \IteratorIterator +{ + /** + * @var LintingResultInterface + */ + private $currentResult; + + private LinterInterface $linter; + + /** + * @param \Iterator $iterator + */ + public function __construct(\Iterator $iterator, LinterInterface $linter) + { + parent::__construct($iterator); + + $this->linter = $linter; + } + + public function currentLintingResult(): ?LintingResultInterface + { + return $this->currentResult; + } + + public function next(): void + { + parent::next(); + + $this->currentResult = $this->valid() ? $this->handleItem($this->current()) : null; + } + + public function rewind(): void + { + parent::rewind(); + + $this->currentResult = $this->valid() ? $this->handleItem($this->current()) : null; + } + + private function handleItem(\SplFileInfo $file): LintingResultInterface + { + return $this->linter->lintFile($file->getRealPath()); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Runner/Runner.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Runner/Runner.php new file mode 100644 index 00000000..7a3bc822 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Runner/Runner.php @@ -0,0 +1,300 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Cache\CacheManagerInterface; +use PhpCsFixer\Cache\Directory; +use PhpCsFixer\Cache\DirectoryInterface; +use PhpCsFixer\Differ\DifferInterface; +use PhpCsFixer\Error\Error; +use PhpCsFixer\Error\ErrorsManager; +use PhpCsFixer\FileReader; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\FixerFileProcessedEvent; +use PhpCsFixer\Linter\LinterInterface; +use PhpCsFixer\Linter\LintingException; +use PhpCsFixer\Linter\LintingResultInterface; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\Filesystem\Exception\IOException; +use Symfony\Contracts\EventDispatcher\Event; + +/** + * @author Dariusz Rumiński + */ +final class Runner +{ + private DifferInterface $differ; + + private ?DirectoryInterface $directory; + + private ?EventDispatcherInterface $eventDispatcher; + + private ErrorsManager $errorsManager; + + private CacheManagerInterface $cacheManager; + + private bool $isDryRun; + + private LinterInterface $linter; + + /** + * @var \Traversable<\SplFileInfo> + */ + private $finder; + + /** + * @var list + */ + private array $fixers; + + private bool $stopOnViolation; + + /** + * @param \Traversable<\SplFileInfo> $finder + * @param list $fixers + */ + public function __construct( + \Traversable $finder, + array $fixers, + DifferInterface $differ, + ?EventDispatcherInterface $eventDispatcher, + ErrorsManager $errorsManager, + LinterInterface $linter, + bool $isDryRun, + CacheManagerInterface $cacheManager, + ?DirectoryInterface $directory = null, + bool $stopOnViolation = false + ) { + $this->finder = $finder; + $this->fixers = $fixers; + $this->differ = $differ; + $this->eventDispatcher = $eventDispatcher; + $this->errorsManager = $errorsManager; + $this->linter = $linter; + $this->isDryRun = $isDryRun; + $this->cacheManager = $cacheManager; + $this->directory = $directory ?? new Directory(''); + $this->stopOnViolation = $stopOnViolation; + } + + /** + * @return array, diff: string}> + */ + public function fix(): array + { + $changed = []; + + $finder = $this->finder; + $finderIterator = $finder instanceof \IteratorAggregate ? $finder->getIterator() : $finder; + $fileFilteredFileIterator = new FileFilterIterator( + $finderIterator, + $this->eventDispatcher, + $this->cacheManager + ); + + $collection = $this->linter->isAsync() + ? new FileCachingLintingIterator($fileFilteredFileIterator, $this->linter) + : new FileLintingIterator($fileFilteredFileIterator, $this->linter); + + foreach ($collection as $file) { + $fixInfo = $this->fixFile($file, $collection->currentLintingResult()); + + // we do not need Tokens to still caching just fixed file - so clear the cache + Tokens::clearCache(); + + if (null !== $fixInfo) { + $name = $this->directory->getRelativePathTo($file->__toString()); + $changed[$name] = $fixInfo; + + if ($this->stopOnViolation) { + break; + } + } + } + + return $changed; + } + + /** + * @return null|array{appliedFixers: list, diff: string} + */ + private function fixFile(\SplFileInfo $file, LintingResultInterface $lintingResult): ?array + { + $name = $file->getPathname(); + + try { + $lintingResult->check(); + } catch (LintingException $e) { + $this->dispatchEvent( + FixerFileProcessedEvent::NAME, + new FixerFileProcessedEvent(FixerFileProcessedEvent::STATUS_INVALID) + ); + + $this->errorsManager->report(new Error(Error::TYPE_INVALID, $name, $e)); + + return null; + } + + $old = FileReader::createSingleton()->read($file->getRealPath()); + + $tokens = Tokens::fromCode($old); + $oldHash = $tokens->getCodeHash(); + + $newHash = $oldHash; + $new = $old; + + $appliedFixers = []; + + try { + foreach ($this->fixers as $fixer) { + // for custom fixers we don't know is it safe to run `->fix()` without checking `->supports()` and `->isCandidate()`, + // thus we need to check it and conditionally skip fixing + if ( + !$fixer instanceof AbstractFixer + && (!$fixer->supports($file) || !$fixer->isCandidate($tokens)) + ) { + continue; + } + + $fixer->fix($file, $tokens); + + if ($tokens->isChanged()) { + $tokens->clearEmptyTokens(); + $tokens->clearChanged(); + $appliedFixers[] = $fixer->getName(); + } + } + } catch (\ParseError $e) { + $this->dispatchEvent( + FixerFileProcessedEvent::NAME, + new FixerFileProcessedEvent(FixerFileProcessedEvent::STATUS_LINT) + ); + + $this->errorsManager->report(new Error(Error::TYPE_LINT, $name, $e)); + + return null; + } catch (\Throwable $e) { + $this->processException($name, $e); + + return null; + } + + $fixInfo = null; + + if ([] !== $appliedFixers) { + $new = $tokens->generateCode(); + $newHash = $tokens->getCodeHash(); + } + + // We need to check if content was changed and then applied changes. + // But we can't simply check $appliedFixers, because one fixer may revert + // work of other and both of them will mark collection as changed. + // Therefore we need to check if code hashes changed. + if ($oldHash !== $newHash) { + $fixInfo = [ + 'appliedFixers' => $appliedFixers, + 'diff' => $this->differ->diff($old, $new, $file), + ]; + + try { + $this->linter->lintSource($new)->check(); + } catch (LintingException $e) { + $this->dispatchEvent( + FixerFileProcessedEvent::NAME, + new FixerFileProcessedEvent(FixerFileProcessedEvent::STATUS_LINT) + ); + + $this->errorsManager->report(new Error(Error::TYPE_LINT, $name, $e, $fixInfo['appliedFixers'], $fixInfo['diff'])); + + return null; + } + + if (!$this->isDryRun) { + $fileName = $file->getRealPath(); + + if (!file_exists($fileName)) { + throw new IOException( + sprintf('Failed to write file "%s" (no longer) exists.', $file->getPathname()), + 0, + null, + $file->getPathname() + ); + } + + if (is_dir($fileName)) { + throw new IOException( + sprintf('Cannot write file "%s" as the location exists as directory.', $fileName), + 0, + null, + $fileName + ); + } + + if (!is_writable($fileName)) { + throw new IOException( + sprintf('Cannot write to file "%s" as it is not writable.', $fileName), + 0, + null, + $fileName + ); + } + + if (false === @file_put_contents($fileName, $new)) { + $error = error_get_last(); + + throw new IOException( + sprintf('Failed to write file "%s", "%s".', $fileName, null !== $error ? $error['message'] : 'no reason available'), + 0, + null, + $fileName + ); + } + } + } + + $this->cacheManager->setFile($name, $new); + + $this->dispatchEvent( + FixerFileProcessedEvent::NAME, + new FixerFileProcessedEvent(null !== $fixInfo ? FixerFileProcessedEvent::STATUS_FIXED : FixerFileProcessedEvent::STATUS_NO_CHANGES) + ); + + return $fixInfo; + } + + /** + * Process an exception that occurred. + */ + private function processException(string $name, \Throwable $e): void + { + $this->dispatchEvent( + FixerFileProcessedEvent::NAME, + new FixerFileProcessedEvent(FixerFileProcessedEvent::STATUS_EXCEPTION) + ); + + $this->errorsManager->report(new Error(Error::TYPE_EXCEPTION, $name, $e)); + } + + private function dispatchEvent(string $name, Event $event): void + { + if (null === $this->eventDispatcher) { + return; + } + + $this->eventDispatcher->dispatch($event, $name); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/StdinFileInfo.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/StdinFileInfo.php new file mode 100644 index 00000000..7ce19091 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/StdinFileInfo.php @@ -0,0 +1,171 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @author Davi Koscianski Vidal + * + * @internal + */ +final class StdinFileInfo extends \SplFileInfo +{ + public function __construct() + { + parent::__construct(__FILE__); + } + + public function __toString(): string + { + return $this->getRealPath(); + } + + public function getRealPath(): string + { + // So file_get_contents & friends will work. + // Warning - this stream is not seekable, so `file_get_contents` will work only once! Consider using `FileReader`. + return 'php://stdin'; + } + + public function getATime(): int + { + return 0; + } + + public function getBasename($suffix = null): string + { + return $this->getFilename(); + } + + public function getCTime(): int + { + return 0; + } + + public function getExtension(): string + { + return '.php'; + } + + public function getFileInfo($className = null): \SplFileInfo + { + throw new \BadMethodCallException(sprintf('Method "%s" is not implemented.', __METHOD__)); + } + + public function getFilename(): string + { + /* + * Useful so fixers depending on PHP-only files still work. + * + * The idea to use STDIN is to parse PHP-only files, so we can + * assume that there will be always a PHP file out there. + */ + + return 'stdin.php'; + } + + public function getGroup(): int + { + return 0; + } + + public function getInode(): int + { + return 0; + } + + public function getLinkTarget(): string + { + return ''; + } + + public function getMTime(): int + { + return 0; + } + + public function getOwner(): int + { + return 0; + } + + public function getPath(): string + { + return ''; + } + + public function getPathInfo($className = null): \SplFileInfo + { + throw new \BadMethodCallException(sprintf('Method "%s" is not implemented.', __METHOD__)); + } + + public function getPathname(): string + { + return $this->getFilename(); + } + + public function getPerms(): int + { + return 0; + } + + public function getSize(): int + { + return 0; + } + + public function getType(): string + { + return 'file'; + } + + public function isDir(): bool + { + return false; + } + + public function isExecutable(): bool + { + return false; + } + + public function isFile(): bool + { + return true; + } + + public function isLink(): bool + { + return false; + } + + public function isReadable(): bool + { + return true; + } + + public function isWritable(): bool + { + return false; + } + + public function openFile($openMode = 'r', $useIncludePath = false, $context = null): \SplFileObject + { + throw new \BadMethodCallException(sprintf('Method "%s" is not implemented.', __METHOD__)); + } + + public function setFileClass($className = null): void {} + + public function setInfoClass($className = null): void {} +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTransformer.php new file mode 100644 index 00000000..5c8de2eb --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTransformer.php @@ -0,0 +1,40 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +use PhpCsFixer\Utils; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +abstract class AbstractTransformer implements TransformerInterface +{ + public function getName(): string + { + $nameParts = explode('\\', static::class); + $name = substr(end($nameParts), 0, -\strlen('Transformer')); + + return Utils::camelCaseToUnderscore($name); + } + + public function getPriority(): int + { + return 0; + } + + abstract public function getCustomTokens(): array; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTypeTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTypeTransformer.php new file mode 100644 index 00000000..8c5476b4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTypeTransformer.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +abstract class AbstractTypeTransformer extends AbstractTransformer +{ + private const TYPE_END_TOKENS = [')', [T_CALLABLE], [T_NS_SEPARATOR], [T_STATIC], [T_STRING], [CT::T_ARRAY_TYPEHINT]]; + + private const TYPE_TOKENS = [ + '|', '&', '(', + ...self::TYPE_END_TOKENS, + [CT::T_TYPE_ALTERNATION], [CT::T_TYPE_INTERSECTION], // some siblings may already be transformed + [T_WHITESPACE], [T_COMMENT], [T_DOC_COMMENT], // technically these can be inside of type tokens array + ]; + + abstract protected function replaceToken(Tokens $tokens, int $index): void; + + /** + * @param array{0: int, 1: string}|string $originalToken + */ + protected function doProcess(Tokens $tokens, int $index, $originalToken): void + { + if (!$tokens[$index]->equals($originalToken)) { + return; + } + + if (!$this->isPartOfType($tokens, $index)) { + return; + } + + $this->replaceToken($tokens, $index); + } + + private function isPartOfType(Tokens $tokens, int $index): bool + { + // return types and non-capturing catches + $typeColonIndex = $tokens->getTokenNotOfKindSibling($index, -1, self::TYPE_TOKENS); + if ($tokens[$typeColonIndex]->isGivenKind([T_CATCH, CT::T_TYPE_COLON, T_CONST])) { + return true; + } + + // for parameter there will be splat operator or variable after the type ("&" is ambiguous and can be reference or bitwise and) + $afterTypeIndex = $tokens->getTokenNotOfKindSibling($index, 1, self::TYPE_TOKENS); + + if ($tokens[$afterTypeIndex]->isGivenKind(T_ELLIPSIS)) { + return true; + } + + if (!$tokens[$afterTypeIndex]->isGivenKind(T_VARIABLE)) { + return false; + } + + $beforeVariableIndex = $tokens->getPrevMeaningfulToken($afterTypeIndex); + if ($tokens[$beforeVariableIndex]->equals('&')) { + $prevIndex = $tokens->getPrevTokenOfKind( + $index, + [ + '{', + '}', + ';', + [T_CLOSE_TAG], + [T_FN], + [T_FUNCTION], + ], + ); + + return null !== $prevIndex && $tokens[$prevIndex]->isGivenKind([T_FN, T_FUNCTION]); + } + + return $tokens[$beforeVariableIndex]->equalsAny(self::TYPE_END_TOKENS); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AlternativeSyntaxAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AlternativeSyntaxAnalyzer.php new file mode 100644 index 00000000..723d4c95 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AlternativeSyntaxAnalyzer.php @@ -0,0 +1,116 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @TODO 4.0 remove this analyzer and move this logic into a transformer + */ +final class AlternativeSyntaxAnalyzer +{ + private const ALTERNATIVE_SYNTAX_BLOCK_EDGES = [ + T_IF => [T_ENDIF, T_ELSE, T_ELSEIF], + T_ELSE => [T_ENDIF], + T_ELSEIF => [T_ENDIF, T_ELSE, T_ELSEIF], + T_FOR => [T_ENDFOR], + T_FOREACH => [T_ENDFOREACH], + T_WHILE => [T_ENDWHILE], + T_SWITCH => [T_ENDSWITCH], + ]; + + public function belongsToAlternativeSyntax(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->equals(':')) { + return false; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prevIndex]->isGivenKind(T_ELSE)) { + return true; + } + + if (!$tokens[$prevIndex]->equals(')')) { + return false; + } + + $openParenthesisIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $prevIndex); + $beforeOpenParenthesisIndex = $tokens->getPrevMeaningfulToken($openParenthesisIndex); + + return $tokens[$beforeOpenParenthesisIndex]->isGivenKind([ + T_DECLARE, + T_ELSEIF, + T_FOR, + T_FOREACH, + T_IF, + T_SWITCH, + T_WHILE, + ]); + } + + public function findAlternativeSyntaxBlockEnd(Tokens $tokens, int $index): int + { + if (!isset($tokens[$index])) { + throw new \InvalidArgumentException("There is no token at index {$index}."); + } + + if (!$this->isStartOfAlternativeSyntaxBlock($tokens, $index)) { + throw new \InvalidArgumentException("Token at index {$index} is not the start of an alternative syntax block."); + } + + $startTokenKind = $tokens[$index]->getId(); + $endTokenKinds = self::ALTERNATIVE_SYNTAX_BLOCK_EDGES[$startTokenKind]; + + $findKinds = [[$startTokenKind]]; + foreach ($endTokenKinds as $endTokenKind) { + $findKinds[] = [$endTokenKind]; + } + + while (true) { + $index = $tokens->getNextTokenOfKind($index, $findKinds); + + if ($tokens[$index]->isGivenKind($endTokenKinds)) { + return $index; + } + + if ($this->isStartOfAlternativeSyntaxBlock($tokens, $index)) { + $index = $this->findAlternativeSyntaxBlockEnd($tokens, $index); + } + } + } + + private function isStartOfAlternativeSyntaxBlock(Tokens $tokens, int $index): bool + { + $map = self::ALTERNATIVE_SYNTAX_BLOCK_EDGES; + $startTokenKind = $tokens[$index]->getId(); + + if (null === $startTokenKind || !isset($map[$startTokenKind])) { + return false; + } + + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->equals('(')) { + $index = $tokens->getNextMeaningfulToken( + $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index) + ); + } + + return $tokens[$index]->equals(':'); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/AbstractControlCaseStructuresAnalysis.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/AbstractControlCaseStructuresAnalysis.php new file mode 100644 index 00000000..a2bc675f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/AbstractControlCaseStructuresAnalysis.php @@ -0,0 +1,49 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +abstract class AbstractControlCaseStructuresAnalysis +{ + private int $index; + + private int $open; + + private int $close; + + public function __construct(int $index, int $open, int $close) + { + $this->index = $index; + $this->open = $open; + $this->close = $close; + } + + public function getIndex(): int + { + return $this->index; + } + + public function getOpenIndex(): int + { + return $this->open; + } + + public function getCloseIndex(): int + { + return $this->close; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php new file mode 100644 index 00000000..a4e72a70 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php @@ -0,0 +1,79 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class ArgumentAnalysis +{ + /** + * The name of the argument. + */ + private ?string $name; + + /** + * The index where the name is located in the supplied Tokens object. + */ + private ?int $nameIndex; + + /** + * The default value of the argument. + */ + private ?string $default; + + /** + * The type analysis of the argument. + */ + private ?TypeAnalysis $typeAnalysis; + + public function __construct(?string $name, ?int $nameIndex, ?string $default, ?TypeAnalysis $typeAnalysis = null) + { + $this->name = $name; + $this->nameIndex = $nameIndex; + $this->default = $default ?? null; + $this->typeAnalysis = $typeAnalysis ?? null; + } + + public function getDefault(): ?string + { + return $this->default; + } + + public function hasDefault(): bool + { + return null !== $this->default; + } + + public function getName(): ?string + { + return $this->name; + } + + public function getNameIndex(): ?int + { + return $this->nameIndex; + } + + public function getTypeAnalysis(): ?TypeAnalysis + { + return $this->typeAnalysis; + } + + public function hasTypeAnalysis(): bool + { + return null !== $this->typeAnalysis; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php new file mode 100644 index 00000000..df8c0dc3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php @@ -0,0 +1,43 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @author Kuba Werłos + * + * @internal + */ +final class CaseAnalysis +{ + private int $index; + + private int $colonIndex; + + public function __construct(int $index, int $colonIndex) + { + $this->index = $index; + $this->colonIndex = $colonIndex; + } + + public function getIndex(): int + { + return $this->index; + } + + public function getColonIndex(): int + { + return $this->colonIndex; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DataProviderAnalysis.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DataProviderAnalysis.php new file mode 100644 index 00000000..75490d76 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DataProviderAnalysis.php @@ -0,0 +1,53 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +final class DataProviderAnalysis +{ + private string $name; + + private int $nameIndex; + + /** @var array */ + private array $usageIndices; + + /** + * @param array $usageIndices + */ + public function __construct(string $name, int $nameIndex, array $usageIndices) + { + $this->name = $name; + $this->nameIndex = $nameIndex; + $this->usageIndices = $usageIndices; + } + + public function getName(): string + { + return $this->name; + } + + public function getNameIndex(): int + { + return $this->nameIndex; + } + + /** + * @return array + */ + public function getUsageIndices(): array + { + return $this->usageIndices; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DefaultAnalysis.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DefaultAnalysis.php new file mode 100644 index 00000000..b742b29a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DefaultAnalysis.php @@ -0,0 +1,41 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class DefaultAnalysis +{ + private int $index; + + private int $colonIndex; + + public function __construct(int $index, int $colonIndex) + { + $this->index = $index; + $this->colonIndex = $colonIndex; + } + + public function getIndex(): int + { + return $this->index; + } + + public function getColonIndex(): int + { + return $this->colonIndex; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/EnumAnalysis.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/EnumAnalysis.php new file mode 100644 index 00000000..6260cca1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/EnumAnalysis.php @@ -0,0 +1,44 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class EnumAnalysis extends AbstractControlCaseStructuresAnalysis +{ + /** + * @var list + */ + private array $cases; + + /** + * @param list $cases + */ + public function __construct(int $index, int $open, int $close, array $cases) + { + parent::__construct($index, $open, $close); + + $this->cases = $cases; + } + + /** + * @return list + */ + public function getCases(): array + { + return $this->cases; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/MatchAnalysis.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/MatchAnalysis.php new file mode 100644 index 00000000..2ac1b977 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/MatchAnalysis.php @@ -0,0 +1,35 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class MatchAnalysis extends AbstractControlCaseStructuresAnalysis +{ + private ?DefaultAnalysis $defaultAnalysis; + + public function __construct(int $index, int $open, int $close, ?DefaultAnalysis $defaultAnalysis) + { + parent::__construct($index, $open, $close); + + $this->defaultAnalysis = $defaultAnalysis; + } + + public function getDefaultAnalysis(): ?DefaultAnalysis + { + return $this->defaultAnalysis; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php new file mode 100644 index 00000000..6702a122 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php @@ -0,0 +1,96 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class NamespaceAnalysis implements StartEndTokenAwareAnalysis +{ + /** + * The fully qualified namespace name. + */ + private string $fullName; + + /** + * The short version of the namespace. + */ + private string $shortName; + + /** + * The start index of the namespace declaration in the analyzed Tokens. + */ + private int $startIndex; + + /** + * The end index of the namespace declaration in the analyzed Tokens. + */ + private int $endIndex; + + /** + * The start index of the scope of the namespace in the analyzed Tokens. + */ + private int $scopeStartIndex; + + /** + * The end index of the scope of the namespace in the analyzed Tokens. + */ + private int $scopeEndIndex; + + public function __construct(string $fullName, string $shortName, int $startIndex, int $endIndex, int $scopeStartIndex, int $scopeEndIndex) + { + $this->fullName = $fullName; + $this->shortName = $shortName; + $this->startIndex = $startIndex; + $this->endIndex = $endIndex; + $this->scopeStartIndex = $scopeStartIndex; + $this->scopeEndIndex = $scopeEndIndex; + } + + public function getFullName(): string + { + return $this->fullName; + } + + public function getShortName(): string + { + return $this->shortName; + } + + public function getStartIndex(): int + { + return $this->startIndex; + } + + public function getEndIndex(): int + { + return $this->endIndex; + } + + public function getScopeStartIndex(): int + { + return $this->scopeStartIndex; + } + + public function getScopeEndIndex(): int + { + return $this->scopeEndIndex; + } + + public function isGlobalNamespace(): bool + { + return '' === $this->getFullName(); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php new file mode 100644 index 00000000..59127b2f --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php @@ -0,0 +1,110 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class NamespaceUseAnalysis implements StartEndTokenAwareAnalysis +{ + public const TYPE_CLASS = 1; // "classy" could be class, interface or trait + public const TYPE_FUNCTION = 2; + public const TYPE_CONSTANT = 3; + + /** + * The fully qualified use namespace. + */ + private string $fullName; + + /** + * The short version of use namespace or the alias name in case of aliased use statements. + */ + private string $shortName; + + /** + * Is the use statement being aliased? + */ + private bool $isAliased; + + /** + * The start index of the namespace declaration in the analyzed Tokens. + */ + private int $startIndex; + + /** + * The end index of the namespace declaration in the analyzed Tokens. + */ + private int $endIndex; + + /** + * The type of import: class, function or constant. + */ + private int $type; + + public function __construct(string $fullName, string $shortName, bool $isAliased, int $startIndex, int $endIndex, int $type) + { + $this->fullName = $fullName; + $this->shortName = $shortName; + $this->isAliased = $isAliased; + $this->startIndex = $startIndex; + $this->endIndex = $endIndex; + $this->type = $type; + } + + public function getFullName(): string + { + return $this->fullName; + } + + public function getShortName(): string + { + return $this->shortName; + } + + public function isAliased(): bool + { + return $this->isAliased; + } + + public function getStartIndex(): int + { + return $this->startIndex; + } + + public function getEndIndex(): int + { + return $this->endIndex; + } + + public function getType(): int + { + return $this->type; + } + + public function isClass(): bool + { + return self::TYPE_CLASS === $this->type; + } + + public function isFunction(): bool + { + return self::TYPE_FUNCTION === $this->type; + } + + public function isConstant(): bool + { + return self::TYPE_CONSTANT === $this->type; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/StartEndTokenAwareAnalysis.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/StartEndTokenAwareAnalysis.php new file mode 100644 index 00000000..0b2f318b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/StartEndTokenAwareAnalysis.php @@ -0,0 +1,28 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +interface StartEndTokenAwareAnalysis +{ + /** + * The start index of the analyzed subject inside of the Tokens. + */ + public function getStartIndex(): int; + + /** + * The end index of the analyzed subject inside of the Tokens. + */ + public function getEndIndex(): int; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php new file mode 100644 index 00000000..f81b48e2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php @@ -0,0 +1,52 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class SwitchAnalysis extends AbstractControlCaseStructuresAnalysis +{ + /** + * @var list + */ + private array $cases; + + private ?DefaultAnalysis $defaultAnalysis; + + /** + * @param list $cases + */ + public function __construct(int $index, int $open, int $close, array $cases, ?DefaultAnalysis $defaultAnalysis) + { + parent::__construct($index, $open, $close); + + $this->cases = $cases; + $this->defaultAnalysis = $defaultAnalysis; + } + + /** + * @return list + */ + public function getCases(): array + { + return $this->cases; + } + + public function getDefaultAnalysis(): ?DefaultAnalysis + { + return $this->defaultAnalysis; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php new file mode 100644 index 00000000..a332b244 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php @@ -0,0 +1,107 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class TypeAnalysis implements StartEndTokenAwareAnalysis +{ + /** + * This list contains soft and hard reserved types that can be used or will be used by PHP at some point. + * + * More info: + * + * @see https://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.types + * @see https://php.net/manual/en/reserved.other-reserved-words.php + * @see https://php.net/manual/en/language.pseudo-types.php + * + * @var list + */ + private static array $reservedTypes = [ + 'array', + 'bool', + 'callable', + 'false', + 'float', + 'int', + 'iterable', + 'mixed', + 'never', + 'null', + 'object', + 'parent', + 'resource', + 'self', + 'static', + 'string', + 'true', + 'void', + ]; + + private string $name; + + private int $startIndex; + + private int $endIndex; + + private bool $nullable; + + /** + * @param ($startIndex is null ? null : int) $endIndex + */ + public function __construct(string $name, int $startIndex = null, int $endIndex = null) + { + $this->name = $name; + $this->nullable = false; + + if (str_starts_with($name, '?')) { + $this->name = substr($name, 1); + $this->nullable = true; + } elseif (\PHP_VERSION_ID >= 8_00_00) { + $this->nullable = \in_array('null', array_map('trim', explode('|', strtolower($name))), true); + } + + if (null !== $startIndex) { + $this->startIndex = $startIndex; + $this->endIndex = $endIndex; + } + } + + public function getName(): string + { + return $this->name; + } + + public function getStartIndex(): int + { + return $this->startIndex; + } + + public function getEndIndex(): int + { + return $this->endIndex; + } + + public function isReservedType(): bool + { + return \in_array(strtolower($this->name), self::$reservedTypes, true); + } + + public function isNullable(): bool + { + return $this->nullable; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ArgumentsAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ArgumentsAnalyzer.php new file mode 100644 index 00000000..94322071 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ArgumentsAnalyzer.php @@ -0,0 +1,161 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * @author Vladimir Reznichenko + * + * @internal + */ +final class ArgumentsAnalyzer +{ + /** + * Count amount of parameters in a function/method reference. + */ + public function countArguments(Tokens $tokens, int $openParenthesis, int $closeParenthesis): int + { + return \count($this->getArguments($tokens, $openParenthesis, $closeParenthesis)); + } + + /** + * Returns start and end token indices of arguments. + * + * Returns an array with each key being the first token of an + * argument and the value the last. Including non-function tokens + * such as comments and white space tokens, but without the separation + * tokens like '(', ',' and ')'. + * + * @return array + */ + public function getArguments(Tokens $tokens, int $openParenthesis, int $closeParenthesis): array + { + $arguments = []; + $firstSensibleToken = $tokens->getNextMeaningfulToken($openParenthesis); + + if ($tokens[$firstSensibleToken]->equals(')')) { + return $arguments; + } + + $paramContentIndex = $openParenthesis + 1; + $argumentsStart = $paramContentIndex; + + for (; $paramContentIndex < $closeParenthesis; ++$paramContentIndex) { + $token = $tokens[$paramContentIndex]; + + // skip nested (), [], {} constructs + $blockDefinitionProbe = Tokens::detectBlockType($token); + + if (null !== $blockDefinitionProbe && true === $blockDefinitionProbe['isStart']) { + $paramContentIndex = $tokens->findBlockEnd($blockDefinitionProbe['type'], $paramContentIndex); + + continue; + } + + // if comma matched, increase arguments counter + if ($token->equals(',')) { + if ($tokens->getNextMeaningfulToken($paramContentIndex) === $closeParenthesis) { + break; // trailing ',' in function call (PHP 7.3) + } + + $arguments[$argumentsStart] = $paramContentIndex - 1; + $argumentsStart = $paramContentIndex + 1; + } + } + + $arguments[$argumentsStart] = $paramContentIndex - 1; + + return $arguments; + } + + public function getArgumentInfo(Tokens $tokens, int $argumentStart, int $argumentEnd): ArgumentAnalysis + { + static $skipTypes = null; + + if (null === $skipTypes) { + $skipTypes = [T_ELLIPSIS, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE]; + + if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required + $skipTypes[] = T_READONLY; + } + } + + $info = [ + 'default' => null, + 'name' => null, + 'name_index' => null, + 'type' => null, + 'type_index_start' => null, + 'type_index_end' => null, + ]; + + $sawName = false; + + for ($index = $argumentStart; $index <= $argumentEnd; ++$index) { + $token = $tokens[$index]; + + if (\defined('T_ATTRIBUTE') && $token->isGivenKind(T_ATTRIBUTE)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + + continue; + } + + if ( + $token->isComment() + || $token->isWhitespace() + || $token->isGivenKind($skipTypes) + || $token->equals('&') + ) { + continue; + } + + if ($token->isGivenKind(T_VARIABLE)) { + $sawName = true; + $info['name_index'] = $index; + $info['name'] = $token->getContent(); + + continue; + } + + if ($token->equals('=')) { + continue; + } + + if ($sawName) { + $info['default'] .= $token->getContent(); + } else { + $info['type_index_start'] = ($info['type_index_start'] > 0) ? $info['type_index_start'] : $index; + $info['type_index_end'] = $index; + $info['type'] .= $token->getContent(); + } + } + + if (null === $info['name']) { + $info['type'] = null; + } + + return new ArgumentAnalysis( + $info['name'], + $info['name_index'], + $info['default'], + null !== $info['type'] ? new TypeAnalysis($info['type'], $info['type_index_start'], $info['type_index_end']) : null + ); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AttributeAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AttributeAnalyzer.php new file mode 100644 index 00000000..c67b76bc --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AttributeAnalyzer.php @@ -0,0 +1,70 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + */ +final class AttributeAnalyzer +{ + private const TOKEN_KINDS_NOT_ALLOWED_IN_ATTRIBUTE = [ + ';', + '{', + [T_ATTRIBUTE], + [T_FUNCTION], + [T_OPEN_TAG], + [T_OPEN_TAG_WITH_ECHO], + [T_PRIVATE], + [T_PROTECTED], + [T_PUBLIC], + [T_RETURN], + [T_VARIABLE], + [CT::T_ATTRIBUTE_CLOSE], + ]; + + /** + * Check if given index is an attribute declaration. + */ + public static function isAttribute(Tokens $tokens, int $index): bool + { + if ( + !\defined('T_ATTRIBUTE') // attributes not available, PHP version lower than 8.0 + || !$tokens[$index]->isGivenKind(T_STRING) // checked token is not a string + || !$tokens->isAnyTokenKindsFound([T_ATTRIBUTE]) // no attributes in the tokens collection + ) { + return false; + } + + $attributeStartIndex = $tokens->getPrevTokenOfKind($index, self::TOKEN_KINDS_NOT_ALLOWED_IN_ATTRIBUTE); + if (!$tokens[$attributeStartIndex]->isGivenKind(T_ATTRIBUTE)) { + return false; + } + + // now, between attribute start and the attribute candidate index cannot be more "(" than ")" + $count = 0; + for ($i = $attributeStartIndex + 1; $i < $index; ++$i) { + if ($tokens[$i]->equals('(')) { + ++$count; + } elseif ($tokens[$i]->equals(')')) { + --$count; + } + } + + return 0 === $count; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/BlocksAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/BlocksAnalyzer.php new file mode 100644 index 00000000..492d7049 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/BlocksAnalyzer.php @@ -0,0 +1,63 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @internal + */ +final class BlocksAnalyzer +{ + public function isBlock(Tokens $tokens, ?int $openIndex, ?int $closeIndex): bool + { + if (null === $openIndex || null === $closeIndex) { + return false; + } + + if (!$tokens->offsetExists($openIndex)) { + return false; + } + + if (!$tokens->offsetExists($closeIndex)) { + return false; + } + + $blockType = $this->getBlockType($tokens[$openIndex]); + + if (null === $blockType) { + return false; + } + + return $closeIndex === $tokens->findBlockEnd($blockType, $openIndex); + } + + /** + * @return Tokens::BLOCK_TYPE_* + */ + private function getBlockType(Token $token): ?int + { + foreach (Tokens::getBlockEdgeDefinitions() as $blockType => $definition) { + if ($token->equals($definition['start'])) { + return $blockType; + } + } + + return null; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ClassyAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ClassyAnalyzer.php new file mode 100644 index 00000000..5770d01c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ClassyAnalyzer.php @@ -0,0 +1,87 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + */ +final class ClassyAnalyzer +{ + public function isClassyInvocation(Tokens $tokens, int $index): bool + { + $token = $tokens[$index]; + + if (!$token->isGivenKind(T_STRING)) { + throw new \LogicException(sprintf('No T_STRING at given index %d, got "%s".', $index, $tokens[$index]->getName())); + } + + if ((new Analysis\TypeAnalysis($token->getContent()))->isReservedType()) { + return false; + } + + $next = $tokens->getNextMeaningfulToken($index); + $nextToken = $tokens[$next]; + + if ($nextToken->isGivenKind(T_NS_SEPARATOR)) { + return false; + } + + if ($nextToken->isGivenKind([T_DOUBLE_COLON, T_ELLIPSIS, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, T_VARIABLE])) { + return true; + } + + $prev = $tokens->getPrevMeaningfulToken($index); + + while ($tokens[$prev]->isGivenKind([CT::T_NAMESPACE_OPERATOR, T_NS_SEPARATOR, T_STRING])) { + $prev = $tokens->getPrevMeaningfulToken($prev); + } + + $prevToken = $tokens[$prev]; + + if ($prevToken->isGivenKind([T_EXTENDS, T_INSTANCEOF, T_INSTEADOF, T_IMPLEMENTS, T_NEW, CT::T_NULLABLE_TYPE, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_TYPE_COLON, CT::T_USE_TRAIT])) { + return true; + } + + if (\PHP_VERSION_ID >= 8_00_00 && $nextToken->equals(')') && $prevToken->equals('(') && $tokens[$tokens->getPrevMeaningfulToken($prev)]->isGivenKind(T_CATCH)) { + return true; + } + + if (AttributeAnalyzer::isAttribute($tokens, $index)) { + return true; + } + + // `Foo & $bar` could be: + // - function reference parameter: function baz(Foo & $bar) {} + // - bit operator: $x = Foo & $bar; + if ($nextToken->equals('&') && $tokens[$tokens->getNextMeaningfulToken($next)]->isGivenKind(T_VARIABLE)) { + $checkIndex = $tokens->getPrevTokenOfKind($prev + 1, [';', '{', '}', [T_FUNCTION], [T_OPEN_TAG], [T_OPEN_TAG_WITH_ECHO]]); + + return $tokens[$checkIndex]->isGivenKind(T_FUNCTION); + } + + if (!$prevToken->equals(',')) { + return false; + } + + do { + $prev = $tokens->getPrevMeaningfulToken($prev); + } while ($tokens[$prev]->equalsAny([',', [T_NS_SEPARATOR], [T_STRING], [CT::T_NAMESPACE_OPERATOR]])); + + return $tokens[$prev]->isGivenKind([T_IMPLEMENTS, CT::T_USE_TRAIT]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/CommentsAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/CommentsAnalyzer.php new file mode 100644 index 00000000..d0d87ef2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/CommentsAnalyzer.php @@ -0,0 +1,324 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @internal + */ +final class CommentsAnalyzer +{ + private const TYPE_HASH = 1; + private const TYPE_DOUBLE_SLASH = 2; + private const TYPE_SLASH_ASTERISK = 3; + + public function isHeaderComment(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->isGivenKind([T_COMMENT, T_DOC_COMMENT])) { + throw new \InvalidArgumentException('Given index must point to a comment.'); + } + + if (null === $tokens->getNextMeaningfulToken($index)) { + return false; + } + + $prevIndex = $tokens->getPrevNonWhitespace($index); + + if ($tokens[$prevIndex]->equals(';')) { + $braceCloseIndex = $tokens->getPrevMeaningfulToken($prevIndex); + if (!$tokens[$braceCloseIndex]->equals(')')) { + return false; + } + + $braceOpenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $braceCloseIndex); + $declareIndex = $tokens->getPrevMeaningfulToken($braceOpenIndex); + if (!$tokens[$declareIndex]->isGivenKind(T_DECLARE)) { + return false; + } + + $prevIndex = $tokens->getPrevNonWhitespace($declareIndex); + } + + return $tokens[$prevIndex]->isGivenKind(T_OPEN_TAG); + } + + /** + * Check if comment at given index precedes structural element. + * + * @see https://github.com/php-fig/fig-standards/blob/master/proposed/phpdoc.md#3-definitions + */ + public function isBeforeStructuralElement(Tokens $tokens, int $index): bool + { + $token = $tokens[$index]; + + if (!$token->isGivenKind([T_COMMENT, T_DOC_COMMENT])) { + throw new \InvalidArgumentException('Given index must point to a comment.'); + } + + $nextIndex = $index; + do { + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + + // @TODO: drop condition when PHP 8.0+ is required + if (\defined('T_ATTRIBUTE')) { + while (null !== $nextIndex && $tokens[$nextIndex]->isGivenKind(T_ATTRIBUTE)) { + $nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $nextIndex); + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + } + } + } while (null !== $nextIndex && $tokens[$nextIndex]->equals('(')); + + if (null === $nextIndex || $tokens[$nextIndex]->equals('}')) { + return false; + } + + if ($this->isStructuralElement($tokens, $nextIndex)) { + return true; + } + + if ($this->isValidControl($tokens, $token, $nextIndex)) { + return true; + } + + if ($this->isValidVariable($tokens, $nextIndex)) { + return true; + } + + if ($this->isValidLanguageConstruct($tokens, $token, $nextIndex)) { + return true; + } + + if ($tokens[$nextIndex]->isGivenKind(CT::T_USE_TRAIT)) { + return true; + } + + return false; + } + + /** + * Return array of indices that are part of a comment started at given index. + * + * @param int $index T_COMMENT index + * + * @return list + */ + public function getCommentBlockIndices(Tokens $tokens, int $index): array + { + if (!$tokens[$index]->isGivenKind(T_COMMENT)) { + throw new \InvalidArgumentException('Given index must point to a comment.'); + } + + $commentType = $this->getCommentType($tokens[$index]->getContent()); + $indices = [$index]; + + if (self::TYPE_SLASH_ASTERISK === $commentType) { + return $indices; + } + + $count = \count($tokens); + ++$index; + + for (; $index < $count; ++$index) { + if ($tokens[$index]->isComment()) { + if ($commentType === $this->getCommentType($tokens[$index]->getContent())) { + $indices[] = $index; + + continue; + } + + break; + } + + if (!$tokens[$index]->isWhitespace() || $this->getLineBreakCount($tokens, $index, $index + 1) > 1) { + break; + } + } + + return $indices; + } + + /** + * @see https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md#3-definitions + */ + private function isStructuralElement(Tokens $tokens, int $index): bool + { + static $skip; + + if (null === $skip) { + $skip = [ + T_PRIVATE, + T_PROTECTED, + T_PUBLIC, + T_VAR, + T_FUNCTION, + T_FN, + T_ABSTRACT, + T_CONST, + T_NAMESPACE, + T_REQUIRE, + T_REQUIRE_ONCE, + T_INCLUDE, + T_INCLUDE_ONCE, + T_FINAL, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, + ]; + + if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required + $skip[] = T_READONLY; + } + } + + $token = $tokens[$index]; + + if ($token->isClassy() || $token->isGivenKind($skip)) { + return true; + } + + if ($token->isGivenKind(T_CASE) && \defined('T_ENUM')) { + $caseParent = $tokens->getPrevTokenOfKind($index, [[T_ENUM], [T_SWITCH]]); + + return $tokens[$caseParent]->isGivenKind([T_ENUM]); + } + + if ($token->isGivenKind(T_STATIC)) { + return !$tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(T_DOUBLE_COLON); + } + + return false; + } + + /** + * Checks control structures (for, foreach, if, switch, while) for correct docblock usage. + * + * @param Token $docsToken docs Token + * @param int $controlIndex index of control structure Token + */ + private function isValidControl(Tokens $tokens, Token $docsToken, int $controlIndex): bool + { + static $controlStructures = [ + T_FOR, + T_FOREACH, + T_IF, + T_SWITCH, + T_WHILE, + ]; + + if (!$tokens[$controlIndex]->isGivenKind($controlStructures)) { + return false; + } + + $openParenthesisIndex = $tokens->getNextMeaningfulToken($controlIndex); + $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesisIndex); + $docsContent = $docsToken->getContent(); + + for ($index = $openParenthesisIndex + 1; $index < $closeParenthesisIndex; ++$index) { + $token = $tokens[$index]; + + if ( + $token->isGivenKind(T_VARIABLE) + && str_contains($docsContent, $token->getContent()) + ) { + return true; + } + } + + return false; + } + + /** + * Checks variable assignments through `list()`, `print()` etc. calls for correct docblock usage. + * + * @param Token $docsToken docs Token + * @param int $languageConstructIndex index of variable Token + */ + private function isValidLanguageConstruct(Tokens $tokens, Token $docsToken, int $languageConstructIndex): bool + { + static $languageStructures = [ + T_LIST, + T_PRINT, + T_ECHO, + CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, + ]; + + if (!$tokens[$languageConstructIndex]->isGivenKind($languageStructures)) { + return false; + } + + $endKind = $tokens[$languageConstructIndex]->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN) + ? [CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE] + : ')'; + + $endIndex = $tokens->getNextTokenOfKind($languageConstructIndex, [$endKind]); + + $docsContent = $docsToken->getContent(); + + for ($index = $languageConstructIndex + 1; $index < $endIndex; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(T_VARIABLE) && str_contains($docsContent, $token->getContent())) { + return true; + } + } + + return false; + } + + /** + * Checks variable assignments for correct docblock usage. + * + * @param int $index index of variable Token + */ + private function isValidVariable(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->isGivenKind(T_VARIABLE)) { + return false; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + return $tokens[$nextIndex]->equals('='); + } + + private function getCommentType(string $content): int + { + if (str_starts_with($content, '#')) { + return self::TYPE_HASH; + } + + if ('*' === $content[1]) { + return self::TYPE_SLASH_ASTERISK; + } + + return self::TYPE_DOUBLE_SLASH; + } + + private function getLineBreakCount(Tokens $tokens, int $whiteStart, int $whiteEnd): int + { + $lineCount = 0; + for ($i = $whiteStart; $i < $whiteEnd; ++$i) { + $lineCount += Preg::matchAll('/\R/u', $tokens[$i]->getContent()); + } + + return $lineCount; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ControlCaseStructuresAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ControlCaseStructuresAnalyzer.php new file mode 100644 index 00000000..cb7cf9c4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ControlCaseStructuresAnalyzer.php @@ -0,0 +1,309 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\AbstractControlCaseStructuresAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\CaseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\DefaultAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\EnumAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\MatchAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; +use PhpCsFixer\Tokenizer\Tokens; + +final class ControlCaseStructuresAnalyzer +{ + /** + * @param list $types Token types of interest of which analyzes must be returned + * + * @return \Generator + */ + public static function findControlStructures(Tokens $tokens, array $types): \Generator + { + if (\count($types) < 1) { + return; // quick skip + } + + $typesWithCaseOrDefault = self::getTypesWithCaseOrDefault(); + + foreach ($types as $type) { + if (!\in_array($type, $typesWithCaseOrDefault, true)) { + throw new \InvalidArgumentException(sprintf('Unexpected type "%d".', $type)); + } + } + + if (!$tokens->isAnyTokenKindsFound($types)) { + return; // quick skip + } + + $depth = -1; + + /** + * @var list, + * default: array{index: int, open: int}|null, + * alternative_syntax: bool, + * }> $stack + */ + $stack = []; + $isTypeOfInterest = false; + + foreach ($tokens as $index => $token) { + if ($token->isGivenKind($typesWithCaseOrDefault)) { + ++$depth; + + $stack[$depth] = [ + 'kind' => $token->getId(), + 'index' => $index, + 'brace_count' => 0, + 'cases' => [], + 'default' => null, + 'alternative_syntax' => false, + ]; + + $isTypeOfInterest = \in_array($stack[$depth]['kind'], $types, true); + + if ($token->isGivenKind(T_SWITCH)) { + $index = $tokens->getNextMeaningfulToken($index); + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + + $stack[$depth]['open'] = $tokens->getNextMeaningfulToken($index); + $stack[$depth]['alternative_syntax'] = $tokens[$stack[$depth]['open']]->equals(':'); + } elseif (\defined('T_MATCH') && $token->isGivenKind(T_MATCH)) { // @TODO: drop condition when PHP 8.0+ is required + $index = $tokens->getNextMeaningfulToken($index); + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + + $stack[$depth]['open'] = $tokens->getNextMeaningfulToken($index); + } elseif (\defined('T_ENUM') && $token->isGivenKind(T_ENUM)) { + $stack[$depth]['open'] = $tokens->getNextTokenOfKind($index, ['{']); + } + + continue; + } + + if ($depth < 0) { + continue; + } + + if ($token->equals('{')) { + ++$stack[$depth]['brace_count']; + + continue; + } + + if ($token->equals('}')) { + --$stack[$depth]['brace_count']; + + if (0 === $stack[$depth]['brace_count']) { + if ($stack[$depth]['alternative_syntax']) { + continue; + } + + if ($isTypeOfInterest) { + $stack[$depth]['end'] = $index; + + yield $stack[$depth]['index'] => self::buildControlCaseStructureAnalysis($stack[$depth]); + } + + array_pop($stack); + --$depth; + + if ($depth < -1) { // @phpstan-ignore-line + throw new \RuntimeException('Analysis depth count failure.'); + } + + if (isset($stack[$depth]['kind'])) { + $isTypeOfInterest = \in_array($stack[$depth]['kind'], $types, true); + } + } + + continue; + } + + if ($tokens[$index]->isGivenKind(T_ENDSWITCH)) { + if (!$stack[$depth]['alternative_syntax']) { + throw new \RuntimeException('Analysis syntax failure, unexpected "T_ENDSWITCH".'); + } + + if (T_SWITCH !== $stack[$depth]['kind']) { + throw new \RuntimeException('Analysis type failure, unexpected "T_ENDSWITCH".'); + } + + if (0 !== $stack[$depth]['brace_count']) { + throw new \RuntimeException('Analysis count failure, unexpected "T_ENDSWITCH".'); + } + + $index = $tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]); + + if ($isTypeOfInterest) { + $stack[$depth]['end'] = $index; + + yield $stack[$depth]['index'] => self::buildControlCaseStructureAnalysis($stack[$depth]); + } + + array_pop($stack); + --$depth; + + if ($depth < -1) { // @phpstan-ignore-line + throw new \RuntimeException('Analysis depth count failure ("T_ENDSWITCH").'); + } + + if (isset($stack[$depth]['kind'])) { + $isTypeOfInterest = \in_array($stack[$depth]['kind'], $types, true); + } + } + + if (!$isTypeOfInterest) { + continue; // don't bother to analyze stuff that caller is not interested in + } + + if ($token->isGivenKind(T_CASE)) { + $stack[$depth]['cases'][] = ['index' => $index, 'open' => self::findCaseOpen($tokens, $stack[$depth]['kind'], $index)]; + } elseif ($token->isGivenKind(T_DEFAULT)) { + if (null !== $stack[$depth]['default']) { + throw new \RuntimeException('Analysis multiple "default" found.'); + } + + $stack[$depth]['default'] = ['index' => $index, 'open' => self::findDefaultOpen($tokens, $stack[$depth]['kind'], $index)]; + } + } + } + + /** + * @param array{ + * kind: int, + * index: int, + * open: int, + * end: int, + * cases: list, + * default: null|array{index: int, open: int}, + * } $analysis + */ + private static function buildControlCaseStructureAnalysis(array $analysis): AbstractControlCaseStructuresAnalysis + { + $default = null === $analysis['default'] + ? null + : new DefaultAnalysis($analysis['default']['index'], $analysis['default']['open']); + + $cases = []; + + foreach ($analysis['cases'] as $case) { + $cases[$case['index']] = new CaseAnalysis($case['index'], $case['open']); + } + + sort($cases); + + if (T_SWITCH === $analysis['kind']) { + return new SwitchAnalysis( + $analysis['index'], + $analysis['open'], + $analysis['end'], + $cases, + $default + ); + } + + if (\defined('T_ENUM') && T_ENUM === $analysis['kind']) { + return new EnumAnalysis( + $analysis['index'], + $analysis['open'], + $analysis['end'], + $cases + ); + } + + if (\defined('T_MATCH') && T_MATCH === $analysis['kind']) { // @TODO: drop condition when PHP 8.0+ is required + return new MatchAnalysis( + $analysis['index'], + $analysis['open'], + $analysis['end'], + $default + ); + } + + throw new \InvalidArgumentException(sprintf('Unexpected type "%d".', $analysis['kind'])); + } + + private static function findCaseOpen(Tokens $tokens, int $kind, int $index): int + { + if (T_SWITCH === $kind) { + $ternariesCount = 0; + + do { + if ($tokens[$index]->equalsAny(['(', '{'])) { // skip constructs + $type = Tokens::detectBlockType($tokens[$index]); + $index = $tokens->findBlockEnd($type['type'], $index); + + continue; + } + + if ($tokens[$index]->equals('?')) { + ++$ternariesCount; + + continue; + } + + if ($tokens[$index]->equalsAny([':', ';'])) { + if (0 === $ternariesCount) { + break; + } + + --$ternariesCount; + } + } while (++$index); + + return $index; + } + + if (\defined('T_ENUM') && T_ENUM === $kind) { + return $tokens->getNextTokenOfKind($index, ['=', ';']); + } + + throw new \InvalidArgumentException(sprintf('Unexpected case for type "%d".', $kind)); + } + + private static function findDefaultOpen(Tokens $tokens, int $kind, int $index): int + { + if (T_SWITCH === $kind) { + return $tokens->getNextTokenOfKind($index, [':', ';']); + } + + if (\defined('T_MATCH') && T_MATCH === $kind) { // @TODO: drop condition when PHP 8.0+ is required + return $tokens->getNextTokenOfKind($index, [[T_DOUBLE_ARROW]]); + } + + throw new \InvalidArgumentException(sprintf('Unexpected default for type "%d".', $kind)); + } + + /** + * @return list + */ + private static function getTypesWithCaseOrDefault(): array + { + $supportedTypes = [T_SWITCH]; + + if (\defined('T_MATCH')) { // @TODO: drop condition when PHP 8.0+ is required + $supportedTypes[] = T_MATCH; + } + + if (\defined('T_ENUM')) { // @TODO: drop condition when PHP 8.1+ is required + $supportedTypes[] = T_ENUM; + } + + return $supportedTypes; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/DataProviderAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/DataProviderAnalyzer.php new file mode 100644 index 00000000..8d74d7de --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/DataProviderAnalyzer.php @@ -0,0 +1,101 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\DataProviderAnalysis; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @internal + */ +final class DataProviderAnalyzer +{ + private const REGEX_CLASS = '(?:\\\\?+'.TypeExpression::REGEX_IDENTIFIER + .'(\\\\'.TypeExpression::REGEX_IDENTIFIER.')*+)'; + + /** + * @return array + */ + public function getDataProviders(Tokens $tokens, int $startIndex, int $endIndex): array + { + $methods = $this->getMethods($tokens, $startIndex, $endIndex); + + $dataProviders = []; + foreach ($methods as $methodIndex) { + $docCommentIndex = $tokens->getTokenNotOfKindSibling( + $methodIndex, + -1, + [[T_ABSTRACT], [T_COMMENT], [T_FINAL], [T_FUNCTION], [T_PRIVATE], [T_PROTECTED], [T_PUBLIC], [T_STATIC], [T_WHITESPACE]] + ); + + if (!$tokens[$docCommentIndex]->isGivenKind(T_DOC_COMMENT)) { + continue; + } + + Preg::matchAll('/@dataProvider\h+(('.self::REGEX_CLASS.'::)?'.TypeExpression::REGEX_IDENTIFIER.')/', $tokens[$docCommentIndex]->getContent(), $matches); + + /** @var array $matches */ + $matches = $matches[1]; + + foreach ($matches as $dataProviderName) { + $dataProviders[$dataProviderName][] = $docCommentIndex; + } + } + + $dataProviderAnalyses = []; + foreach ($dataProviders as $dataProviderName => $dataProviderUsages) { + $lowercaseDataProviderName = strtolower($dataProviderName); + if (!\array_key_exists($lowercaseDataProviderName, $methods)) { + continue; + } + $dataProviderAnalyses[$methods[$lowercaseDataProviderName]] = new DataProviderAnalysis( + $tokens[$methods[$lowercaseDataProviderName]]->getContent(), + $methods[$lowercaseDataProviderName], + $dataProviderUsages, + ); + } + + ksort($dataProviderAnalyses); + + return array_values($dataProviderAnalyses); + } + + /** + * @return array + */ + private function getMethods(Tokens $tokens, int $startIndex, int $endIndex): array + { + $functions = []; + for ($index = $startIndex; $index < $endIndex; ++$index) { + if (!$tokens[$index]->isGivenKind(T_FUNCTION)) { + continue; + } + + $functionNameIndex = $tokens->getNextNonWhitespace($index); + + if (!$tokens[$functionNameIndex]->isGivenKind(T_STRING)) { + continue; + } + + $functions[strtolower($tokens[$functionNameIndex]->getContent())] = $functionNameIndex; + } + + return $functions; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FunctionsAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FunctionsAnalyzer.php new file mode 100644 index 00000000..51b2ac03 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FunctionsAnalyzer.php @@ -0,0 +1,269 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + */ +final class FunctionsAnalyzer +{ + /** + * @var array{tokens: string, imports: list, declarations: list} + */ + private array $functionsAnalysis = ['tokens' => '', 'imports' => [], 'declarations' => []]; + + /** + * Important: risky because of the limited (file) scope of the tool. + */ + public function isGlobalFunctionCall(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->isGivenKind(T_STRING)) { + return false; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$nextIndex]->equals('(')) { + return false; + } + + $previousIsNamespaceSeparator = false; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { + $previousIsNamespaceSeparator = true; + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + } + + $possibleKind = [ + T_DOUBLE_COLON, T_FUNCTION, CT::T_NAMESPACE_OPERATOR, T_NEW, CT::T_RETURN_REF, T_STRING, + ...Token::getObjectOperatorKinds(), + ]; + + // @TODO: drop condition when PHP 8.0+ is required + if (\defined('T_ATTRIBUTE')) { + $possibleKind[] = T_ATTRIBUTE; + } + + if ($tokens[$prevIndex]->isGivenKind($possibleKind)) { + return false; + } + + if ($tokens[$tokens->getNextMeaningfulToken($nextIndex)]->isGivenKind(CT::T_FIRST_CLASS_CALLABLE)) { + return false; + } + + if ($previousIsNamespaceSeparator) { + return true; + } + + if ($tokens->isChanged() || $tokens->getCodeHash() !== $this->functionsAnalysis['tokens']) { + $this->buildFunctionsAnalysis($tokens); + } + + // figure out in which namespace we are + $scopeStartIndex = 0; + $scopeEndIndex = \count($tokens) - 1; + $inGlobalNamespace = false; + + foreach ($tokens->getNamespaceDeclarations() as $declaration) { + $scopeStartIndex = $declaration->getScopeStartIndex(); + $scopeEndIndex = $declaration->getScopeEndIndex(); + + if ($index >= $scopeStartIndex && $index <= $scopeEndIndex) { + $inGlobalNamespace = $declaration->isGlobalNamespace(); + + break; + } + } + + $call = strtolower($tokens[$index]->getContent()); + + // check if the call is to a function declared in the same namespace as the call is done, + // if the call is already in the global namespace than declared functions are in the same + // global namespace and don't need checking + + if (!$inGlobalNamespace) { + /** @var int $functionNameIndex */ + foreach ($this->functionsAnalysis['declarations'] as $functionNameIndex) { + if ($functionNameIndex < $scopeStartIndex || $functionNameIndex > $scopeEndIndex) { + continue; + } + + if (strtolower($tokens[$functionNameIndex]->getContent()) === $call) { + return false; + } + } + } + + /** @var NamespaceUseAnalysis $functionUse */ + foreach ($this->functionsAnalysis['imports'] as $functionUse) { + if ($functionUse->getStartIndex() < $scopeStartIndex || $functionUse->getEndIndex() > $scopeEndIndex) { + continue; + } + + if ($call !== strtolower($functionUse->getShortName())) { + continue; + } + + // global import like `use function \str_repeat;` + return $functionUse->getShortName() === ltrim($functionUse->getFullName(), '\\'); + } + + if (AttributeAnalyzer::isAttribute($tokens, $index)) { + return false; + } + + return true; + } + + /** + * @return array + */ + public function getFunctionArguments(Tokens $tokens, int $functionIndex): array + { + $argumentsStart = $tokens->getNextTokenOfKind($functionIndex, ['(']); + $argumentsEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $argumentsStart); + $argumentAnalyzer = new ArgumentsAnalyzer(); + $arguments = []; + + foreach ($argumentAnalyzer->getArguments($tokens, $argumentsStart, $argumentsEnd) as $start => $end) { + $argumentInfo = $argumentAnalyzer->getArgumentInfo($tokens, $start, $end); + $arguments[$argumentInfo->getName()] = $argumentInfo; + } + + return $arguments; + } + + public function getFunctionReturnType(Tokens $tokens, int $methodIndex): ?TypeAnalysis + { + $argumentsStart = $tokens->getNextTokenOfKind($methodIndex, ['(']); + $argumentsEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $argumentsStart); + $typeColonIndex = $tokens->getNextMeaningfulToken($argumentsEnd); + + if (!$tokens[$typeColonIndex]->isGivenKind(CT::T_TYPE_COLON)) { + return null; + } + + $type = ''; + $typeStartIndex = $tokens->getNextMeaningfulToken($typeColonIndex); + $typeEndIndex = $typeStartIndex; + $functionBodyStart = $tokens->getNextTokenOfKind($typeColonIndex, ['{', ';', [T_DOUBLE_ARROW]]); + + for ($i = $typeStartIndex; $i < $functionBodyStart; ++$i) { + if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { + continue; + } + + $type .= $tokens[$i]->getContent(); + $typeEndIndex = $i; + } + + return new TypeAnalysis($type, $typeStartIndex, $typeEndIndex); + } + + public function isTheSameClassCall(Tokens $tokens, int $index): bool + { + if (!$tokens->offsetExists($index)) { + return false; + } + + $operatorIndex = $tokens->getPrevMeaningfulToken($index); + + if (null === $operatorIndex) { + return false; + } + + if (!$tokens[$operatorIndex]->isObjectOperator() && !$tokens[$operatorIndex]->isGivenKind(T_DOUBLE_COLON)) { + return false; + } + + $referenceIndex = $tokens->getPrevMeaningfulToken($operatorIndex); + + if (null === $referenceIndex) { + return false; + } + + return $tokens[$referenceIndex]->equalsAny([[T_VARIABLE, '$this'], [T_STRING, 'self'], [T_STATIC, 'static']], false); + } + + private function buildFunctionsAnalysis(Tokens $tokens): void + { + $this->functionsAnalysis = [ + 'tokens' => $tokens->getCodeHash(), + 'imports' => [], + 'declarations' => [], + ]; + + // find declarations + + if ($tokens->isTokenKindFound(T_FUNCTION)) { + $end = \count($tokens); + + for ($i = 0; $i < $end; ++$i) { + // skip classy, we are looking for functions not methods + if ($tokens[$i]->isGivenKind(Token::getClassyTokenKinds())) { + $i = $tokens->getNextTokenOfKind($i, ['(', '{']); + + if ($tokens[$i]->equals('(')) { // anonymous class + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $i); + $i = $tokens->getNextTokenOfKind($i, ['{']); + } + + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $i); + + continue; + } + + if (!$tokens[$i]->isGivenKind(T_FUNCTION)) { + continue; + } + + $i = $tokens->getNextMeaningfulToken($i); + + if ($tokens[$i]->isGivenKind(CT::T_RETURN_REF)) { + $i = $tokens->getNextMeaningfulToken($i); + } + + if (!$tokens[$i]->isGivenKind(T_STRING)) { + continue; + } + + $this->functionsAnalysis['declarations'][] = $i; + } + } + + // find imported functions + + $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); + + if ($tokens->isTokenKindFound(CT::T_FUNCTION_IMPORT)) { + $declarations = $namespaceUsesAnalyzer->getDeclarationsFromTokens($tokens); + + foreach ($declarations as $declaration) { + if ($declaration->isFunction()) { + $this->functionsAnalysis['imports'][] = $declaration; + } + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/GotoLabelAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/GotoLabelAnalyzer.php new file mode 100644 index 00000000..15d5b066 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/GotoLabelAnalyzer.php @@ -0,0 +1,40 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + */ +final class GotoLabelAnalyzer +{ + public function belongsToGoToLabel(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->equals(':')) { + return false; + } + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$prevMeaningfulTokenIndex]->isGivenKind(T_STRING)) { + return false; + } + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulTokenIndex); + + return $tokens[$prevMeaningfulTokenIndex]->equalsAny([':', ';', '{', '}', [T_OPEN_TAG]]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php new file mode 100644 index 00000000..40e9053a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php @@ -0,0 +1,121 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @internal + */ +final class NamespaceUsesAnalyzer +{ + /** + * @return list + */ + public function getDeclarationsFromTokens(Tokens $tokens): array + { + $tokenAnalyzer = new TokensAnalyzer($tokens); + $useIndices = $tokenAnalyzer->getImportUseIndexes(); + + return $this->getDeclarations($tokens, $useIndices); + } + + /** + * @return list + */ + public function getDeclarationsInNamespace(Tokens $tokens, NamespaceAnalysis $namespace): array + { + $namespaceUses = []; + + foreach ($this->getDeclarationsFromTokens($tokens) as $namespaceUse) { + if ($namespaceUse->getStartIndex() >= $namespace->getScopeStartIndex() && $namespaceUse->getStartIndex() <= $namespace->getScopeEndIndex()) { + $namespaceUses[] = $namespaceUse; + } + } + + return $namespaceUses; + } + + /** + * @param list $useIndices + * + * @return list + */ + private function getDeclarations(Tokens $tokens, array $useIndices): array + { + $uses = []; + + foreach ($useIndices as $index) { + $endIndex = $tokens->getNextTokenOfKind($index, [';', [T_CLOSE_TAG]]); + $analysis = $this->parseDeclaration($tokens, $index, $endIndex); + + if (null !== $analysis) { + $uses[] = $analysis; + } + } + + return $uses; + } + + private function parseDeclaration(Tokens $tokens, int $startIndex, int $endIndex): ?NamespaceUseAnalysis + { + $fullName = $shortName = ''; + $aliased = false; + + $type = NamespaceUseAnalysis::TYPE_CLASS; + for ($i = $startIndex; $i <= $endIndex; ++$i) { + $token = $tokens[$i]; + if ($token->equals(',') || $token->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) { + // do not touch group use declarations until the logic of this is added (for example: `use some\a\{ClassD};`) + // ignore multiple use statements that should be split into few separate statements (for example: `use BarB, BarC as C;`) + return null; + } + + if ($token->isGivenKind(CT::T_FUNCTION_IMPORT)) { + $type = NamespaceUseAnalysis::TYPE_FUNCTION; + } elseif ($token->isGivenKind(CT::T_CONST_IMPORT)) { + $type = NamespaceUseAnalysis::TYPE_CONSTANT; + } + + if ($token->isWhitespace() || $token->isComment() || $token->isGivenKind(T_USE)) { + continue; + } + + if ($token->isGivenKind(T_STRING)) { + $shortName = $token->getContent(); + if (!$aliased) { + $fullName .= $shortName; + } + } elseif ($token->isGivenKind(T_NS_SEPARATOR)) { + $fullName .= $token->getContent(); + } elseif ($token->isGivenKind(T_AS)) { + $aliased = true; + } + } + + return new NamespaceUseAnalysis( + trim($fullName), + $shortName, + $aliased, + $startIndex, + $endIndex, + $type + ); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespacesAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespacesAnalyzer.php new file mode 100644 index 00000000..3890523a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespacesAnalyzer.php @@ -0,0 +1,88 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + */ +final class NamespacesAnalyzer +{ + /** + * @return list + */ + public function getDeclarations(Tokens $tokens): array + { + $namespaces = []; + + for ($index = 1, $count = \count($tokens); $index < $count; ++$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(T_NAMESPACE)) { + continue; + } + + $declarationEndIndex = $tokens->getNextTokenOfKind($index, [';', '{']); + $namespace = trim($tokens->generatePartialCode($index + 1, $declarationEndIndex - 1)); + $declarationParts = explode('\\', $namespace); + $shortName = end($declarationParts); + + if ($tokens[$declarationEndIndex]->equals('{')) { + $scopeEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $declarationEndIndex); + } else { + $scopeEndIndex = $tokens->getNextTokenOfKind($declarationEndIndex, [[T_NAMESPACE]]); + if (null === $scopeEndIndex) { + $scopeEndIndex = \count($tokens); + } + --$scopeEndIndex; + } + + $namespaces[] = new NamespaceAnalysis( + $namespace, + $shortName, + $index, + $declarationEndIndex, + $index, + $scopeEndIndex + ); + + // Continue the analysis after the end of this namespace to find the next one + $index = $scopeEndIndex; + } + + if (0 === \count($namespaces)) { + $namespaces[] = new NamespaceAnalysis('', '', 0, 0, 0, \count($tokens) - 1); + } + + return $namespaces; + } + + public function getNamespaceAt(Tokens $tokens, int $index): NamespaceAnalysis + { + if (!$tokens->offsetExists($index)) { + throw new \InvalidArgumentException(sprintf('Token index %d does not exist.', $index)); + } + + foreach ($this->getDeclarations($tokens) as $namespace) { + if ($namespace->getScopeStartIndex() <= $index && $namespace->getScopeEndIndex() >= $index) { + return $namespace; + } + } + + throw new \LogicException(sprintf('Unable to get the namespace at index %d.', $index)); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/RangeAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/RangeAnalyzer.php new file mode 100644 index 00000000..51a2abde --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/RangeAnalyzer.php @@ -0,0 +1,90 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + */ +final class RangeAnalyzer +{ + private function __construct() + { + // cannot create instance of util. class + } + + /** + * Meaningful compare of tokens within ranges. + * + * @param array{start: int, end: int} $range1 + * @param array{start: int, end: int} $range2 + */ + public static function rangeEqualsRange(Tokens $tokens, array $range1, array $range2): bool + { + $leftStart = $range1['start']; + $leftEnd = $range1['end']; + + if ($tokens[$leftStart]->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) { + $leftStart = $tokens->getNextMeaningfulToken($leftStart); + } + + while ($tokens[$leftStart]->equals('(') && $tokens[$leftEnd]->equals(')')) { + $leftStart = $tokens->getNextMeaningfulToken($leftStart); + $leftEnd = $tokens->getPrevMeaningfulToken($leftEnd); + } + + $rightStart = $range2['start']; + $rightEnd = $range2['end']; + + if ($tokens[$rightStart]->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) { + $rightStart = $tokens->getNextMeaningfulToken($rightStart); + } + + while ($tokens[$rightStart]->equals('(') && $tokens[$rightEnd]->equals(')')) { + $rightStart = $tokens->getNextMeaningfulToken($rightStart); + $rightEnd = $tokens->getPrevMeaningfulToken($rightEnd); + } + + $arrayOpenTypes = ['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN]]; + $arrayCloseTypes = [']', [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE]]; + + while (true) { + $leftToken = $tokens[$leftStart]; + $rightToken = $tokens[$rightStart]; + + if ( + !$leftToken->equals($rightToken) + && !($leftToken->equalsAny($arrayOpenTypes) && $rightToken->equalsAny($arrayOpenTypes)) + && !($leftToken->equalsAny($arrayCloseTypes) && $rightToken->equalsAny($arrayCloseTypes)) + ) { + return false; + } + + $leftStart = $tokens->getNextMeaningfulToken($leftStart); + $rightStart = $tokens->getNextMeaningfulToken($rightStart); + + $reachedLeftEnd = null === $leftStart || $leftStart > $leftEnd; // reached end left or moved over + $reachedRightEnd = null === $rightStart || $rightStart > $rightEnd; // reached end right or moved over + + if (!$reachedLeftEnd && !$reachedRightEnd) { + continue; + } + + return $reachedLeftEnd && $reachedRightEnd; + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ReferenceAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ReferenceAnalyzer.php new file mode 100644 index 00000000..0c7d4bd9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ReferenceAnalyzer.php @@ -0,0 +1,49 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @internal + */ +final class ReferenceAnalyzer +{ + public function isReference(Tokens $tokens, int $index): bool + { + if ($tokens[$index]->isGivenKind(CT::T_RETURN_REF)) { + return true; + } + + if (!$tokens[$index]->equals('&')) { + return false; + } + + /** @var int $index */ + $index = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$index]->equalsAny(['=', [T_AS], [T_CALLABLE], [T_DOUBLE_ARROW], [CT::T_ARRAY_TYPEHINT]])) { + return true; + } + + if ($tokens[$index]->isGivenKind(T_STRING)) { + $index = $tokens->getPrevMeaningfulToken($index); + } + + return $tokens[$index]->equalsAny(['(', ',', [T_NS_SEPARATOR], [CT::T_NULLABLE_TYPE]]); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/SwitchAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/SwitchAnalyzer.php new file mode 100644 index 00000000..b6142f69 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/SwitchAnalyzer.php @@ -0,0 +1,69 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + */ +final class SwitchAnalyzer +{ + /** @var array> */ + private static array $cache = []; + + public static function belongsToSwitch(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->equals(':')) { + return false; + } + + $codeHash = $tokens->getCodeHash(); + + if (!\array_key_exists($codeHash, self::$cache)) { + self::$cache[$codeHash] = self::getColonIndicesForSwitch(clone $tokens); + } + + return \in_array($index, self::$cache[$codeHash], true); + } + + /** + * @return int[] + */ + private static function getColonIndicesForSwitch(Tokens $tokens): array + { + $colonIndices = []; + + /** @var SwitchAnalysis $analysis */ + foreach (ControlCaseStructuresAnalyzer::findControlStructures($tokens, [T_SWITCH]) as $analysis) { + if ($tokens[$analysis->getOpenIndex()]->equals(':')) { + $colonIndices[] = $analysis->getOpenIndex(); + } + + foreach ($analysis->getCases() as $case) { + $colonIndices[] = $case->getColonIndex(); + } + + $defaultAnalysis = $analysis->getDefaultAnalysis(); + + if (null !== $defaultAnalysis) { + $colonIndices[] = $defaultAnalysis->getColonIndex(); + } + } + + return $colonIndices; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/WhitespacesAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/WhitespacesAnalyzer.php new file mode 100644 index 00000000..0845ce40 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/WhitespacesAnalyzer.php @@ -0,0 +1,52 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + */ +final class WhitespacesAnalyzer +{ + public static function detectIndent(Tokens $tokens, int $index): string + { + while (true) { + $whitespaceIndex = $tokens->getPrevTokenOfKind($index, [[T_WHITESPACE]]); + + if (null === $whitespaceIndex) { + return ''; + } + + $whitespaceToken = $tokens[$whitespaceIndex]; + + if (str_contains($whitespaceToken->getContent(), "\n")) { + break; + } + + $prevToken = $tokens[$whitespaceIndex - 1]; + + if ($prevToken->isGivenKind([T_OPEN_TAG, T_COMMENT]) && "\n" === substr($prevToken->getContent(), -1)) { + break; + } + + $index = $whitespaceIndex; + } + + $explodedContent = explode("\n", $whitespaceToken->getContent()); + + return end($explodedContent); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CT.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CT.php new file mode 100644 index 00000000..0b32ef94 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CT.php @@ -0,0 +1,106 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +/** + * @author Dariusz Rumiński + */ +final class CT +{ + public const T_ARRAY_INDEX_CURLY_BRACE_CLOSE = 10001; + public const T_ARRAY_INDEX_CURLY_BRACE_OPEN = 10002; + public const T_ARRAY_SQUARE_BRACE_CLOSE = 10003; + public const T_ARRAY_SQUARE_BRACE_OPEN = 10004; + public const T_ARRAY_TYPEHINT = 10005; + public const T_BRACE_CLASS_INSTANTIATION_CLOSE = 10006; + public const T_BRACE_CLASS_INSTANTIATION_OPEN = 10007; + public const T_CLASS_CONSTANT = 10008; + public const T_CONST_IMPORT = 10009; + public const T_CURLY_CLOSE = 10010; + public const T_DESTRUCTURING_SQUARE_BRACE_CLOSE = 10011; + public const T_DESTRUCTURING_SQUARE_BRACE_OPEN = 10012; + public const T_DOLLAR_CLOSE_CURLY_BRACES = 10013; + public const T_DYNAMIC_PROP_BRACE_CLOSE = 10014; + public const T_DYNAMIC_PROP_BRACE_OPEN = 10015; + public const T_DYNAMIC_VAR_BRACE_CLOSE = 10016; + public const T_DYNAMIC_VAR_BRACE_OPEN = 10017; + public const T_FUNCTION_IMPORT = 10018; + public const T_GROUP_IMPORT_BRACE_CLOSE = 10019; + public const T_GROUP_IMPORT_BRACE_OPEN = 10020; + public const T_NAMESPACE_OPERATOR = 10021; + public const T_NULLABLE_TYPE = 10022; + public const T_RETURN_REF = 10023; + public const T_TYPE_ALTERNATION = 10024; + public const T_TYPE_COLON = 10025; + public const T_USE_LAMBDA = 10026; + public const T_USE_TRAIT = 10027; + public const T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC = 10028; + public const T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED = 10029; + public const T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE = 10030; + public const T_ATTRIBUTE_CLOSE = 10031; + public const T_NAMED_ARGUMENT_NAME = 10032; + public const T_NAMED_ARGUMENT_COLON = 10033; + public const T_FIRST_CLASS_CALLABLE = 10034; + public const T_TYPE_INTERSECTION = 10035; + public const T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN = 10036; + public const T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE = 10037; + public const T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_OPEN = 10038; + public const T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_CLOSE = 10039; + + private function __construct() {} + + /** + * Get name for custom token. + * + * @param int $value custom token value + */ + public static function getName(int $value): string + { + if (!self::has($value)) { + throw new \InvalidArgumentException(sprintf('No custom token was found for "%s".', $value)); + } + + $tokens = self::getMapById(); + + return 'CT::'.$tokens[$value]; + } + + /** + * Check if given custom token exists. + * + * @param int $value custom token value + */ + public static function has(int $value): bool + { + $tokens = self::getMapById(); + + return isset($tokens[$value]); + } + + /** + * @return array + */ + private static function getMapById(): array + { + static $constants; + + if (null === $constants) { + $reflection = new \ReflectionClass(__CLASS__); + $constants = array_flip($reflection->getConstants()); + } + + return $constants; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CodeHasher.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CodeHasher.php new file mode 100644 index 00000000..ec316615 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CodeHasher.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class CodeHasher +{ + private function __construct() + { + // cannot create instance of util. class + } + + /** + * Calculate hash for code. + */ + public static function calculateCodeHash(string $code): string + { + return md5($code); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Token.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Token.php new file mode 100644 index 00000000..1009717c --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Token.php @@ -0,0 +1,508 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +/** + * Representation of single token. + * As a token prototype you should understand a single element generated by token_get_all. + * + * @author Dariusz Rumiński + */ +final class Token +{ + /** + * Content of token prototype. + */ + private string $content; + + /** + * ID of token prototype, if available. + */ + private ?int $id = null; + + /** + * If token prototype is an array. + */ + private bool $isArray; + + /** + * Flag is token was changed. + */ + private bool $changed = false; + + /** + * @param array{int, string}|string $token token prototype + */ + public function __construct($token) + { + if (\is_array($token)) { + if (!\is_int($token[0])) { + throw new \InvalidArgumentException(sprintf( + 'Id must be an int, got "%s".', + get_debug_type($token[0]) + )); + } + + if (!\is_string($token[1])) { + throw new \InvalidArgumentException(sprintf( + 'Content must be a string, got "%s".', + get_debug_type($token[1]) + )); + } + + if ('' === $token[1]) { + throw new \InvalidArgumentException('Cannot set empty content for id-based Token.'); + } + + $this->isArray = true; + $this->id = $token[0]; + $this->content = $token[1]; + } elseif (\is_string($token)) { + $this->isArray = false; + $this->content = $token; + } else { + throw new \InvalidArgumentException(sprintf('Cannot recognize input value as valid Token prototype, got "%s".', get_debug_type($token))); + } + } + + /** + * @return list + */ + public static function getCastTokenKinds(): array + { + static $castTokens = [T_ARRAY_CAST, T_BOOL_CAST, T_DOUBLE_CAST, T_INT_CAST, T_OBJECT_CAST, T_STRING_CAST, T_UNSET_CAST]; + + return $castTokens; + } + + /** + * Get classy tokens kinds: T_CLASS, T_INTERFACE and T_TRAIT. + * + * @return list + */ + public static function getClassyTokenKinds(): array + { + static $classTokens; + + if (null === $classTokens) { + $classTokens = [T_CLASS, T_TRAIT, T_INTERFACE]; + + if (\defined('T_ENUM')) { // @TODO: drop condition when PHP 8.1+ is required + $classTokens[] = T_ENUM; + } + } + + return $classTokens; + } + + /** + * Get object operator tokens kinds: T_OBJECT_OPERATOR and (if available) T_NULLSAFE_OBJECT_OPERATOR. + * + * @return list + */ + public static function getObjectOperatorKinds(): array + { + static $objectOperators = null; + + if (null === $objectOperators) { + $objectOperators = [T_OBJECT_OPERATOR]; + if (\defined('T_NULLSAFE_OBJECT_OPERATOR')) { + $objectOperators[] = T_NULLSAFE_OBJECT_OPERATOR; + } + } + + return $objectOperators; + } + + /** + * Check if token is equals to given one. + * + * If tokens are arrays, then only keys defined in parameter token are checked. + * + * @param array{0: int, 1?: string}|string|Token $other token or it's prototype + * @param bool $caseSensitive perform a case sensitive comparison + */ + public function equals($other, bool $caseSensitive = true): bool + { + if (\defined('T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG')) { // @TODO: drop condition when PHP 8.1+ is required + if ('&' === $other) { + return '&' === $this->content && (null === $this->id || $this->isGivenKind([T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG])); + } + if (null === $this->id && '&' === $this->content) { + return $other instanceof self && '&' === $other->content && (null === $other->id || $other->isGivenKind([T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG])); + } + } + + if ($other instanceof self) { + // Inlined getPrototype() on this very hot path. + // We access the private properties of $other directly to save function call overhead. + // This is only possible because $other is of the same class as `self`. + if (!$other->isArray) { + $otherPrototype = $other->content; + } else { + $otherPrototype = [ + $other->id, + $other->content, + ]; + } + } else { + $otherPrototype = $other; + } + + if ($this->isArray !== \is_array($otherPrototype)) { + return false; + } + + if (!$this->isArray) { + return $this->content === $otherPrototype; + } + + if ($this->id !== $otherPrototype[0]) { + return false; + } + + if (isset($otherPrototype[1])) { + if ($caseSensitive) { + if ($this->content !== $otherPrototype[1]) { + return false; + } + } elseif (0 !== strcasecmp($this->content, $otherPrototype[1])) { + return false; + } + } + + // detect unknown keys + unset($otherPrototype[0], $otherPrototype[1]); + + return [] === $otherPrototype; + } + + /** + * Check if token is equals to one of given. + * + * @param list $others array of tokens or token prototypes + * @param bool $caseSensitive perform a case sensitive comparison + */ + public function equalsAny(array $others, bool $caseSensitive = true): bool + { + foreach ($others as $other) { + if ($this->equals($other, $caseSensitive)) { + return true; + } + } + + return false; + } + + /** + * A helper method used to find out whether a certain input token has to be case-sensitively matched. + * + * @param bool|list $caseSensitive global case sensitiveness or an array of booleans, whose keys should match + * the ones used in $sequence. If any is missing, the default case-sensitive + * comparison is used + * @param int $key the key of the token that has to be looked up + */ + public static function isKeyCaseSensitive($caseSensitive, int $key): bool + { + if (\is_array($caseSensitive)) { + return $caseSensitive[$key] ?? true; + } + + return $caseSensitive; + } + + /** + * @return array{int, string}|string + */ + public function getPrototype() + { + if (!$this->isArray) { + return $this->content; + } + + return [ + $this->id, + $this->content, + ]; + } + + /** + * Get token's content. + * + * It shall be used only for getting the content of token, not for checking it against excepted value. + */ + public function getContent(): string + { + return $this->content; + } + + /** + * Get token's id. + * + * It shall be used only for getting the internal id of token, not for checking it against excepted value. + */ + public function getId(): ?int + { + return $this->id; + } + + /** + * Get token's name. + * + * It shall be used only for getting the name of token, not for checking it against excepted value. + * + * @return null|string token name + */ + public function getName(): ?string + { + if (null === $this->id) { + return null; + } + + return self::getNameForId($this->id); + } + + /** + * Get token's name. + * + * It shall be used only for getting the name of token, not for checking it against excepted value. + * + * @return null|string token name + */ + public static function getNameForId(int $id): ?string + { + if (CT::has($id)) { + return CT::getName($id); + } + + $name = token_name($id); + + return 'UNKNOWN' === $name ? null : $name; + } + + /** + * Generate array containing all keywords that exists in PHP version in use. + * + * @return array + */ + public static function getKeywords(): array + { + static $keywords = null; + + if (null === $keywords) { + $keywords = self::getTokenKindsForNames(['T_ABSTRACT', 'T_ARRAY', 'T_AS', 'T_BREAK', 'T_CALLABLE', 'T_CASE', + 'T_CATCH', 'T_CLASS', 'T_CLONE', 'T_CONST', 'T_CONTINUE', 'T_DECLARE', 'T_DEFAULT', 'T_DO', + 'T_ECHO', 'T_ELSE', 'T_ELSEIF', 'T_EMPTY', 'T_ENDDECLARE', 'T_ENDFOR', 'T_ENDFOREACH', + 'T_ENDIF', 'T_ENDSWITCH', 'T_ENDWHILE', 'T_EVAL', 'T_EXIT', 'T_EXTENDS', 'T_FINAL', + 'T_FINALLY', 'T_FN', 'T_FOR', 'T_FOREACH', 'T_FUNCTION', 'T_GLOBAL', 'T_GOTO', 'T_HALT_COMPILER', + 'T_IF', 'T_IMPLEMENTS', 'T_INCLUDE', 'T_INCLUDE_ONCE', 'T_INSTANCEOF', 'T_INSTEADOF', + 'T_INTERFACE', 'T_ISSET', 'T_LIST', 'T_LOGICAL_AND', 'T_LOGICAL_OR', 'T_LOGICAL_XOR', + 'T_NAMESPACE', 'T_MATCH', 'T_NEW', 'T_PRINT', 'T_PRIVATE', 'T_PROTECTED', 'T_PUBLIC', 'T_REQUIRE', + 'T_REQUIRE_ONCE', 'T_RETURN', 'T_STATIC', 'T_SWITCH', 'T_THROW', 'T_TRAIT', 'T_TRY', + 'T_UNSET', 'T_USE', 'T_VAR', 'T_WHILE', 'T_YIELD', 'T_YIELD_FROM', 'T_READONLY', 'T_ENUM', + ]) + [ + CT::T_ARRAY_TYPEHINT => CT::T_ARRAY_TYPEHINT, + CT::T_CLASS_CONSTANT => CT::T_CLASS_CONSTANT, + CT::T_CONST_IMPORT => CT::T_CONST_IMPORT, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, + CT::T_FUNCTION_IMPORT => CT::T_FUNCTION_IMPORT, + CT::T_NAMESPACE_OPERATOR => CT::T_NAMESPACE_OPERATOR, + CT::T_USE_LAMBDA => CT::T_USE_LAMBDA, + CT::T_USE_TRAIT => CT::T_USE_TRAIT, + ]; + } + + return $keywords; + } + + /** + * Generate array containing all predefined constants that exists in PHP version in use. + * + * @see https://php.net/manual/en/language.constants.predefined.php + * + * @return array + */ + public static function getMagicConstants(): array + { + static $magicConstants = null; + + if (null === $magicConstants) { + $magicConstants = self::getTokenKindsForNames(['T_CLASS_C', 'T_DIR', 'T_FILE', 'T_FUNC_C', 'T_LINE', 'T_METHOD_C', 'T_NS_C', 'T_TRAIT_C']); + } + + return $magicConstants; + } + + /** + * Check if token prototype is an array. + * + * @return bool is array + */ + public function isArray(): bool + { + return $this->isArray; + } + + /** + * Check if token is one of type cast tokens. + */ + public function isCast(): bool + { + return $this->isGivenKind(self::getCastTokenKinds()); + } + + /** + * Check if token is one of classy tokens: T_CLASS, T_INTERFACE, T_TRAIT or T_ENUM. + */ + public function isClassy(): bool + { + return $this->isGivenKind(self::getClassyTokenKinds()); + } + + /** + * Check if token is one of comment tokens: T_COMMENT or T_DOC_COMMENT. + */ + public function isComment(): bool + { + static $commentTokens = [T_COMMENT, T_DOC_COMMENT]; + + return $this->isGivenKind($commentTokens); + } + + /** + * Check if token is one of object operator tokens: T_OBJECT_OPERATOR or T_NULLSAFE_OBJECT_OPERATOR. + */ + public function isObjectOperator(): bool + { + return $this->isGivenKind(self::getObjectOperatorKinds()); + } + + /** + * Check if token is one of given kind. + * + * @param int|list $possibleKind kind or array of kinds + */ + public function isGivenKind($possibleKind): bool + { + return $this->isArray && (\is_array($possibleKind) ? \in_array($this->id, $possibleKind, true) : $this->id === $possibleKind); + } + + /** + * Check if token is a keyword. + */ + public function isKeyword(): bool + { + $keywords = self::getKeywords(); + + return $this->isArray && isset($keywords[$this->id]); + } + + /** + * Check if token is a native PHP constant: true, false or null. + */ + public function isNativeConstant(): bool + { + static $nativeConstantStrings = ['true', 'false', 'null']; + + return $this->isArray && \in_array(strtolower($this->content), $nativeConstantStrings, true); + } + + /** + * Returns if the token is of a Magic constants type. + * + * @see https://php.net/manual/en/language.constants.predefined.php + */ + public function isMagicConstant(): bool + { + $magicConstants = self::getMagicConstants(); + + return $this->isArray && isset($magicConstants[$this->id]); + } + + /** + * Check if token is whitespace. + * + * @param null|string $whitespaces whitespace characters, default is " \t\n\r\0\x0B" + */ + public function isWhitespace(?string $whitespaces = " \t\n\r\0\x0B"): bool + { + if (null === $whitespaces) { + $whitespaces = " \t\n\r\0\x0B"; + } + + if ($this->isArray && !$this->isGivenKind(T_WHITESPACE)) { + return false; + } + + return '' === trim($this->content, $whitespaces); + } + + /** + * @return array{ + * id: int|null, + * name: string|null, + * content: string, + * isArray: bool, + * changed: bool, + * } + */ + public function toArray(): array + { + return [ + 'id' => $this->id, + 'name' => $this->getName(), + 'content' => $this->content, + 'isArray' => $this->isArray, + 'changed' => $this->changed, + ]; + } + + public function toJson(): string + { + $jsonResult = json_encode($this->toArray(), JSON_PRETTY_PRINT | JSON_NUMERIC_CHECK); + + if (JSON_ERROR_NONE !== json_last_error()) { + $jsonResult = json_encode( + [ + 'errorDescription' => 'Cannot encode Tokens to JSON.', + 'rawErrorMessage' => json_last_error_msg(), + ], + JSON_PRETTY_PRINT | JSON_NUMERIC_CHECK + ); + } + + return $jsonResult; + } + + /** + * @param list $tokenNames + * + * @return array + */ + private static function getTokenKindsForNames(array $tokenNames): array + { + $keywords = []; + foreach ($tokenNames as $keywordName) { + if (\defined($keywordName)) { + $keyword = \constant($keywordName); + $keywords[$keyword] = $keyword; + } + } + + return $keywords; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Tokens.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Tokens.php new file mode 100644 index 00000000..a7e2e9ce --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Tokens.php @@ -0,0 +1,1434 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer; + +/** + * Collection of code tokens. + * + * Its role is to provide the ability to manage collection and navigate through it. + * + * As a token prototype you should understand a single element generated by token_get_all. + * + * @author Dariusz Rumiński + * + * @extends \SplFixedArray + * + * @method Token offsetGet($offset) + * + * @final + */ +class Tokens extends \SplFixedArray +{ + public const BLOCK_TYPE_PARENTHESIS_BRACE = 1; + public const BLOCK_TYPE_CURLY_BRACE = 2; + public const BLOCK_TYPE_INDEX_SQUARE_BRACE = 3; + public const BLOCK_TYPE_ARRAY_SQUARE_BRACE = 4; + public const BLOCK_TYPE_DYNAMIC_PROP_BRACE = 5; + public const BLOCK_TYPE_DYNAMIC_VAR_BRACE = 6; + public const BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE = 7; + public const BLOCK_TYPE_GROUP_IMPORT_BRACE = 8; + public const BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE = 9; + public const BLOCK_TYPE_BRACE_CLASS_INSTANTIATION = 10; + public const BLOCK_TYPE_ATTRIBUTE = 11; + public const BLOCK_TYPE_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS = 12; + public const BLOCK_TYPE_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE = 13; + + /** + * Static class cache. + * + * @var array + */ + private static array $cache = []; + + /** + * Cache of block starts. Any change in collection will invalidate it. + * + * @var array + */ + private array $blockStartCache = []; + + /** + * Cache of block ends. Any change in collection will invalidate it. + * + * @var array + */ + private array $blockEndCache = []; + + /** + * A MD5 hash of the code string. + */ + private ?string $codeHash = null; + + /** + * Flag is collection was changed. + * + * It doesn't know about change of collection's items. To check it run `isChanged` method. + */ + private bool $changed = false; + + /** + * Set of found token kinds. + * + * When the token kind is present in this set it means that given token kind + * was ever seen inside the collection (but may not be part of it any longer). + * The key is token kind and the value is always true. + * + * @var array + */ + private array $foundTokenKinds = []; + + /** + * @var null|list + */ + private ?array $namespaceDeclarations = null; + + /** + * Clone tokens collection. + */ + public function __clone() + { + foreach ($this as $key => $val) { + $this[$key] = clone $val; + } + } + + /** + * Clear cache - one position or all of them. + * + * @param null|string $key position to clear, when null clear all + */ + public static function clearCache(?string $key = null): void + { + if (null === $key) { + self::$cache = []; + + return; + } + + unset(self::$cache[$key]); + } + + /** + * Detect type of block. + * + * @param Token $token token + * + * @return null|array{type: self::BLOCK_TYPE_*, isStart: bool} + */ + public static function detectBlockType(Token $token): ?array + { + foreach (self::getBlockEdgeDefinitions() as $type => $definition) { + if ($token->equals($definition['start'])) { + return ['type' => $type, 'isStart' => true]; + } + + if ($token->equals($definition['end'])) { + return ['type' => $type, 'isStart' => false]; + } + } + + return null; + } + + /** + * Create token collection from array. + * + * @param Token[] $array the array to import + * @param ?bool $saveIndices save the numeric indices used in the original array, default is yes + */ + public static function fromArray($array, $saveIndices = null): self + { + $tokens = new self(\count($array)); + + if ($saveIndices ?? true) { + foreach ($array as $key => $val) { + $tokens[$key] = $val; + } + } else { + $index = 0; + + foreach ($array as $val) { + $tokens[$index++] = $val; + } + } + + $tokens->generateCode(); // regenerate code to calculate code hash + $tokens->clearChanged(); + + return $tokens; + } + + /** + * Create token collection directly from code. + * + * @param string $code PHP code + */ + public static function fromCode(string $code): self + { + $codeHash = self::calculateCodeHash($code); + + if (self::hasCache($codeHash)) { + $tokens = self::getCache($codeHash); + + // generate the code to recalculate the hash + $tokens->generateCode(); + + if ($codeHash === $tokens->codeHash) { + $tokens->clearEmptyTokens(); + $tokens->clearChanged(); + + return $tokens; + } + } + + $tokens = new self(); + $tokens->setCode($code); + $tokens->clearChanged(); + + return $tokens; + } + + /** + * @return array> + */ + public static function getBlockEdgeDefinitions(): array + { + $definitions = [ + self::BLOCK_TYPE_CURLY_BRACE => [ + 'start' => '{', + 'end' => '}', + ], + self::BLOCK_TYPE_PARENTHESIS_BRACE => [ + 'start' => '(', + 'end' => ')', + ], + self::BLOCK_TYPE_INDEX_SQUARE_BRACE => [ + 'start' => '[', + 'end' => ']', + ], + self::BLOCK_TYPE_ARRAY_SQUARE_BRACE => [ + 'start' => [CT::T_ARRAY_SQUARE_BRACE_OPEN, '['], + 'end' => [CT::T_ARRAY_SQUARE_BRACE_CLOSE, ']'], + ], + self::BLOCK_TYPE_DYNAMIC_PROP_BRACE => [ + 'start' => [CT::T_DYNAMIC_PROP_BRACE_OPEN, '{'], + 'end' => [CT::T_DYNAMIC_PROP_BRACE_CLOSE, '}'], + ], + self::BLOCK_TYPE_DYNAMIC_VAR_BRACE => [ + 'start' => [CT::T_DYNAMIC_VAR_BRACE_OPEN, '{'], + 'end' => [CT::T_DYNAMIC_VAR_BRACE_CLOSE, '}'], + ], + self::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE => [ + 'start' => [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{'], + 'end' => [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE, '}'], + ], + self::BLOCK_TYPE_GROUP_IMPORT_BRACE => [ + 'start' => [CT::T_GROUP_IMPORT_BRACE_OPEN, '{'], + 'end' => [CT::T_GROUP_IMPORT_BRACE_CLOSE, '}'], + ], + self::BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE => [ + 'start' => [CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, '['], + 'end' => [CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ']'], + ], + self::BLOCK_TYPE_BRACE_CLASS_INSTANTIATION => [ + 'start' => [CT::T_BRACE_CLASS_INSTANTIATION_OPEN, '('], + 'end' => [CT::T_BRACE_CLASS_INSTANTIATION_CLOSE, ')'], + ], + self::BLOCK_TYPE_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS => [ + 'start' => [CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '('], + 'end' => [CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')'], + ], + self::BLOCK_TYPE_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE => [ + 'start' => [CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_OPEN, '{'], + 'end' => [CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_CLOSE, '}'], + ], + ]; + + // @TODO: drop condition when PHP 8.0+ is required + if (\defined('T_ATTRIBUTE')) { + $definitions[self::BLOCK_TYPE_ATTRIBUTE] = [ + 'start' => [T_ATTRIBUTE, '#['], + 'end' => [CT::T_ATTRIBUTE_CLOSE, ']'], + ]; + } + + return $definitions; + } + + /** + * Set new size of collection. + * + * @param int $size + */ + public function setSize($size): bool + { + if ($this->getSize() !== $size) { + $this->changed = true; + $this->namespaceDeclarations = null; + + return parent::setSize($size); + } + + return true; + } + + /** + * Unset collection item. + * + * @param int $index + */ + public function offsetUnset($index): void + { + $this->changed = true; + $this->namespaceDeclarations = null; + if (isset($this[$index])) { + $this->unregisterFoundToken($this[$index]); + } + + parent::offsetUnset($index); + } + + /** + * Set collection item. + * + * Warning! `$newval` must not be typehinted to be compatible with `ArrayAccess::offsetSet` method. + * + * @param int $index + * @param Token $newval + */ + public function offsetSet($index, $newval): void + { + $this->blockStartCache = []; + $this->blockEndCache = []; + + if (!isset($this[$index]) || !$this[$index]->equals($newval)) { + $this->changed = true; + $this->namespaceDeclarations = null; + + if (isset($this[$index])) { + $this->unregisterFoundToken($this[$index]); + } + $this->registerFoundToken($newval); + } + + parent::offsetSet($index, $newval); + } + + /** + * Clear internal flag if collection was changed and flag for all collection's items. + */ + public function clearChanged(): void + { + $this->changed = false; + } + + /** + * Clear empty tokens. + * + * Empty tokens can occur e.g. after calling clear on item of collection. + */ + public function clearEmptyTokens(): void + { + $limit = $this->count(); + + for ($index = 0; $index < $limit; ++$index) { + if ($this->isEmptyAt($index)) { + break; + } + } + + // no empty token found, therefore there is no need to override collection + if ($limit === $index) { + return; + } + + for ($count = $index; $index < $limit; ++$index) { + if (!$this->isEmptyAt($index)) { + // use directly for speed, skip the register of token kinds found etc. + parent::offsetSet($count++, $this[$index]); + } + } + + // we are moving the tokens, we need to clear the indices Cache + $this->blockStartCache = []; + $this->blockEndCache = []; + + $this->setSize($count); + } + + /** + * Ensure that on given index is a whitespace with given kind. + * + * If there is a whitespace then it's content will be modified. + * If not - the new Token will be added. + * + * @param int $index index + * @param int $indexOffset index offset for Token insertion + * @param string $whitespace whitespace to set + * + * @return bool if new Token was added + */ + public function ensureWhitespaceAtIndex(int $index, int $indexOffset, string $whitespace): bool + { + $removeLastCommentLine = static function (self $tokens, int $index, int $indexOffset, string $whitespace): string { + $token = $tokens[$index]; + + if (1 === $indexOffset && $token->isGivenKind(T_OPEN_TAG)) { + if (str_starts_with($whitespace, "\r\n")) { + $tokens[$index] = new Token([T_OPEN_TAG, rtrim($token->getContent())."\r\n"]); + + return \strlen($whitespace) > 2 // @TODO: can be removed on PHP 8; https://php.net/manual/en/function.substr.php + ? substr($whitespace, 2) + : ''; + } + + $tokens[$index] = new Token([T_OPEN_TAG, rtrim($token->getContent()).$whitespace[0]]); + + return \strlen($whitespace) > 1 // @TODO: can be removed on PHP 8; https://php.net/manual/en/function.substr.php + ? substr($whitespace, 1) + : ''; + } + + return $whitespace; + }; + + if ($this[$index]->isWhitespace()) { + $whitespace = $removeLastCommentLine($this, $index - 1, $indexOffset, $whitespace); + + if ('' === $whitespace) { + $this->clearAt($index); + } else { + $this[$index] = new Token([T_WHITESPACE, $whitespace]); + } + + return false; + } + + $whitespace = $removeLastCommentLine($this, $index, $indexOffset, $whitespace); + + if ('' === $whitespace) { + return false; + } + + $this->insertAt( + $index + $indexOffset, + [new Token([T_WHITESPACE, $whitespace])] + ); + + return true; + } + + /** + * @param self::BLOCK_TYPE_* $type type of block + * @param int $searchIndex index of opening brace + * + * @return int index of closing brace + */ + public function findBlockEnd(int $type, int $searchIndex): int + { + return $this->findOppositeBlockEdge($type, $searchIndex, true); + } + + /** + * @param self::BLOCK_TYPE_* $type type of block + * @param int $searchIndex index of closing brace + * + * @return int index of opening brace + */ + public function findBlockStart(int $type, int $searchIndex): int + { + return $this->findOppositeBlockEdge($type, $searchIndex, false); + } + + /** + * @param int|list $possibleKind kind or array of kinds + * @param int $start optional offset + * @param null|int $end optional limit + * + * @return array>|array + */ + public function findGivenKind($possibleKind, int $start = 0, ?int $end = null): array + { + if (null === $end) { + $end = $this->count(); + } + + $elements = []; + $possibleKinds = (array) $possibleKind; + + foreach ($possibleKinds as $kind) { + $elements[$kind] = []; + } + + $possibleKinds = array_filter($possibleKinds, fn ($kind): bool => $this->isTokenKindFound($kind)); + + if (\count($possibleKinds) > 0) { + for ($i = $start; $i < $end; ++$i) { + $token = $this[$i]; + if ($token->isGivenKind($possibleKinds)) { + $elements[$token->getId()][$i] = $token; + } + } + } + + return \is_array($possibleKind) ? $elements : $elements[$possibleKind]; + } + + public function generateCode(): string + { + $code = $this->generatePartialCode(0, \count($this) - 1); + $this->changeCodeHash(self::calculateCodeHash($code)); + + return $code; + } + + /** + * Generate code from tokens between given indices. + * + * @param int $start start index + * @param int $end end index + */ + public function generatePartialCode(int $start, int $end): string + { + $code = ''; + + for ($i = $start; $i <= $end; ++$i) { + $code .= $this[$i]->getContent(); + } + + return $code; + } + + /** + * Get hash of code. + */ + public function getCodeHash(): string + { + return $this->codeHash; + } + + /** + * Get index for closest next token which is non whitespace. + * + * This method is shorthand for getNonWhitespaceSibling method. + * + * @param int $index token index + * @param null|string $whitespaces whitespaces characters for Token::isWhitespace + */ + public function getNextNonWhitespace(int $index, ?string $whitespaces = null): ?int + { + return $this->getNonWhitespaceSibling($index, 1, $whitespaces); + } + + /** + * Get index for closest next token of given kind. + * + * This method is shorthand for getTokenOfKindSibling method. + * + * @param int $index token index + * @param list $tokens possible tokens + * @param bool $caseSensitive perform a case sensitive comparison + */ + public function getNextTokenOfKind(int $index, array $tokens = [], bool $caseSensitive = true): ?int + { + return $this->getTokenOfKindSibling($index, 1, $tokens, $caseSensitive); + } + + /** + * Get index for closest sibling token which is non whitespace. + * + * @param int $index token index + * @param -1|1 $direction + * @param null|string $whitespaces whitespaces characters for Token::isWhitespace + */ + public function getNonWhitespaceSibling(int $index, int $direction, ?string $whitespaces = null): ?int + { + while (true) { + $index += $direction; + + if (!$this->offsetExists($index)) { + return null; + } + + if (!$this[$index]->isWhitespace($whitespaces)) { + return $index; + } + } + } + + /** + * Get index for closest previous token which is non whitespace. + * + * This method is shorthand for getNonWhitespaceSibling method. + * + * @param int $index token index + * @param null|string $whitespaces whitespaces characters for Token::isWhitespace + */ + public function getPrevNonWhitespace(int $index, ?string $whitespaces = null): ?int + { + return $this->getNonWhitespaceSibling($index, -1, $whitespaces); + } + + /** + * Get index for closest previous token of given kind. + * This method is shorthand for getTokenOfKindSibling method. + * + * @param int $index token index + * @param list $tokens possible tokens + * @param bool $caseSensitive perform a case sensitive comparison + */ + public function getPrevTokenOfKind(int $index, array $tokens = [], bool $caseSensitive = true): ?int + { + return $this->getTokenOfKindSibling($index, -1, $tokens, $caseSensitive); + } + + /** + * Get index for closest sibling token of given kind. + * + * @param int $index token index + * @param -1|1 $direction + * @param list $tokens possible tokens + * @param bool $caseSensitive perform a case sensitive comparison + */ + public function getTokenOfKindSibling(int $index, int $direction, array $tokens = [], bool $caseSensitive = true): ?int + { + $tokens = array_filter($tokens, fn ($token): bool => $this->isTokenKindFound($this->extractTokenKind($token))); + + if (0 === \count($tokens)) { + return null; + } + + while (true) { + $index += $direction; + + if (!$this->offsetExists($index)) { + return null; + } + + if ($this[$index]->equalsAny($tokens, $caseSensitive)) { + return $index; + } + } + } + + /** + * Get index for closest sibling token not of given kind. + * + * @param int $index token index + * @param -1|1 $direction + * @param list $tokens possible tokens + */ + public function getTokenNotOfKindSibling(int $index, int $direction, array $tokens = []): ?int + { + return $this->getTokenNotOfKind( + $index, + $direction, + fn (int $a): bool => $this[$a]->equalsAny($tokens), + ); + } + + /** + * Get index for closest sibling token not of given kind. + * + * @param int $index token index + * @param -1|1 $direction + * @param list $kinds possible tokens kinds + */ + public function getTokenNotOfKindsSibling(int $index, int $direction, array $kinds = []): ?int + { + return $this->getTokenNotOfKind( + $index, + $direction, + fn (int $index): bool => $this[$index]->isGivenKind($kinds), + ); + } + + /** + * Get index for closest sibling token that is not a whitespace, comment or attribute. + * + * @param int $index token index + * @param -1|1 $direction + */ + public function getMeaningfulTokenSibling(int $index, int $direction): ?int + { + return $this->getTokenNotOfKindsSibling( + $index, + $direction, + [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT] + ); + } + + /** + * Get index for closest sibling token which is not empty. + * + * @param int $index token index + * @param -1|1 $direction + */ + public function getNonEmptySibling(int $index, int $direction): ?int + { + while (true) { + $index += $direction; + + if (!$this->offsetExists($index)) { + return null; + } + + if (!$this->isEmptyAt($index)) { + return $index; + } + } + } + + /** + * Get index for closest next token that is not a whitespace or comment. + * + * @param int $index token index + */ + public function getNextMeaningfulToken(int $index): ?int + { + return $this->getMeaningfulTokenSibling($index, 1); + } + + /** + * Get index for closest previous token that is not a whitespace or comment. + * + * @param int $index token index + */ + public function getPrevMeaningfulToken(int $index): ?int + { + return $this->getMeaningfulTokenSibling($index, -1); + } + + /** + * Find a sequence of meaningful tokens and returns the array of their locations. + * + * @param list $sequence an array of token (kinds) + * @param int $start start index, defaulting to the start of the file + * @param null|int $end end index, defaulting to the end of the file + * @param array|bool $caseSensitive global case sensitiveness or a list of booleans, whose keys should match + * the ones used in $sequence. If any is missing, the default case-sensitive + * comparison is used + * + * @return null|array an array containing the tokens matching the sequence elements, indexed by their position + */ + public function findSequence(array $sequence, int $start = 0, ?int $end = null, $caseSensitive = true): ?array + { + $sequenceCount = \count($sequence); + if (0 === $sequenceCount) { + throw new \InvalidArgumentException('Invalid sequence.'); + } + + // $end defaults to the end of the collection + $end = null === $end ? \count($this) - 1 : min($end, \count($this) - 1); + + if ($start + $sequenceCount - 1 > $end) { + return null; + } + + $nonMeaningFullKind = [T_COMMENT, T_DOC_COMMENT, T_WHITESPACE]; + + // make sure the sequence content is "meaningful" + foreach ($sequence as $key => $token) { + // if not a Token instance already, we convert it to verify the meaningfulness + if (!$token instanceof Token) { + if (\is_array($token) && !isset($token[1])) { + // fake some content as it is required by the Token constructor, + // although optional for search purposes + $token[1] = 'DUMMY'; + } + + $token = new Token($token); + } + + if ($token->isGivenKind($nonMeaningFullKind)) { + throw new \InvalidArgumentException(sprintf('Non-meaningful token at position: "%s".', $key)); + } + + if ('' === $token->getContent()) { + throw new \InvalidArgumentException(sprintf('Non-meaningful (empty) token at position: "%s".', $key)); + } + } + + foreach ($sequence as $token) { + if (!$this->isTokenKindFound($this->extractTokenKind($token))) { + return null; + } + } + + // remove the first token from the sequence, so we can freely iterate through the sequence after a match to + // the first one is found + $key = key($sequence); + $firstCs = Token::isKeyCaseSensitive($caseSensitive, $key); + $firstToken = $sequence[$key]; + unset($sequence[$key]); + + // begin searching for the first token in the sequence (start included) + $index = $start - 1; + while ($index <= $end) { + $index = $this->getNextTokenOfKind($index, [$firstToken], $firstCs); + + // ensure we found a match and didn't get past the end index + if (null === $index || $index > $end) { + return null; + } + + // initialise the result array with the current index + $result = [$index => $this[$index]]; + + // advance cursor to the current position + $currIdx = $index; + + // iterate through the remaining tokens in the sequence + foreach ($sequence as $key => $token) { + $currIdx = $this->getNextMeaningfulToken($currIdx); + + // ensure we didn't go too far + if (null === $currIdx || $currIdx > $end) { + return null; + } + + if (!$this[$currIdx]->equals($token, Token::isKeyCaseSensitive($caseSensitive, $key))) { + // not a match, restart the outer loop + continue 2; + } + + // append index to the result array + $result[$currIdx] = $this[$currIdx]; + } + + // do we have a complete match? + // hint: $result is bigger than $sequence since the first token has been removed from the latter + if (\count($sequence) < \count($result)) { + return $result; + } + } + + return null; + } + + /** + * Insert instances of Token inside collection. + * + * @param int $index start inserting index + * @param list|Token|Tokens $items instances of Token to insert + */ + public function insertAt(int $index, $items): void + { + $this->insertSlices([$index => $items]); + } + + /** + * Insert a slices or individual Tokens into multiple places in a single run. + * + * This approach is kind-of an experiment - it's proven to improve performance a lot for big files that needs plenty of new tickets to be inserted, + * like edge case example of 3.7h vs 4s (https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues/3996#issuecomment-455617637), + * yet at same time changing a logic of fixers in not-always easy way. + * + * To be discussed: + * - should we always aim to use this method? + * - should we deprecate `insertAt` method ? + * + * The `$slices` parameter is an assoc array, in which: + * - index: starting point for inserting of individual slice, with indices being relatives to original array collection before any Token inserted + * - value under index: a slice of Tokens to be inserted + * + * @internal + * + * @param array|Token|Tokens> $slices + */ + public function insertSlices(array $slices): void + { + $itemsCount = 0; + + foreach ($slices as $slice) { + $itemsCount += \is_array($slice) || $slice instanceof self ? \count($slice) : 1; + } + + if (0 === $itemsCount) { + return; + } + + $oldSize = \count($this); + $this->changed = true; + $this->namespaceDeclarations = null; + $this->blockStartCache = []; + $this->blockEndCache = []; + $this->setSize($oldSize + $itemsCount); + + krsort($slices); + $farthestSliceIndex = key($slices); + + // We check only the farthest index, if it's within the size of collection, other indices will be valid too. + if (!\is_int($farthestSliceIndex) || $farthestSliceIndex > $oldSize) { + throw new \OutOfBoundsException(sprintf('Cannot insert index "%s" outside of collection.', $farthestSliceIndex)); + } + + $previousSliceIndex = $oldSize; + + // since we only move already existing items around, we directly call into SplFixedArray::offset* methods. + // that way we get around additional overhead this class adds with overridden offset* methods. + foreach ($slices as $index => $slice) { + if (!\is_int($index) || $index < 0) { + throw new \OutOfBoundsException(sprintf('Invalid index "%s".', $index)); + } + + $slice = \is_array($slice) || $slice instanceof self ? $slice : [$slice]; + $sliceCount = \count($slice); + + for ($i = $previousSliceIndex - 1; $i >= $index; --$i) { + parent::offsetSet($i + $itemsCount, parent::offsetGet($i)); + } + + $previousSliceIndex = $index; + $itemsCount -= $sliceCount; + + foreach ($slice as $indexItem => $item) { + if ('' === $item->getContent()) { + throw new \InvalidArgumentException('Must not add empty token to collection.'); + } + + $this->registerFoundToken($item); + + parent::offsetSet($index + $itemsCount + $indexItem, $item); + } + } + } + + /** + * Check if collection was change: collection itself (like insert new tokens) or any of collection's elements. + */ + public function isChanged(): bool + { + return $this->changed; + } + + public function isEmptyAt(int $index): bool + { + $token = $this[$index]; + + return null === $token->getId() && '' === $token->getContent(); + } + + public function clearAt(int $index): void + { + $this[$index] = new Token(''); + } + + /** + * Override tokens at given range. + * + * @param int $indexStart start overriding index + * @param int $indexEnd end overriding index + * @param array|Tokens $items tokens to insert + */ + public function overrideRange(int $indexStart, int $indexEnd, iterable $items): void + { + $indexToChange = $indexEnd - $indexStart + 1; + $itemsCount = \count($items); + + // If we want to add more items than passed range contains we need to + // add placeholders for overhead items. + if ($itemsCount > $indexToChange) { + $placeholders = []; + + while ($itemsCount > $indexToChange) { + $placeholders[] = new Token('__PLACEHOLDER__'); + ++$indexToChange; + } + + $this->insertAt($indexEnd + 1, $placeholders); + } + + // Override each items. + foreach ($items as $itemIndex => $item) { + $this[$indexStart + $itemIndex] = $item; + } + + // If we want to add fewer tokens than passed range contains then clear + // not needed tokens. + if ($itemsCount < $indexToChange) { + $this->clearRange($indexStart + $itemsCount, $indexEnd); + } + } + + /** + * @param null|string $whitespaces optional whitespaces characters for Token::isWhitespace + */ + public function removeLeadingWhitespace(int $index, ?string $whitespaces = null): void + { + $this->removeWhitespaceSafely($index, -1, $whitespaces); + } + + /** + * @param null|string $whitespaces optional whitespaces characters for Token::isWhitespace + */ + public function removeTrailingWhitespace(int $index, ?string $whitespaces = null): void + { + $this->removeWhitespaceSafely($index, 1, $whitespaces); + } + + /** + * Set code. Clear all current content and replace it by new Token items generated from code directly. + * + * @param string $code PHP code + */ + public function setCode(string $code): void + { + // No need to work when the code is the same. + // That is how we avoid a lot of work and setting changed flag. + if ($code === $this->generateCode()) { + return; + } + + // clear memory + $this->setSize(0); + + $tokens = token_get_all($code, TOKEN_PARSE); + + $this->setSize(\count($tokens)); + + foreach ($tokens as $index => $token) { + $this[$index] = new Token($token); + } + + $this->applyTransformers(); + + $this->foundTokenKinds = []; + + foreach ($this as $token) { + $this->registerFoundToken($token); + } + + if (\PHP_VERSION_ID < 8_00_00) { + $this->rewind(); + } + + $this->changeCodeHash(self::calculateCodeHash($code)); + $this->changed = true; + $this->namespaceDeclarations = null; + } + + public function toJson(): string + { + $output = new \SplFixedArray(\count($this)); + + foreach ($this as $index => $token) { + $output[$index] = $token->toArray(); + } + + if (\PHP_VERSION_ID < 8_00_00) { + $this->rewind(); + } + + return json_encode($output, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT | JSON_NUMERIC_CHECK); + } + + /** + * Check if all token kinds given as argument are found. + * + * @param list $tokenKinds + */ + public function isAllTokenKindsFound(array $tokenKinds): bool + { + foreach ($tokenKinds as $tokenKind) { + if (!isset($this->foundTokenKinds[$tokenKind])) { + return false; + } + } + + return true; + } + + /** + * Check if any token kind given as argument is found. + * + * @param list $tokenKinds + */ + public function isAnyTokenKindsFound(array $tokenKinds): bool + { + foreach ($tokenKinds as $tokenKind) { + if (isset($this->foundTokenKinds[$tokenKind])) { + return true; + } + } + + return false; + } + + /** + * Check if token kind given as argument is found. + * + * @param int|string $tokenKind + */ + public function isTokenKindFound($tokenKind): bool + { + return isset($this->foundTokenKinds[$tokenKind]); + } + + /** + * @param int|string $tokenKind + */ + public function countTokenKind($tokenKind): int + { + return $this->foundTokenKinds[$tokenKind] ?? 0; + } + + /** + * Clear tokens in the given range. + */ + public function clearRange(int $indexStart, int $indexEnd): void + { + for ($i = $indexStart; $i <= $indexEnd; ++$i) { + $this->clearAt($i); + } + } + + /** + * Checks for monolithic PHP code. + * + * Checks that the code is pure PHP code, in a single code block, starting + * with an open tag. + */ + public function isMonolithicPhp(): bool + { + if (0 === $this->count()) { + return false; + } + + if ($this->countTokenKind(T_INLINE_HTML) > 1) { + return false; + } + + if (1 === $this->countTokenKind(T_INLINE_HTML)) { + return Preg::match('/^#!.+$/', $this[0]->getContent()); + } + + return 1 === ($this->countTokenKind(T_OPEN_TAG) + $this->countTokenKind(T_OPEN_TAG_WITH_ECHO)); + } + + /** + * @param int $start start index + * @param int $end end index + */ + public function isPartialCodeMultiline(int $start, int $end): bool + { + for ($i = $start; $i <= $end; ++$i) { + if (str_contains($this[$i]->getContent(), "\n")) { + return true; + } + } + + return false; + } + + public function hasAlternativeSyntax(): bool + { + return $this->isAnyTokenKindsFound([ + T_ENDDECLARE, + T_ENDFOR, + T_ENDFOREACH, + T_ENDIF, + T_ENDSWITCH, + T_ENDWHILE, + ]); + } + + public function clearTokenAndMergeSurroundingWhitespace(int $index): void + { + $count = \count($this); + $this->clearAt($index); + + if ($index === $count - 1) { + return; + } + + $nextIndex = $this->getNonEmptySibling($index, 1); + + if (null === $nextIndex || !$this[$nextIndex]->isWhitespace()) { + return; + } + + $prevIndex = $this->getNonEmptySibling($index, -1); + + if ($this[$prevIndex]->isWhitespace()) { + $this[$prevIndex] = new Token([T_WHITESPACE, $this[$prevIndex]->getContent().$this[$nextIndex]->getContent()]); + } elseif ($this->isEmptyAt($prevIndex + 1)) { + $this[$prevIndex + 1] = new Token([T_WHITESPACE, $this[$nextIndex]->getContent()]); + } + + $this->clearAt($nextIndex); + } + + /** + * @internal This is performance-related workaround for lack of proper DI, may be removed at some point + * + * @return list + */ + public function getNamespaceDeclarations(): array + { + if (null === $this->namespaceDeclarations) { + $this->namespaceDeclarations = (new NamespacesAnalyzer())->getDeclarations($this); + } + + return $this->namespaceDeclarations; + } + + /** + * @internal + */ + protected function applyTransformers(): void + { + $transformers = Transformers::createSingleton(); + $transformers->transform($this); + } + + /** + * @param -1|1 $direction + */ + private function removeWhitespaceSafely(int $index, int $direction, ?string $whitespaces = null): void + { + $whitespaceIndex = $this->getNonEmptySibling($index, $direction); + if (isset($this[$whitespaceIndex]) && $this[$whitespaceIndex]->isWhitespace()) { + $newContent = ''; + $tokenToCheck = $this[$whitespaceIndex]; + + // if the token candidate to remove is preceded by single line comment we do not consider the new line after this comment as part of T_WHITESPACE + if (isset($this[$whitespaceIndex - 1]) && $this[$whitespaceIndex - 1]->isComment() && !str_starts_with($this[$whitespaceIndex - 1]->getContent(), '/*')) { + [, $newContent, $whitespacesToCheck] = Preg::split('/^(\R)/', $this[$whitespaceIndex]->getContent(), -1, PREG_SPLIT_DELIM_CAPTURE); + + if ('' === $whitespacesToCheck) { + return; + } + + $tokenToCheck = new Token([T_WHITESPACE, $whitespacesToCheck]); + } + + if (!$tokenToCheck->isWhitespace($whitespaces)) { + return; + } + + if ('' === $newContent) { + $this->clearAt($whitespaceIndex); + } else { + $this[$whitespaceIndex] = new Token([T_WHITESPACE, $newContent]); + } + } + } + + /** + * @param self::BLOCK_TYPE_* $type type of block + * @param int $searchIndex index of starting brace + * @param bool $findEnd if method should find block's end or start + * + * @return int index of opposite brace + */ + private function findOppositeBlockEdge(int $type, int $searchIndex, bool $findEnd): int + { + $blockEdgeDefinitions = self::getBlockEdgeDefinitions(); + + if (!isset($blockEdgeDefinitions[$type])) { + throw new \InvalidArgumentException(sprintf('Invalid param type: "%s".', $type)); + } + + if ($findEnd && isset($this->blockStartCache[$searchIndex])) { + return $this->blockStartCache[$searchIndex]; + } + + if (!$findEnd && isset($this->blockEndCache[$searchIndex])) { + return $this->blockEndCache[$searchIndex]; + } + + $startEdge = $blockEdgeDefinitions[$type]['start']; + $endEdge = $blockEdgeDefinitions[$type]['end']; + $startIndex = $searchIndex; + $endIndex = $this->count() - 1; + $indexOffset = 1; + + if (!$findEnd) { + [$startEdge, $endEdge] = [$endEdge, $startEdge]; + $indexOffset = -1; + $endIndex = 0; + } + + if (!$this[$startIndex]->equals($startEdge)) { + throw new \InvalidArgumentException(sprintf('Invalid param $startIndex - not a proper block "%s".', $findEnd ? 'start' : 'end')); + } + + $blockLevel = 0; + + for ($index = $startIndex; $index !== $endIndex; $index += $indexOffset) { + $token = $this[$index]; + + if ($token->equals($startEdge)) { + ++$blockLevel; + + continue; + } + + if ($token->equals($endEdge)) { + --$blockLevel; + + if (0 === $blockLevel) { + break; + } + } + } + + if (!$this[$index]->equals($endEdge)) { + throw new \UnexpectedValueException(sprintf('Missing block "%s".', $findEnd ? 'end' : 'start')); + } + + if ($startIndex < $index) { + $this->blockStartCache[$startIndex] = $index; + $this->blockEndCache[$index] = $startIndex; + } else { + $this->blockStartCache[$index] = $startIndex; + $this->blockEndCache[$startIndex] = $index; + } + + return $index; + } + + /** + * Calculate hash for code. + */ + private static function calculateCodeHash(string $code): string + { + return CodeHasher::calculateCodeHash($code); + } + + /** + * Get cache value for given key. + * + * @param string $key item key + */ + private static function getCache(string $key): self + { + if (!self::hasCache($key)) { + throw new \OutOfBoundsException(sprintf('Unknown cache key: "%s".', $key)); + } + + return self::$cache[$key]; + } + + /** + * Check if given key exists in cache. + * + * @param string $key item key + */ + private static function hasCache(string $key): bool + { + return isset(self::$cache[$key]); + } + + /** + * @param string $key item key + * @param Tokens $value item value + */ + private static function setCache(string $key, self $value): void + { + self::$cache[$key] = $value; + } + + /** + * Change code hash. + * + * Remove old cache and set new one. + * + * @param string $codeHash new code hash + */ + private function changeCodeHash(string $codeHash): void + { + if (null !== $this->codeHash) { + self::clearCache($this->codeHash); + } + + $this->codeHash = $codeHash; + self::setCache($this->codeHash, $this); + } + + /** + * Register token as found. + * + * @param array{int}|string|Token $token token prototype + */ + private function registerFoundToken($token): void + { + // inlined extractTokenKind() call on the hot path + $tokenKind = $token instanceof Token + ? ($token->isArray() ? $token->getId() : $token->getContent()) + : (\is_array($token) ? $token[0] : $token); + + $this->foundTokenKinds[$tokenKind] ??= 0; + ++$this->foundTokenKinds[$tokenKind]; + } + + /** + * Unregister token as not found. + * + * @param array{int}|string|Token $token token prototype + */ + private function unregisterFoundToken($token): void + { + // inlined extractTokenKind() call on the hot path + $tokenKind = $token instanceof Token + ? ($token->isArray() ? $token->getId() : $token->getContent()) + : (\is_array($token) ? $token[0] : $token); + + if (1 === $this->foundTokenKinds[$tokenKind]) { + unset($this->foundTokenKinds[$tokenKind]); + } else { + --$this->foundTokenKinds[$tokenKind]; + } + } + + /** + * @param array{int}|string|Token $token token prototype + * + * @return int|string + */ + private function extractTokenKind($token) + { + return $token instanceof Token + ? ($token->isArray() ? $token->getId() : $token->getContent()) + : (\is_array($token) ? $token[0] : $token); + } + + /** + * @param int $index token index + * @param -1|1 $direction + * @param callable(int): bool $filter + */ + private function getTokenNotOfKind(int $index, int $direction, callable $filter): ?int + { + while (true) { + $index += $direction; + + if (!$this->offsetExists($index)) { + return null; + } + + if ($this->isEmptyAt($index) || $filter($index)) { + continue; + } + + return $index; + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TokensAnalyzer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TokensAnalyzer.php new file mode 100644 index 00000000..18ee0407 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TokensAnalyzer.php @@ -0,0 +1,859 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer; + +/** + * Analyzer of Tokens collection. + * + * Its role is to provide the ability to analyze collection. + * + * @author Dariusz Rumiński + * @author Gregor Harlan + * + * @internal + */ +final class TokensAnalyzer +{ + /** + * Tokens collection instance. + */ + private Tokens $tokens; + + private ?GotoLabelAnalyzer $gotoLabelAnalyzer = null; + + public function __construct(Tokens $tokens) + { + $this->tokens = $tokens; + } + + /** + * Get indices of methods and properties in classy code (classes, interfaces and traits). + * + * @return array + */ + public function getClassyElements(): array + { + $elements = []; + + for ($index = 1, $count = \count($this->tokens) - 2; $index < $count; ++$index) { + if ($this->tokens[$index]->isClassy()) { + [$index, $newElements] = $this->findClassyElements($index, $index); + $elements += $newElements; + } + } + + ksort($elements); + + return $elements; + } + + /** + * Get indices of modifiers of a classy code (classes, interfaces and traits). + * + * @return array{ + * final: int|null, + * abstract: int|null, + * readonly: int|null + * } + */ + public function getClassyModifiers(int $index): array + { + if (!$this->tokens[$index]->isClassy()) { + throw new \InvalidArgumentException(sprintf('Not an "classy" at given index %d.', $index)); + } + + $readOnlyPossible = \defined('T_READONLY'); // @TODO: drop condition when PHP 8.2+ is required + $modifiers = ['final' => null, 'abstract' => null, 'readonly' => null]; + + while (true) { + $index = $this->tokens->getPrevMeaningfulToken($index); + + if ($this->tokens[$index]->isGivenKind(T_FINAL)) { + $modifiers['final'] = $index; + } elseif ($this->tokens[$index]->isGivenKind(T_ABSTRACT)) { + $modifiers['abstract'] = $index; + } elseif ($readOnlyPossible && $this->tokens[$index]->isGivenKind(T_READONLY)) { + $modifiers['readonly'] = $index; + } else { // no need to skip attributes as it is not possible on PHP8.2 + break; + } + } + + return $modifiers; + } + + /** + * Get indices of namespace uses. + * + * @param bool $perNamespace Return namespace uses per namespace + * + * @return ($perNamespace is true ? array> : list) + */ + public function getImportUseIndexes(bool $perNamespace = false): array + { + $tokens = $this->tokens; + + $uses = []; + $namespaceIndex = 0; + + for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(T_NAMESPACE)) { + $nextTokenIndex = $tokens->getNextTokenOfKind($index, [';', '{']); + $nextToken = $tokens[$nextTokenIndex]; + + if ($nextToken->equals('{')) { + $index = $nextTokenIndex; + } + + if ($perNamespace) { + ++$namespaceIndex; + } + + continue; + } + + if ($token->isGivenKind(T_USE)) { + $uses[$namespaceIndex][] = $index; + } + } + + if (!$perNamespace && isset($uses[$namespaceIndex])) { + return $uses[$namespaceIndex]; + } + + return $uses; + } + + /** + * Check if there is an array at given index. + */ + public function isArray(int $index): bool + { + return $this->tokens[$index]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]); + } + + /** + * Check if the array at index is multiline. + * + * This only checks the root-level of the array. + */ + public function isArrayMultiLine(int $index): bool + { + if (!$this->isArray($index)) { + throw new \InvalidArgumentException(sprintf('Not an array at given index %d.', $index)); + } + + $tokens = $this->tokens; + + // Skip only when it's an array, for short arrays we need the brace for correct + // level counting + if ($tokens[$index]->isGivenKind(T_ARRAY)) { + $index = $tokens->getNextMeaningfulToken($index); + } + + return $this->isBlockMultiline($tokens, $index); + } + + public function isBlockMultiline(Tokens $tokens, int $index): bool + { + $blockType = Tokens::detectBlockType($tokens[$index]); + + if (null === $blockType || !$blockType['isStart']) { + throw new \InvalidArgumentException(sprintf('Not an block start at given index %d.', $index)); + } + + $endIndex = $tokens->findBlockEnd($blockType['type'], $index); + + for (++$index; $index < $endIndex; ++$index) { + $token = $tokens[$index]; + $blockType = Tokens::detectBlockType($token); + + if (null !== $blockType && $blockType['isStart']) { + $index = $tokens->findBlockEnd($blockType['type'], $index); + + continue; + } + + if ( + $token->isWhitespace() + && !$tokens[$index - 1]->isGivenKind(T_END_HEREDOC) + && str_contains($token->getContent(), "\n") + ) { + return true; + } + } + + return false; + } + + /** + * @param int $index Index of the T_FUNCTION token + * + * @return array{visibility: null|T_PRIVATE|T_PROTECTED|T_PUBLIC, static: bool, abstract: bool, final: bool} + */ + public function getMethodAttributes(int $index): array + { + if (!$this->tokens[$index]->isGivenKind(T_FUNCTION)) { + throw new \LogicException(sprintf('No T_FUNCTION at given index %d, got "%s".', $index, $this->tokens[$index]->getName())); + } + + $attributes = [ + 'visibility' => null, + 'static' => false, + 'abstract' => false, + 'final' => false, + ]; + + for ($i = $index; $i >= 0; --$i) { + $i = $this->tokens->getPrevMeaningfulToken($i); + $token = $this->tokens[$i]; + + if ($token->isGivenKind(T_STATIC)) { + $attributes['static'] = true; + + continue; + } + + if ($token->isGivenKind(T_FINAL)) { + $attributes['final'] = true; + + continue; + } + + if ($token->isGivenKind(T_ABSTRACT)) { + $attributes['abstract'] = true; + + continue; + } + + // visibility + + if ($token->isGivenKind(T_PRIVATE)) { + $attributes['visibility'] = T_PRIVATE; + + continue; + } + + if ($token->isGivenKind(T_PROTECTED)) { + $attributes['visibility'] = T_PROTECTED; + + continue; + } + + if ($token->isGivenKind(T_PUBLIC)) { + $attributes['visibility'] = T_PUBLIC; + + continue; + } + + // found a meaningful token that is not part of + // the function signature; stop looking + break; + } + + return $attributes; + } + + /** + * Check if there is an anonymous class under given index. + */ + public function isAnonymousClass(int $index): bool + { + if (!$this->tokens[$index]->isClassy()) { + throw new \LogicException(sprintf('No classy token at given index %d.', $index)); + } + + if (!$this->tokens[$index]->isGivenKind(T_CLASS)) { + return false; + } + + $index = $this->tokens->getPrevMeaningfulToken($index); + + if (\defined('T_READONLY') && $this->tokens[$index]->isGivenKind(T_READONLY)) { // @TODO: drop condition when PHP 8.1+ is required + $index = $this->tokens->getPrevMeaningfulToken($index); + } + + while ($this->tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $index = $this->tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + $index = $this->tokens->getPrevMeaningfulToken($index); + } + + return $this->tokens[$index]->isGivenKind(T_NEW); + } + + /** + * Check if the function under given index is a lambda. + */ + public function isLambda(int $index): bool + { + if (!$this->tokens[$index]->isGivenKind([T_FUNCTION, T_FN])) { + throw new \LogicException(sprintf('No T_FUNCTION or T_FN at given index %d, got "%s".', $index, $this->tokens[$index]->getName())); + } + + $startParenthesisIndex = $this->tokens->getNextMeaningfulToken($index); + $startParenthesisToken = $this->tokens[$startParenthesisIndex]; + + // skip & for `function & () {}` syntax + if ($startParenthesisToken->isGivenKind(CT::T_RETURN_REF)) { + $startParenthesisIndex = $this->tokens->getNextMeaningfulToken($startParenthesisIndex); + $startParenthesisToken = $this->tokens[$startParenthesisIndex]; + } + + return $startParenthesisToken->equals('('); + } + + public function getLastTokenIndexOfArrowFunction(int $index): int + { + if (!$this->tokens[$index]->isGivenKind(T_FN)) { + throw new \InvalidArgumentException(sprintf('Not an "arrow function" at given index %d.', $index)); + } + + $stopTokens = [')', ']', ',', ';', [T_CLOSE_TAG]]; + $index = $this->tokens->getNextTokenOfKind($index, [[T_DOUBLE_ARROW]]); + + while (true) { + $index = $this->tokens->getNextMeaningfulToken($index); + + if ($this->tokens[$index]->equalsAny($stopTokens)) { + break; + } + + $blockType = Tokens::detectBlockType($this->tokens[$index]); + + if (null === $blockType) { + continue; + } + + if ($blockType['isStart']) { + $index = $this->tokens->findBlockEnd($blockType['type'], $index); + + continue; + } + + break; + } + + return $this->tokens->getPrevMeaningfulToken($index); + } + + /** + * Check if the T_STRING under given index is a constant invocation. + */ + public function isConstantInvocation(int $index): bool + { + if (!$this->tokens[$index]->isGivenKind(T_STRING)) { + throw new \LogicException(sprintf('No T_STRING at given index %d, got "%s".', $index, $this->tokens[$index]->getName())); + } + + $nextIndex = $this->tokens->getNextMeaningfulToken($index); + + if ( + $this->tokens[$nextIndex]->equalsAny(['(', '{']) + || $this->tokens[$nextIndex]->isGivenKind([T_AS, T_DOUBLE_COLON, T_ELLIPSIS, T_NS_SEPARATOR, CT::T_RETURN_REF, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, T_VARIABLE]) + ) { + return false; + } + + $prevIndex = $this->tokens->getPrevMeaningfulToken($index); + + if ($this->tokens[$prevIndex]->isGivenKind([T_AS, T_CLASS, T_CONST, T_DOUBLE_COLON, T_FUNCTION, T_GOTO, CT::T_GROUP_IMPORT_BRACE_OPEN, T_INTERFACE, T_TRAIT, CT::T_TYPE_COLON, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]) || $this->tokens[$prevIndex]->isObjectOperator()) { + return false; + } + + while ($this->tokens[$prevIndex]->isGivenKind([CT::T_NAMESPACE_OPERATOR, T_NS_SEPARATOR, T_STRING])) { + $prevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex); + } + + if ($this->tokens[$prevIndex]->isGivenKind([CT::T_CONST_IMPORT, T_EXTENDS, CT::T_FUNCTION_IMPORT, T_IMPLEMENTS, T_INSTANCEOF, T_INSTEADOF, T_NAMESPACE, T_NEW, CT::T_NULLABLE_TYPE, CT::T_TYPE_COLON, T_USE, CT::T_USE_TRAIT])) { + return false; + } + + // `FOO & $bar` could be: + // - function reference parameter: function baz(Foo & $bar) {} + // - bit operator: $x = FOO & $bar; + if ($this->tokens[$nextIndex]->equals('&') && $this->tokens[$this->tokens->getNextMeaningfulToken($nextIndex)]->isGivenKind(T_VARIABLE)) { + $checkIndex = $this->tokens->getPrevTokenOfKind($prevIndex, [';', '{', '}', [T_FUNCTION], [T_OPEN_TAG], [T_OPEN_TAG_WITH_ECHO]]); + + if ($this->tokens[$checkIndex]->isGivenKind(T_FUNCTION)) { + return false; + } + } + + // check for `extends`/`implements`/`use` list + if ($this->tokens[$prevIndex]->equals(',')) { + $checkIndex = $prevIndex; + + while ($this->tokens[$checkIndex]->equalsAny([',', [T_AS], [CT::T_NAMESPACE_OPERATOR], [T_NS_SEPARATOR], [T_STRING]])) { + $checkIndex = $this->tokens->getPrevMeaningfulToken($checkIndex); + } + + if ($this->tokens[$checkIndex]->isGivenKind([T_EXTENDS, CT::T_GROUP_IMPORT_BRACE_OPEN, T_IMPLEMENTS, T_USE, CT::T_USE_TRAIT])) { + return false; + } + } + + // check for array in double quoted string: `"..$foo[bar].."` + if ($this->tokens[$prevIndex]->equals('[') && $this->tokens[$nextIndex]->equals(']')) { + $checkToken = $this->tokens[$this->tokens->getNextMeaningfulToken($nextIndex)]; + + if ($checkToken->equals('"') || $checkToken->isGivenKind([T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES, T_ENCAPSED_AND_WHITESPACE, T_VARIABLE])) { + return false; + } + } + + // check for attribute: `#[Foo]` + if (AttributeAnalyzer::isAttribute($this->tokens, $index)) { + return false; + } + + // check for goto label + if ($this->tokens[$nextIndex]->equals(':')) { + if (null === $this->gotoLabelAnalyzer) { + $this->gotoLabelAnalyzer = new GotoLabelAnalyzer(); + } + + if ($this->gotoLabelAnalyzer->belongsToGoToLabel($this->tokens, $nextIndex)) { + return false; + } + } + + // check for non-capturing catches + + while ($this->tokens[$prevIndex]->isGivenKind([CT::T_NAMESPACE_OPERATOR, T_NS_SEPARATOR, T_STRING, CT::T_TYPE_ALTERNATION])) { + $prevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex); + } + + if ($this->tokens[$prevIndex]->equals('(')) { + $prevPrevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex); + + if ($this->tokens[$prevPrevIndex]->isGivenKind(T_CATCH)) { + return false; + } + } + + return true; + } + + /** + * Checks if there is a unary successor operator under given index. + */ + public function isUnarySuccessorOperator(int $index): bool + { + static $allowedPrevToken = [ + ']', + [T_STRING], + [T_VARIABLE], + [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], + [CT::T_DYNAMIC_PROP_BRACE_CLOSE], + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + ]; + + $tokens = $this->tokens; + $token = $tokens[$index]; + + if (!$token->isGivenKind([T_INC, T_DEC])) { + return false; + } + + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + + return $prevToken->equalsAny($allowedPrevToken); + } + + /** + * Checks if there is a unary predecessor operator under given index. + */ + public function isUnaryPredecessorOperator(int $index): bool + { + static $potentialSuccessorOperator = [T_INC, T_DEC]; + + static $potentialBinaryOperator = ['+', '-', '&', [CT::T_RETURN_REF]]; + + static $otherOperators; + + if (null === $otherOperators) { + $otherOperators = ['!', '~', '@', [T_ELLIPSIS]]; + } + + static $disallowedPrevTokens; + + if (null === $disallowedPrevTokens) { + $disallowedPrevTokens = [ + ']', + '}', + ')', + '"', + '`', + [CT::T_ARRAY_SQUARE_BRACE_CLOSE], + [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], + [CT::T_DYNAMIC_PROP_BRACE_CLOSE], + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + [T_CLASS_C], + [T_CONSTANT_ENCAPSED_STRING], + [T_DEC], + [T_DIR], + [T_DNUMBER], + [T_FILE], + [T_FUNC_C], + [T_INC], + [T_LINE], + [T_LNUMBER], + [T_METHOD_C], + [T_NS_C], + [T_STRING], + [T_TRAIT_C], + [T_VARIABLE], + ]; + } + + $tokens = $this->tokens; + $token = $tokens[$index]; + + if ($token->isGivenKind($potentialSuccessorOperator)) { + return !$this->isUnarySuccessorOperator($index); + } + + if ($token->equalsAny($otherOperators)) { + return true; + } + + if (!$token->equalsAny($potentialBinaryOperator)) { + return false; + } + + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + + if (!$prevToken->equalsAny($disallowedPrevTokens)) { + return true; + } + + if (!$token->equals('&') || !$prevToken->isGivenKind(T_STRING)) { + return false; + } + + static $searchTokens = [ + ';', + '{', + '}', + [T_FUNCTION], + [T_OPEN_TAG], + [T_OPEN_TAG_WITH_ECHO], + ]; + $prevToken = $tokens[$tokens->getPrevTokenOfKind($index, $searchTokens)]; + + return $prevToken->isGivenKind(T_FUNCTION); + } + + /** + * Checks if there is a binary operator under given index. + */ + public function isBinaryOperator(int $index): bool + { + static $nonArrayOperators = [ + '=' => true, + '*' => true, + '/' => true, + '%' => true, + '<' => true, + '>' => true, + '|' => true, + '^' => true, + '.' => true, + ]; + + static $potentialUnaryNonArrayOperators = [ + '+' => true, + '-' => true, + '&' => true, + ]; + + static $arrayOperators; + + if (null === $arrayOperators) { + $arrayOperators = [ + T_AND_EQUAL => true, // &= + T_BOOLEAN_AND => true, // && + T_BOOLEAN_OR => true, // || + T_CONCAT_EQUAL => true, // .= + T_DIV_EQUAL => true, // /= + T_DOUBLE_ARROW => true, // => + T_IS_EQUAL => true, // == + T_IS_GREATER_OR_EQUAL => true, // >= + T_IS_IDENTICAL => true, // === + T_IS_NOT_EQUAL => true, // !=, <> + T_IS_NOT_IDENTICAL => true, // !== + T_IS_SMALLER_OR_EQUAL => true, // <= + T_LOGICAL_AND => true, // and + T_LOGICAL_OR => true, // or + T_LOGICAL_XOR => true, // xor + T_MINUS_EQUAL => true, // -= + T_MOD_EQUAL => true, // %= + T_MUL_EQUAL => true, // *= + T_OR_EQUAL => true, // |= + T_PLUS_EQUAL => true, // += + T_POW => true, // ** + T_POW_EQUAL => true, // **= + T_SL => true, // << + T_SL_EQUAL => true, // <<= + T_SR => true, // >> + T_SR_EQUAL => true, // >>= + T_XOR_EQUAL => true, // ^= + T_SPACESHIP => true, // <=> + T_COALESCE => true, // ?? + T_COALESCE_EQUAL => true, // ??= + ]; + } + + $tokens = $this->tokens; + $token = $tokens[$index]; + + if ($token->isGivenKind([T_INLINE_HTML, T_ENCAPSED_AND_WHITESPACE, CT::T_TYPE_INTERSECTION])) { + return false; + } + + if (isset($potentialUnaryNonArrayOperators[$token->getContent()])) { + return !$this->isUnaryPredecessorOperator($index); + } + + if ($token->isArray()) { + return isset($arrayOperators[$token->getId()]); + } + + if (isset($nonArrayOperators[$token->getContent()])) { + return true; + } + + return false; + } + + /** + * Check if `T_WHILE` token at given index is `do { ... } while ();` syntax + * and not `while () { ...}`. + */ + public function isWhilePartOfDoWhile(int $index): bool + { + $tokens = $this->tokens; + $token = $tokens[$index]; + + if (!$token->isGivenKind(T_WHILE)) { + throw new \LogicException(sprintf('No T_WHILE at given index %d, got "%s".', $index, $token->getName())); + } + + $endIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$endIndex]->equals('}')) { + return false; + } + + $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $endIndex); + $beforeStartIndex = $tokens->getPrevMeaningfulToken($startIndex); + + return $tokens[$beforeStartIndex]->isGivenKind(T_DO); + } + + /** + * @throws \LogicException when provided index does not point to token containing T_CASE + */ + public function isEnumCase(int $caseIndex): bool + { + $tokens = $this->tokens; + $token = $tokens[$caseIndex]; + + if (!$token->isGivenKind(T_CASE)) { + throw new \LogicException(sprintf( + 'No T_CASE given at index %d, got %s instead.', + $caseIndex, + $token->getName() ?? $token->getContent() + )); + } + + if (!\defined('T_ENUM') || !$tokens->isTokenKindFound(T_ENUM)) { + return false; + } + + $prevIndex = $tokens->getPrevTokenOfKind($caseIndex, [[T_ENUM], [T_SWITCH]]); + + return null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(T_ENUM); + } + + public function isSuperGlobal(int $index): bool + { + static $superNames = [ + '$_COOKIE' => true, + '$_ENV' => true, + '$_FILES' => true, + '$_GET' => true, + '$_POST' => true, + '$_REQUEST' => true, + '$_SERVER' => true, + '$_SESSION' => true, + '$GLOBALS' => true, + ]; + + $token = $this->tokens[$index]; + + if (!$token->isGivenKind(T_VARIABLE)) { + return false; + } + + return isset($superNames[strtoupper($token->getContent())]); + } + + /** + * Find classy elements. + * + * Searches in tokens from the classy (start) index till the end (index) of the classy. + * Returns an array; first value is the index until the method has analysed (int), second the found classy elements (array). + * + * @param int $classIndex classy index + * + * @return array{int, array} + */ + private function findClassyElements(int $classIndex, int $index): array + { + $elements = []; + $curlyBracesLevel = 0; + $bracesLevel = 0; + ++$index; // skip the classy index itself + + for ($count = \count($this->tokens); $index < $count; ++$index) { + $token = $this->tokens[$index]; + + if ($token->isGivenKind(T_ENCAPSED_AND_WHITESPACE)) { + continue; + } + + if ($token->isGivenKind(T_CLASS)) { // anonymous class in class + // check for nested anonymous classes inside the new call of an anonymous class, + // for example `new class(function (){new class(function (){new class(function (){}){};}){};}){};` etc. + // if class(XYZ) {} skip till `(` as XYZ might contain functions etc. + + $nestedClassIndex = $index; + $index = $this->tokens->getNextMeaningfulToken($index); + + if ($this->tokens[$index]->equals('(')) { + ++$index; // move after `(` + + for ($nestedBracesLevel = 1; $index < $count; ++$index) { + $token = $this->tokens[$index]; + + if ($token->equals('(')) { + ++$nestedBracesLevel; + + continue; + } + + if ($token->equals(')')) { + --$nestedBracesLevel; + + if (0 === $nestedBracesLevel) { + [$index, $newElements] = $this->findClassyElements($nestedClassIndex, $index); + $elements += $newElements; + + break; + } + + continue; + } + + if ($token->isGivenKind(T_CLASS)) { // anonymous class in class + [$index, $newElements] = $this->findClassyElements($index, $index); + $elements += $newElements; + } + } + } else { + [$index, $newElements] = $this->findClassyElements($nestedClassIndex, $nestedClassIndex); + $elements += $newElements; + } + + continue; + } + + if ($token->equals('(')) { + ++$bracesLevel; + + continue; + } + + if ($token->equals(')')) { + --$bracesLevel; + + continue; + } + + if ($token->equals('{')) { + ++$curlyBracesLevel; + + continue; + } + + if ($token->equals('}')) { + --$curlyBracesLevel; + + if (0 === $curlyBracesLevel) { + break; + } + + continue; + } + + if (1 !== $curlyBracesLevel || !$token->isArray()) { + continue; + } + + if (0 === $bracesLevel && $token->isGivenKind(T_VARIABLE)) { + $elements[$index] = [ + 'classIndex' => $classIndex, + 'token' => $token, + 'type' => 'property', + ]; + + continue; + } + + if ($token->isGivenKind(T_FUNCTION)) { + $elements[$index] = [ + 'classIndex' => $classIndex, + 'token' => $token, + 'type' => 'method', + ]; + } elseif ($token->isGivenKind(T_CONST)) { + $elements[$index] = [ + 'classIndex' => $classIndex, + 'token' => $token, + 'type' => 'const', + ]; + } elseif ($token->isGivenKind(CT::T_USE_TRAIT)) { + $elements[$index] = [ + 'classIndex' => $classIndex, + 'token' => $token, + 'type' => 'trait_import', + ]; + } elseif ($token->isGivenKind(T_CASE)) { + $elements[$index] = [ + 'classIndex' => $classIndex, + 'token' => $token, + 'type' => 'case', + ]; + } + } + + return [$index, $elements]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ArrayTypehintTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ArrayTypehintTransformer.php new file mode 100644 index 00000000..8e5b9bf1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ArrayTypehintTransformer.php @@ -0,0 +1,54 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `array` typehint from T_ARRAY into CT::T_ARRAY_TYPEHINT. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class ArrayTypehintTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 5_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$token->isGivenKind(T_ARRAY)) { + return; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + $nextToken = $tokens[$nextIndex]; + + if (!$nextToken->equals('(')) { + $tokens[$index] = new Token([CT::T_ARRAY_TYPEHINT, $token->getContent()]); + } + } + + public function getCustomTokens(): array + { + return [CT::T_ARRAY_TYPEHINT]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/AttributeTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/AttributeTransformer.php new file mode 100644 index 00000000..d19d3b88 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/AttributeTransformer.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transforms attribute related Tokens. + * + * @internal + */ +final class AttributeTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // must run before all other transformers that might touch attributes + return 200; + } + + public function getRequiredPhpVersionId(): int + { + return 8_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$tokens[$index]->isGivenKind(T_ATTRIBUTE)) { + return; + } + + $level = 1; + + do { + ++$index; + + if ($tokens[$index]->equals('[')) { + ++$level; + } elseif ($tokens[$index]->equals(']')) { + --$level; + } + } while (0 < $level); + + $tokens[$index] = new Token([CT::T_ATTRIBUTE_CLOSE, ']']); + } + + public function getCustomTokens(): array + { + return [ + CT::T_ATTRIBUTE_CLOSE, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php new file mode 100644 index 00000000..1a690b89 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php @@ -0,0 +1,80 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform braced class instantiation braces in `(new Foo())` into CT::T_BRACE_CLASS_INSTANTIATION_OPEN + * and CT::T_BRACE_CLASS_INSTANTIATION_CLOSE. + * + * @author Sebastiaans Stok + * + * @internal + */ +final class BraceClassInstantiationTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // must run after CurlyBraceTransformer and SquareBraceTransformer + return -2; + } + + public function getRequiredPhpVersionId(): int + { + return 5_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$tokens[$index]->equals('(') || !$tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(T_NEW)) { + return; + } + + if ($tokens[$tokens->getPrevMeaningfulToken($index)]->equalsAny([ + ')', + ']', + [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], + [CT::T_ARRAY_SQUARE_BRACE_CLOSE], + [CT::T_BRACE_CLASS_INSTANTIATION_CLOSE], + [T_ARRAY], + [T_CLASS], + [T_ELSEIF], + [T_FOR], + [T_FOREACH], + [T_IF], + [T_STATIC], + [T_STRING], + [T_SWITCH], + [T_VARIABLE], + [T_WHILE], + ])) { + return; + } + + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + + $tokens[$index] = new Token([CT::T_BRACE_CLASS_INSTANTIATION_OPEN, '(']); + $tokens[$closeIndex] = new Token([CT::T_BRACE_CLASS_INSTANTIATION_CLOSE, ')']); + } + + public function getCustomTokens(): array + { + return [CT::T_BRACE_CLASS_INSTANTIATION_OPEN, CT::T_BRACE_CLASS_INSTANTIATION_CLOSE]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceTransformer.php new file mode 100644 index 00000000..e4f374ad --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceTransformer.php @@ -0,0 +1,286 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform discriminate overloaded curly braces tokens. + * + * Performed transformations: + * - closing `}` for T_CURLY_OPEN into CT::T_CURLY_CLOSE, + * - closing `}` for T_DOLLAR_OPEN_CURLY_BRACES into CT::T_DOLLAR_CLOSE_CURLY_BRACES, + * - in `$foo->{$bar}` into CT::T_DYNAMIC_PROP_BRACE_OPEN and CT::T_DYNAMIC_PROP_BRACE_CLOSE, + * - in `${$foo}` into CT::T_DYNAMIC_VAR_BRACE_OPEN and CT::T_DYNAMIC_VAR_BRACE_CLOSE, + * - in `$array{$index}` into CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN and CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE, + * - in `use some\a\{ClassA, ClassB, ClassC as C}` into CT::T_GROUP_IMPORT_BRACE_OPEN, CT::T_GROUP_IMPORT_BRACE_CLOSE. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class BraceTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 5_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + $this->transformIntoCurlyCloseBrace($tokens, $token, $index); + $this->transformIntoDollarCloseBrace($tokens, $token, $index); + $this->transformIntoDynamicPropBraces($tokens, $token, $index); + $this->transformIntoDynamicVarBraces($tokens, $token, $index); + $this->transformIntoCurlyIndexBraces($tokens, $token, $index); + $this->transformIntoGroupUseBraces($tokens, $token, $index); + $this->transformIntoDynamicClassConstantFetchBraces($tokens, $token, $index); + } + + public function getCustomTokens(): array + { + return [ + CT::T_CURLY_CLOSE, + CT::T_DOLLAR_CLOSE_CURLY_BRACES, + CT::T_DYNAMIC_PROP_BRACE_OPEN, + CT::T_DYNAMIC_PROP_BRACE_CLOSE, + CT::T_DYNAMIC_VAR_BRACE_OPEN, + CT::T_DYNAMIC_VAR_BRACE_CLOSE, + CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, + CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE, + CT::T_GROUP_IMPORT_BRACE_OPEN, + CT::T_GROUP_IMPORT_BRACE_CLOSE, + CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_OPEN, + CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_CLOSE, + ]; + } + + /** + * Transform closing `}` for T_CURLY_OPEN into CT::T_CURLY_CLOSE. + * + * This should be done at very beginning of curly braces transformations. + */ + private function transformIntoCurlyCloseBrace(Tokens $tokens, Token $token, int $index): void + { + if (!$token->isGivenKind(T_CURLY_OPEN)) { + return; + } + + $level = 1; + + do { + ++$index; + + if ($tokens[$index]->equals('{') || $tokens[$index]->isGivenKind(T_CURLY_OPEN)) { // we count all kind of { + ++$level; + } elseif ($tokens[$index]->equals('}')) { // we count all kind of } + --$level; + } + } while (0 < $level); + + $tokens[$index] = new Token([CT::T_CURLY_CLOSE, '}']); + } + + private function transformIntoDollarCloseBrace(Tokens $tokens, Token $token, int $index): void + { + if ($token->isGivenKind(T_DOLLAR_OPEN_CURLY_BRACES)) { + $nextIndex = $tokens->getNextTokenOfKind($index, ['}']); + $tokens[$nextIndex] = new Token([CT::T_DOLLAR_CLOSE_CURLY_BRACES, '}']); + } + } + + private function transformIntoDynamicPropBraces(Tokens $tokens, Token $token, int $index): void + { + if (!$token->isObjectOperator()) { + return; + } + + if (!$tokens[$index + 1]->equals('{')) { + return; + } + + $openIndex = $index + 1; + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $openIndex); + + $tokens[$openIndex] = new Token([CT::T_DYNAMIC_PROP_BRACE_OPEN, '{']); + $tokens[$closeIndex] = new Token([CT::T_DYNAMIC_PROP_BRACE_CLOSE, '}']); + } + + private function transformIntoDynamicVarBraces(Tokens $tokens, Token $token, int $index): void + { + if (!$token->equals('$')) { + return; + } + + $openIndex = $tokens->getNextMeaningfulToken($index); + + if (null === $openIndex) { + return; + } + + $openToken = $tokens[$openIndex]; + + if (!$openToken->equals('{')) { + return; + } + + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $openIndex); + + $tokens[$openIndex] = new Token([CT::T_DYNAMIC_VAR_BRACE_OPEN, '{']); + $tokens[$closeIndex] = new Token([CT::T_DYNAMIC_VAR_BRACE_CLOSE, '}']); + } + + private function transformIntoCurlyIndexBraces(Tokens $tokens, Token $token, int $index): void + { + if (!$token->equals('{')) { + return; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$prevIndex]->equalsAny([ + [T_STRING], + [T_VARIABLE], + [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], + ']', + ')', + ])) { + return; + } + + if ( + $tokens[$prevIndex]->isGivenKind(T_STRING) + && !$tokens[$tokens->getPrevMeaningfulToken($prevIndex)]->isObjectOperator() + ) { + return; + } + + if ( + $tokens[$prevIndex]->equals(')') + && !$tokens[$tokens->getPrevMeaningfulToken( + $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $prevIndex) + )]->isGivenKind(T_ARRAY) + ) { + return; + } + + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $index); + + $tokens[$index] = new Token([CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{']); + $tokens[$closeIndex] = new Token([CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE, '}']); + } + + private function transformIntoGroupUseBraces(Tokens $tokens, Token $token, int $index): void + { + if (!$token->equals('{')) { + return; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { + return; + } + + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $index); + + $tokens[$index] = new Token([CT::T_GROUP_IMPORT_BRACE_OPEN, '{']); + $tokens[$closeIndex] = new Token([CT::T_GROUP_IMPORT_BRACE_CLOSE, '}']); + } + + private function transformIntoDynamicClassConstantFetchBraces(Tokens $tokens, Token $token, int $index): void + { + if (\PHP_VERSION_ID < 8_03_00) { + return; // @TODO: drop condition when PHP 8.3+ is required or majority of the users are using 8.3+ + } + + if (!$token->equals('{')) { + return; + } + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); + + while (!$tokens[$prevMeaningfulTokenIndex]->isGivenKind(T_DOUBLE_COLON)) { + if (!$tokens[$prevMeaningfulTokenIndex]->equals(')')) { + return; + } + + $prevMeaningfulTokenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $prevMeaningfulTokenIndex); + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulTokenIndex); + + if (!$tokens[$prevMeaningfulTokenIndex]->equals('}')) { + return; + } + + $prevMeaningfulTokenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $prevMeaningfulTokenIndex); + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulTokenIndex); + } + + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $index); + $nextMeaningfulTokenIndexAfterCloseIndex = $tokens->getNextMeaningfulToken($closeIndex); + + if (!$tokens[$nextMeaningfulTokenIndexAfterCloseIndex]->equalsAny([';', [T_CLOSE_TAG], [T_DOUBLE_COLON]])) { + return; + } + + $tokens[$index] = new Token([CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_OPEN, '{']); + $tokens[$closeIndex] = new Token([CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_CLOSE, '}']); + } + + /** + * We do not want to rely on `$tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index)` here, + * as it relies on block types that are assuming that `}` tokens are already transformed to Custom Tokens that are allowing to distinguish different block types. + * As we are just about to transform `{` and `}` into Custom Tokens by this transformer, thus we need to compare those tokens manually by content without using `Tokens::findBlockEnd`. + */ + private function naivelyFindCurlyBlockEnd(Tokens $tokens, int $startIndex): int + { + if (!$tokens->offsetExists($startIndex)) { + throw new \OutOfBoundsException(sprintf('Unavailable index: "%s".', $startIndex)); + } + + if ('{' !== $tokens[$startIndex]->getContent()) { + throw new \InvalidArgumentException(sprintf('Wrong start index: "%s".', $startIndex)); + } + + $blockLevel = 1; + $endIndex = $tokens->count() - 1; + for ($index = $startIndex + 1; $index !== $endIndex; ++$index) { + $token = $tokens[$index]; + + if ('{' === $token->getContent()) { + ++$blockLevel; + + continue; + } + + if ('}' === $token->getContent()) { + --$blockLevel; + + if (0 === $blockLevel) { + if (!$token->equals('}')) { + throw new \UnexpectedValueException(sprintf('Detected block end for index: "%s" was already transformed into other token type: "%s".', $startIndex, $token->getName())); + } + + return $index; + } + } + } + + throw new \UnexpectedValueException(sprintf('Missing block end for index: "%s".', $startIndex)); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ClassConstantTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ClassConstantTransformer.php new file mode 100644 index 00000000..bb75b727 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ClassConstantTransformer.php @@ -0,0 +1,57 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `class` class' constant from T_CLASS into CT::T_CLASS_CONSTANT. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class ClassConstantTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 5_05_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$token->equalsAny([ + [T_CLASS, 'class'], + [T_STRING, 'class'], + ], false)) { + return; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $prevToken = $tokens[$prevIndex]; + + if ($prevToken->isGivenKind(T_DOUBLE_COLON)) { + $tokens[$index] = new Token([CT::T_CLASS_CONSTANT, $token->getContent()]); + } + } + + public function getCustomTokens(): array + { + return [CT::T_CLASS_CONSTANT]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ConstructorPromotionTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ConstructorPromotionTransformer.php new file mode 100644 index 00000000..cdb282d3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ConstructorPromotionTransformer.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transforms for Constructor Property Promotion. + * + * Transform T_PUBLIC, T_PROTECTED and T_PRIVATE of Constructor Property Promotion into custom tokens. + * + * @internal + */ +final class ConstructorPromotionTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 8_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$tokens[$index]->isGivenKind(T_FUNCTION)) { + return; + } + + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$functionNameIndex]->isGivenKind(T_STRING) || '__construct' !== strtolower($tokens[$functionNameIndex]->getContent())) { + return; + } + + /** @var int $openParenthesisIndex */ + $openParenthesisIndex = $tokens->getNextMeaningfulToken($functionNameIndex); // we are @ '(' now + $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesisIndex); + + for ($argsIndex = $openParenthesisIndex; $argsIndex < $closeParenthesisIndex; ++$argsIndex) { + if ($tokens[$argsIndex]->isGivenKind(T_PUBLIC)) { + $tokens[$argsIndex] = new Token([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, $tokens[$argsIndex]->getContent()]); + } elseif ($tokens[$argsIndex]->isGivenKind(T_PROTECTED)) { + $tokens[$argsIndex] = new Token([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, $tokens[$argsIndex]->getContent()]); + } elseif ($tokens[$argsIndex]->isGivenKind(T_PRIVATE)) { + $tokens[$argsIndex] = new Token([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, $tokens[$argsIndex]->getContent()]); + } + } + } + + public function getCustomTokens(): array + { + return [ + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformer.php new file mode 100644 index 00000000..21d062b0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformer.php @@ -0,0 +1,65 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform DNF parentheses into CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN and CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE. + * + * @see https://wiki.php.net/rfc/dnf_types + * + * @internal + */ +final class DisjunctiveNormalFormTypeParenthesisTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // needs to run after TypeAlternationTransformer + return -16; + } + + public function getRequiredPhpVersionId(): int + { + return 8_02_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if ($token->equals('(') && $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(CT::T_TYPE_ALTERNATION)) { + $openIndex = $index; + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + } elseif ($token->equals(')') && $tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(CT::T_TYPE_ALTERNATION)) { + $openIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $closeIndex = $index; + } else { + return; + } + + $tokens[$openIndex] = new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '(']); + $tokens[$closeIndex] = new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')']); + } + + public function getCustomTokens(): array + { + return [ + CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, + CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/FirstClassCallableTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/FirstClassCallableTransformer.php new file mode 100644 index 00000000..4781e7b8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/FirstClassCallableTransformer.php @@ -0,0 +1,49 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + */ +final class FirstClassCallableTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 8_01_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if ( + $token->isGivenKind(T_ELLIPSIS) + && $tokens[$tokens->getPrevMeaningfulToken($index)]->equals('(') + && $tokens[$tokens->getNextMeaningfulToken($index)]->equals(')') + ) { + $tokens[$index] = new Token([CT::T_FIRST_CLASS_CALLABLE, '...']); + } + } + + public function getCustomTokens(): array + { + return [ + CT::T_FIRST_CLASS_CALLABLE, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ImportTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ImportTransformer.php new file mode 100644 index 00000000..1a5b0107 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ImportTransformer.php @@ -0,0 +1,72 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform const/function import tokens. + * + * Performed transformations: + * - T_CONST into CT::T_CONST_IMPORT + * - T_FUNCTION into CT::T_FUNCTION_IMPORT + * + * @author Gregor Harlan + * + * @internal + */ +final class ImportTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // Should run after CurlyBraceTransformer and ReturnRefTransformer + return -1; + } + + public function getRequiredPhpVersionId(): int + { + return 5_06_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$token->isGivenKind([T_CONST, T_FUNCTION])) { + return; + } + + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + + if (!$prevToken->isGivenKind(T_USE)) { + $nextToken = $tokens[$tokens->getNextTokenOfKind($index, ['=', '(', [CT::T_RETURN_REF], [CT::T_GROUP_IMPORT_BRACE_CLOSE]])]; + + if (!$nextToken->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) { + return; + } + } + + $tokens[$index] = new Token([ + $token->isGivenKind(T_FUNCTION) ? CT::T_FUNCTION_IMPORT : CT::T_CONST_IMPORT, + $token->getContent(), + ]); + } + + public function getCustomTokens(): array + { + return [CT::T_CONST_IMPORT, CT::T_FUNCTION_IMPORT]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NameQualifiedTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NameQualifiedTransformer.php new file mode 100644 index 00000000..b0521954 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NameQualifiedTransformer.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED and T_NAME_RELATIVE into T_NAMESPACE T_NS_SEPARATOR T_STRING. + * + * @internal + */ +final class NameQualifiedTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + return 1; // must run before NamespaceOperatorTransformer + } + + public function getRequiredPhpVersionId(): int + { + return 8_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if ($token->isGivenKind([T_NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED])) { + $this->transformQualified($tokens, $token, $index); + } elseif ($token->isGivenKind(T_NAME_RELATIVE)) { + $this->transformRelative($tokens, $token, $index); + } + } + + public function getCustomTokens(): array + { + return []; + } + + private function transformQualified(Tokens $tokens, Token $token, int $index): void + { + $parts = explode('\\', $token->getContent()); + $newTokens = []; + + if ('' === $parts[0]) { + $newTokens[] = new Token([T_NS_SEPARATOR, '\\']); + array_shift($parts); + } + + foreach ($parts as $part) { + $newTokens[] = new Token([T_STRING, $part]); + $newTokens[] = new Token([T_NS_SEPARATOR, '\\']); + } + + array_pop($newTokens); + + $tokens->overrideRange($index, $index, $newTokens); + } + + private function transformRelative(Tokens $tokens, Token $token, int $index): void + { + $parts = explode('\\', $token->getContent()); + $newTokens = [ + new Token([T_NAMESPACE, array_shift($parts)]), + new Token([T_NS_SEPARATOR, '\\']), + ]; + + foreach ($parts as $part) { + $newTokens[] = new Token([T_STRING, $part]); + $newTokens[] = new Token([T_NS_SEPARATOR, '\\']); + } + + array_pop($newTokens); + + $tokens->overrideRange($index, $index, $newTokens); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamedArgumentTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamedArgumentTransformer.php new file mode 100644 index 00000000..0f64717b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamedArgumentTransformer.php @@ -0,0 +1,73 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform named argument tokens. + * + * @internal + */ +final class NamedArgumentTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // needs to run after TypeColonTransformer + return -15; + } + + public function getRequiredPhpVersionId(): int + { + return 8_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$tokens[$index]->equals(':')) { + return; + } + + $stringIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$stringIndex]->isGivenKind(T_STRING)) { + return; + } + + $preStringIndex = $tokens->getPrevMeaningfulToken($stringIndex); + + // if equals any [';', '{', '}', [T_OPEN_TAG]] than it is a goto label + // if equals ')' than likely it is a type colon, but sure not a name argument + // if equals '?' than it is part of ternary statement + + if (!$tokens[$preStringIndex]->equalsAny([',', '('])) { + return; + } + + $tokens[$stringIndex] = new Token([CT::T_NAMED_ARGUMENT_NAME, $tokens[$stringIndex]->getContent()]); + $tokens[$index] = new Token([CT::T_NAMED_ARGUMENT_COLON, ':']); + } + + public function getCustomTokens(): array + { + return [ + CT::T_NAMED_ARGUMENT_COLON, + CT::T_NAMED_ARGUMENT_NAME, + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamespaceOperatorTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamespaceOperatorTransformer.php new file mode 100644 index 00000000..5244481a --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamespaceOperatorTransformer.php @@ -0,0 +1,53 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `namespace` operator from T_NAMESPACE into CT::T_NAMESPACE_OPERATOR. + * + * @author Gregor Harlan + * + * @internal + */ +final class NamespaceOperatorTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 5_03_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$token->isGivenKind(T_NAMESPACE)) { + return; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$nextIndex]->isGivenKind(T_NS_SEPARATOR)) { + $tokens[$index] = new Token([CT::T_NAMESPACE_OPERATOR, $token->getContent()]); + } + } + + public function getCustomTokens(): array + { + return [CT::T_NAMESPACE_OPERATOR]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NullableTypeTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NullableTypeTransformer.php new file mode 100644 index 00000000..07f481f4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NullableTypeTransformer.php @@ -0,0 +1,83 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `?` operator into CT::T_NULLABLE_TYPE in `function foo(?Bar $b) {}`. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class NullableTypeTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // needs to run after TypeColonTransformer + return -20; + } + + public function getRequiredPhpVersionId(): int + { + return 7_01_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$token->equals('?')) { + return; + } + + static $types; + + if (null === $types) { + $types = [ + '(', + ',', + [CT::T_TYPE_COLON], + [CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC], + [CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED], + [CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE], + [CT::T_ATTRIBUTE_CLOSE], + [T_PRIVATE], + [T_PROTECTED], + [T_PUBLIC], + [T_VAR], + [T_STATIC], + [T_CONST], + ]; + + if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required + $types[] = [T_READONLY]; + } + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prevIndex]->equalsAny($types)) { + $tokens[$index] = new Token([CT::T_NULLABLE_TYPE, '?']); + } + } + + public function getCustomTokens(): array + { + return [CT::T_NULLABLE_TYPE]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ReturnRefTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ReturnRefTransformer.php new file mode 100644 index 00000000..13f26d05 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ReturnRefTransformer.php @@ -0,0 +1,47 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `&` operator into CT::T_RETURN_REF in `function & foo() {}`. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class ReturnRefTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 5_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if ($token->equals('&') && $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind([T_FUNCTION, T_FN])) { + $tokens[$index] = new Token([CT::T_RETURN_REF, '&']); + } + } + + public function getCustomTokens(): array + { + return [CT::T_RETURN_REF]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/SquareBraceTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/SquareBraceTransformer.php new file mode 100644 index 00000000..46e5b12d --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/SquareBraceTransformer.php @@ -0,0 +1,187 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform discriminate overloaded square braces tokens. + * + * Performed transformations: + * - in `[1, 2, 3]` into CT::T_ARRAY_SQUARE_BRACE_OPEN and CT::T_ARRAY_SQUARE_BRACE_CLOSE, + * - in `[$a, &$b, [$c]] = array(1, 2, array(3))` into CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN and CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class SquareBraceTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // must run after CurlyBraceTransformer and AttributeTransformer + return -1; + } + + public function getRequiredPhpVersionId(): int + { + // Short array syntax was introduced in PHP 5.4, but the fixer is smart + // enough to handle it even before 5.4. + // Same for array destructing syntax sugar `[` introduced in PHP 7.1. + return 5_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if ($this->isArrayDestructing($tokens, $index)) { + $this->transformIntoDestructuringSquareBrace($tokens, $index); + + return; + } + + if ($this->isShortArray($tokens, $index)) { + $this->transformIntoArraySquareBrace($tokens, $index); + } + } + + public function getCustomTokens(): array + { + return [ + CT::T_ARRAY_SQUARE_BRACE_OPEN, + CT::T_ARRAY_SQUARE_BRACE_CLOSE, + CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, + CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, + ]; + } + + private function transformIntoArraySquareBrace(Tokens $tokens, int $index): void + { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index); + + $tokens[$index] = new Token([CT::T_ARRAY_SQUARE_BRACE_OPEN, '[']); + $tokens[$endIndex] = new Token([CT::T_ARRAY_SQUARE_BRACE_CLOSE, ']']); + } + + private function transformIntoDestructuringSquareBrace(Tokens $tokens, int $index): void + { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index); + + $tokens[$index] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, '[']); + $tokens[$endIndex] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ']']); + + $previousMeaningfulIndex = $index; + $index = $tokens->getNextMeaningfulToken($index); + + while ($index < $endIndex) { + if ($tokens[$index]->equals('[') && $tokens[$previousMeaningfulIndex]->equalsAny([[CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN], ','])) { + $tokens[$tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index)] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ']']); + $tokens[$index] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, '[']); + } + + $previousMeaningfulIndex = $index; + $index = $tokens->getNextMeaningfulToken($index); + } + } + + /** + * Check if token under given index is short array opening. + */ + private function isShortArray(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->equals('[')) { + return false; + } + + static $disallowedPrevTokens = [ + ')', + ']', + '}', + '"', + [T_CONSTANT_ENCAPSED_STRING], + [T_STRING], + [T_STRING_VARNAME], + [T_VARIABLE], + [CT::T_ARRAY_SQUARE_BRACE_CLOSE], + [CT::T_DYNAMIC_PROP_BRACE_CLOSE], + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], + ]; + + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + if ($prevToken->equalsAny($disallowedPrevTokens)) { + return false; + } + + $nextToken = $tokens[$tokens->getNextMeaningfulToken($index)]; + if ($nextToken->equals(']')) { + return true; + } + + return !$this->isArrayDestructing($tokens, $index); + } + + private function isArrayDestructing(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->equals('[')) { + return false; + } + + static $disallowedPrevTokens = [ + ')', + ']', + '"', + [T_CONSTANT_ENCAPSED_STRING], + [T_STRING], + [T_STRING_VARNAME], + [T_VARIABLE], + [CT::T_ARRAY_SQUARE_BRACE_CLOSE], + [CT::T_DYNAMIC_PROP_BRACE_CLOSE], + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], + ]; + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $prevToken = $tokens[$prevIndex]; + if ($prevToken->equalsAny($disallowedPrevTokens)) { + return false; + } + + if ($prevToken->isGivenKind(T_AS)) { + return true; + } + + if ($prevToken->isGivenKind(T_DOUBLE_ARROW)) { + $variableIndex = $tokens->getPrevMeaningfulToken($prevIndex); + if (!$tokens[$variableIndex]->isGivenKind(T_VARIABLE)) { + return false; + } + + $prevVariableIndex = $tokens->getPrevMeaningfulToken($variableIndex); + if ($tokens[$prevVariableIndex]->isGivenKind(T_AS)) { + return true; + } + } + + $type = Tokens::detectBlockType($tokens[$index]); + $end = $tokens->findBlockEnd($type['type'], $index); + + $nextToken = $tokens[$tokens->getNextMeaningfulToken($end)]; + + return $nextToken->equals('='); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeAlternationTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeAlternationTransformer.php new file mode 100644 index 00000000..91035f90 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeAlternationTransformer.php @@ -0,0 +1,57 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTypeTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `|` operator into CT::T_TYPE_ALTERNATION in `function foo(Type1 | Type2 $x) {` + * or `} catch (ExceptionType1 | ExceptionType2 $e) {`. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class TypeAlternationTransformer extends AbstractTypeTransformer +{ + public function getPriority(): int + { + // needs to run after ArrayTypehintTransformer, TypeColonTransformer and AttributeTransformer + return -15; + } + + public function getRequiredPhpVersionId(): int + { + return 7_01_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + $this->doProcess($tokens, $index, '|'); + } + + public function getCustomTokens(): array + { + return [CT::T_TYPE_ALTERNATION]; + } + + protected function replaceToken(Tokens $tokens, int $index): void + { + $tokens[$index] = new Token([CT::T_TYPE_ALTERNATION, '|']); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeColonTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeColonTransformer.php new file mode 100644 index 00000000..7fed9de2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeColonTransformer.php @@ -0,0 +1,83 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `:` operator into CT::T_TYPE_COLON in `function foo() : int {}`. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class TypeColonTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // needs to run after ReturnRefTransformer and UseTransformer + // and before TypeAlternationTransformer + return -10; + } + + public function getRequiredPhpVersionId(): int + { + return 7_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$token->equals(':')) { + return; + } + + $endIndex = $tokens->getPrevMeaningfulToken($index); + + if ( + \defined('T_ENUM') // @TODO: drop condition when PHP 8.1+ is required + && $tokens[$tokens->getPrevMeaningfulToken($endIndex)]->isGivenKind(T_ENUM) + ) { + $tokens[$index] = new Token([CT::T_TYPE_COLON, ':']); + + return; + } + + if (!$tokens[$endIndex]->equals(')')) { + return; + } + + $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endIndex); + $prevIndex = $tokens->getPrevMeaningfulToken($startIndex); + $prevToken = $tokens[$prevIndex]; + + // if this could be a function name we need to take one more step + if ($prevToken->isGivenKind(T_STRING)) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + $prevToken = $tokens[$prevIndex]; + } + + if ($prevToken->isGivenKind([T_FUNCTION, CT::T_RETURN_REF, CT::T_USE_LAMBDA, T_FN])) { + $tokens[$index] = new Token([CT::T_TYPE_COLON, ':']); + } + } + + public function getCustomTokens(): array + { + return [CT::T_TYPE_COLON]; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeIntersectionTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeIntersectionTransformer.php new file mode 100644 index 00000000..8018155e --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeIntersectionTransformer.php @@ -0,0 +1,55 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTypeTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `&` operator into CT::T_TYPE_INTERSECTION in `function foo(Type1 & Type2 $x) {` + * or `} catch (ExceptionType1 & ExceptionType2 $e) {`. + * + * @internal + */ +final class TypeIntersectionTransformer extends AbstractTypeTransformer +{ + public function getPriority(): int + { + // needs to run after ArrayTypehintTransformer, TypeColonTransformer and AttributeTransformer + return -15; + } + + public function getRequiredPhpVersionId(): int + { + return 8_01_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + $this->doProcess($tokens, $index, [T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG, '&']); + } + + public function getCustomTokens(): array + { + return [CT::T_TYPE_INTERSECTION]; + } + + protected function replaceToken(Tokens $tokens, int $index): void + { + $tokens[$index] = new Token([CT::T_TYPE_INTERSECTION, '&']); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/UseTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/UseTransformer.php new file mode 100644 index 00000000..5aa0c027 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/UseTransformer.php @@ -0,0 +1,102 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform T_USE into: + * - CT::T_USE_TRAIT for imports, + * - CT::T_USE_LAMBDA for lambda variable uses. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class UseTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // Should run after CurlyBraceTransformer and before TypeColonTransformer + return -5; + } + + public function getRequiredPhpVersionId(): int + { + return 5_03_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if ($token->isGivenKind(T_USE) && $this->isUseForLambda($tokens, $index)) { + $tokens[$index] = new Token([CT::T_USE_LAMBDA, $token->getContent()]); + + return; + } + + // Only search inside class/trait body for `T_USE` for traits. + // Cannot import traits inside interfaces or anywhere else + + $classTypes = [T_TRAIT]; + + if (\defined('T_ENUM')) { // @TODO: drop condition when PHP 8.1+ is required + $classTypes[] = T_ENUM; + } + + if ($token->isGivenKind(T_CLASS)) { + if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_DOUBLE_COLON)) { + return; + } + } elseif (!$token->isGivenKind($classTypes)) { + return; + } + + $index = $tokens->getNextTokenOfKind($index, ['{']); + $innerLimit = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + + while ($index < $innerLimit) { + $token = $tokens[++$index]; + + if (!$token->isGivenKind(T_USE)) { + continue; + } + + if ($this->isUseForLambda($tokens, $index)) { + $tokens[$index] = new Token([CT::T_USE_LAMBDA, $token->getContent()]); + } else { + $tokens[$index] = new Token([CT::T_USE_TRAIT, $token->getContent()]); + } + } + } + + public function getCustomTokens(): array + { + return [CT::T_USE_TRAIT, CT::T_USE_LAMBDA]; + } + + /** + * Check if token under given index is `use` statement for lambda function. + */ + private function isUseForLambda(Tokens $tokens, int $index): bool + { + $nextToken = $tokens[$tokens->getNextMeaningfulToken($index)]; + + // test `function () use ($foo) {}` case + return $nextToken->equals('('); + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/WhitespacyCommentTransformer.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/WhitespacyCommentTransformer.php new file mode 100644 index 00000000..91ab4cf2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/WhitespacyCommentTransformer.php @@ -0,0 +1,64 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Move trailing whitespaces from comments and docs into following T_WHITESPACE token. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class WhitespacyCommentTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 5_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$token->isComment()) { + return; + } + + $content = $token->getContent(); + $trimmedContent = rtrim($content); + + // nothing trimmed, nothing to do + if ($content === $trimmedContent) { + return; + } + + $whitespaces = substr($content, \strlen($trimmedContent)); + + $tokens[$index] = new Token([$token->getId(), $trimmedContent]); + + if (isset($tokens[$index + 1]) && $tokens[$index + 1]->isWhitespace()) { + $tokens[$index + 1] = new Token([T_WHITESPACE, $whitespaces.$tokens[$index + 1]->getContent()]); + } else { + $tokens->insertAt($index + 1, new Token([T_WHITESPACE, $whitespaces])); + } + } + + public function getCustomTokens(): array + { + return []; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TransformerInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TransformerInterface.php new file mode 100644 index 00000000..9d7f8600 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TransformerInterface.php @@ -0,0 +1,68 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +/** + * Interface for Transformer class. + * + * Transformer role is to register custom tokens and transform Tokens collection to use them. + * + * Custom token is a user defined token type and is used to separate different meaning of original token type. + * For example T_ARRAY is a token for both creating new array and typehinting a parameter. This two meaning should have two token types. + * + * @author Dariusz Rumiński + * + * @internal + */ +interface TransformerInterface +{ + /** + * Get tokens created by Transformer. + * + * @return list + */ + public function getCustomTokens(): array; + + /** + * Return the name of the transformer. + * + * The name must be all lowercase and without any spaces. + * + * @return string The name of the fixer + */ + public function getName(): string; + + /** + * Returns the priority of the transformer. + * + * The default priority is 0 and higher priorities are executed first. + */ + public function getPriority(): int; + + /** + * Return minimal required PHP version id to transform the code. + * + * Custom Token kinds from Transformers are always registered, but sometimes + * there is no need to analyse the Tokens if for sure we cannot find examined + * token kind, e.g. transforming `T_FUNCTION` in ` + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +use Symfony\Component\Finder\Finder; +use Symfony\Component\Finder\SplFileInfo; + +/** + * Collection of Transformer classes. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class Transformers +{ + /** + * The registered transformers. + * + * @var list + */ + private array $items = []; + + /** + * Register built in Transformers. + */ + private function __construct() + { + $this->registerBuiltInTransformers(); + + usort($this->items, static fn (TransformerInterface $a, TransformerInterface $b): int => $b->getPriority() <=> $a->getPriority()); + } + + public static function createSingleton(): self + { + static $instance = null; + + if (!$instance) { + $instance = new self(); + } + + return $instance; + } + + /** + * Transform given Tokens collection through all Transformer classes. + * + * @param Tokens $tokens Tokens collection + */ + public function transform(Tokens $tokens): void + { + foreach ($this->items as $transformer) { + foreach ($tokens as $index => $token) { + $transformer->process($tokens, $token, $index); + } + } + } + + /** + * @param TransformerInterface $transformer Transformer + */ + private function registerTransformer(TransformerInterface $transformer): void + { + if (\PHP_VERSION_ID >= $transformer->getRequiredPhpVersionId()) { + $this->items[] = $transformer; + } + } + + private function registerBuiltInTransformers(): void + { + static $registered = false; + + if ($registered) { + return; + } + + $registered = true; + + foreach ($this->findBuiltInTransformers() as $transformer) { + $this->registerTransformer($transformer); + } + } + + /** + * @return \Generator + */ + private function findBuiltInTransformers(): iterable + { + /** @var SplFileInfo $file */ + foreach (Finder::create()->files()->in(__DIR__.'/Transformer') as $file) { + $relativeNamespace = $file->getRelativePath(); + $class = __NAMESPACE__.'\\Transformer\\'.('' !== $relativeNamespace ? $relativeNamespace.'\\' : '').$file->getBasename('.php'); + + yield new $class(); + } + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ToolInfo.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ToolInfo.php new file mode 100644 index 00000000..cab29e45 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ToolInfo.php @@ -0,0 +1,113 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Console\Application; + +/** + * Obtain information about using version of tool. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class ToolInfo implements ToolInfoInterface +{ + public const COMPOSER_PACKAGE_NAME = 'friendsofphp/php-cs-fixer'; + + public const COMPOSER_LEGACY_PACKAGE_NAME = 'fabpot/php-cs-fixer'; + + /** + * @var null|array{name: string, version: string, dist: array{reference?: string}} + */ + private $composerInstallationDetails; + + /** + * @var null|bool + */ + private $isInstalledByComposer; + + public function getComposerInstallationDetails(): array + { + if (!$this->isInstalledByComposer()) { + throw new \LogicException('Cannot get composer version for tool not installed by composer.'); + } + + if (null === $this->composerInstallationDetails) { + $composerInstalled = json_decode(file_get_contents($this->getComposerInstalledFile()), true, 512, JSON_THROW_ON_ERROR); + + $packages = $composerInstalled['packages'] ?? $composerInstalled; + + foreach ($packages as $package) { + if (\in_array($package['name'], [self::COMPOSER_PACKAGE_NAME, self::COMPOSER_LEGACY_PACKAGE_NAME], true)) { + $this->composerInstallationDetails = $package; + + break; + } + } + } + + return $this->composerInstallationDetails; + } + + public function getComposerVersion(): string + { + $package = $this->getComposerInstallationDetails(); + + $versionSuffix = ''; + + if (isset($package['dist']['reference'])) { + $versionSuffix = '#'.$package['dist']['reference']; + } + + return $package['version'].$versionSuffix; + } + + public function getVersion(): string + { + if ($this->isInstalledByComposer()) { + return Application::VERSION.':'.$this->getComposerVersion(); + } + + return Application::VERSION; + } + + public function isInstalledAsPhar(): bool + { + return str_starts_with(__DIR__, 'phar://'); + } + + public function isInstalledByComposer(): bool + { + if (null === $this->isInstalledByComposer) { + $this->isInstalledByComposer = !$this->isInstalledAsPhar() && file_exists($this->getComposerInstalledFile()); + } + + return $this->isInstalledByComposer; + } + + public function getPharDownloadUri(string $version): string + { + return sprintf( + 'https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/releases/download/%s/php-cs-fixer.phar', + $version + ); + } + + private function getComposerInstalledFile(): string + { + return __DIR__.'/../../../composer/installed.json'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ToolInfoInterface.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ToolInfoInterface.php new file mode 100644 index 00000000..5124292b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/ToolInfoInterface.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @internal + */ +interface ToolInfoInterface +{ + /** + * @return array{name: string, version: string, dist: array{reference?: string}} + */ + public function getComposerInstallationDetails(): array; + + public function getComposerVersion(): string; + + public function getVersion(): string; + + public function isInstalledAsPhar(): bool; + + public function isInstalledByComposer(): bool; + + public function getPharDownloadUri(string $version): string; +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Utils.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Utils.php new file mode 100644 index 00000000..b89d4e18 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/Utils.php @@ -0,0 +1,231 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Tokenizer\Token; + +/** + * @author Dariusz Rumiński + * @author Graham Campbell + * @author Odín del Río + * + * @internal + * + * @deprecated This is a God Class anti-pattern. Don't expand it. It is fine to use logic that is already here (that's why we don't trigger deprecation warnings), but over time logic should be moved to dedicated, single-responsibility classes. + */ +final class Utils +{ + /** + * @var array + */ + private static array $deprecations = []; + + private function __construct() + { + // cannot create instance of util. class + } + + /** + * Converts a camel cased string to a snake cased string. + */ + public static function camelCaseToUnderscore(string $string): string + { + return mb_strtolower(Preg::replace('/(?isWhitespace()) { + throw new \InvalidArgumentException(sprintf('The given token must be whitespace, got "%s".', $token->getName())); + } + + $str = strrchr( + str_replace(["\r\n", "\r"], "\n", $token->getContent()), + "\n" + ); + + if (false === $str) { + return ''; + } + + return ltrim($str, "\n"); + } + + /** + * Perform stable sorting using provided comparison function. + * + * Stability is ensured by using Schwartzian transform. + * + * @param mixed[] $elements + * @param callable $getComparedValue a callable that takes a single element and returns the value to compare + * @param callable $compareValues a callable that compares two values + * + * @return mixed[] + */ + public static function stableSort(array $elements, callable $getComparedValue, callable $compareValues): array + { + array_walk($elements, static function (&$element, int $index) use ($getComparedValue): void { + $element = [$element, $index, $getComparedValue($element)]; + }); + + usort($elements, static function ($a, $b) use ($compareValues): int { + $comparison = $compareValues($a[2], $b[2]); + + if (0 !== $comparison) { + return $comparison; + } + + return $a[1] <=> $b[1]; + }); + + return array_map(static fn (array $item) => $item[0], $elements); + } + + /** + * Sort fixers by their priorities. + * + * @param FixerInterface[] $fixers + * + * @return FixerInterface[] + */ + public static function sortFixers(array $fixers): array + { + // Schwartzian transform is used to improve the efficiency and avoid + // `usort(): Array was modified by the user comparison function` warning for mocked objects. + return self::stableSort( + $fixers, + static fn (FixerInterface $fixer): int => $fixer->getPriority(), + static fn (int $a, int $b): int => $b <=> $a + ); + } + + /** + * Join names in natural language using specified wrapper (double quote by default). + * + * @param string[] $names + * + * @throws \InvalidArgumentException + */ + public static function naturalLanguageJoin(array $names, string $wrapper = '"'): string + { + if (0 === \count($names)) { + throw new \InvalidArgumentException('Array of names cannot be empty.'); + } + + if (\strlen($wrapper) > 1) { + throw new \InvalidArgumentException('Wrapper should be a single-char string or empty.'); + } + + $names = array_map(static fn (string $name): string => sprintf('%2$s%1$s%2$s', $name, $wrapper), $names); + + $last = array_pop($names); + + if (\count($names) > 0) { + return implode(', ', $names).' and '.$last; + } + + return $last; + } + + /** + * Join names in natural language wrapped in backticks, e.g. `a`, `b` and `c`. + * + * @param string[] $names + * + * @throws \InvalidArgumentException + */ + public static function naturalLanguageJoinWithBackticks(array $names): string + { + return self::naturalLanguageJoin($names, '`'); + } + + public static function triggerDeprecation(\Exception $futureException): void + { + if (getenv('PHP_CS_FIXER_FUTURE_MODE')) { + throw new \RuntimeException( + 'Your are using something deprecated, see previous exception. Aborting execution because `PHP_CS_FIXER_FUTURE_MODE` environment variable is set.', + 0, + $futureException + ); + } + + $message = $futureException->getMessage(); + + self::$deprecations[$message] = true; + @trigger_error($message, E_USER_DEPRECATED); + } + + /** + * @return list + */ + public static function getTriggeredDeprecations(): array + { + $triggeredDeprecations = array_keys(self::$deprecations); + sort($triggeredDeprecations); + + return $triggeredDeprecations; + } + + /** + * @param mixed $value + */ + public static function toString($value): string + { + return \is_array($value) + ? self::arrayToString($value) + : self::scalarToString($value); + } + + /** + * @param mixed $value + */ + private static function scalarToString($value): string + { + $str = var_export($value, true); + + return Preg::replace('/\bNULL\b/', 'null', $str); + } + + /** + * @param array $value + */ + private static function arrayToString(array $value): string + { + if (0 === \count($value)) { + return '[]'; + } + + $isHash = !array_is_list($value); + $str = '['; + + foreach ($value as $k => $v) { + if ($isHash) { + $str .= self::scalarToString($k).' => '; + } + + $str .= \is_array($v) + ? self::arrayToString($v).', ' + : self::scalarToString($v).', '; + } + + return substr($str, 0, -2).']'; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/WhitespacesFixerConfig.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/WhitespacesFixerConfig.php new file mode 100644 index 00000000..e558fd6b --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/WhitespacesFixerConfig.php @@ -0,0 +1,49 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @author Dariusz Rumiński + */ +final class WhitespacesFixerConfig +{ + private string $indent; + + private string $lineEnding; + + public function __construct(string $indent = ' ', string $lineEnding = "\n") + { + if (!\in_array($indent, [' ', ' ', "\t"], true)) { + throw new \InvalidArgumentException('Invalid "indent" param, expected tab or two or four spaces.'); + } + + if (!\in_array($lineEnding, ["\n", "\r\n"], true)) { + throw new \InvalidArgumentException('Invalid "lineEnding" param, expected "\n" or "\r\n".'); + } + + $this->indent = $indent; + $this->lineEnding = $lineEnding; + } + + public function getIndent(): string + { + return $this->indent; + } + + public function getLineEnding(): string + { + return $this->lineEnding; + } +} diff --git a/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/WordMatcher.php b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/WordMatcher.php new file mode 100644 index 00000000..36265a88 --- /dev/null +++ b/tools/php-cs-fixer/vendor/friendsofphp/php-cs-fixer/src/WordMatcher.php @@ -0,0 +1,53 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class WordMatcher +{ + /** + * @var string[] + */ + private array $candidates; + + /** + * @param string[] $candidates + */ + public function __construct(array $candidates) + { + $this->candidates = $candidates; + } + + public function match(string $needle): ?string + { + $word = null; + $distance = ceil(\strlen($needle) * 0.35); + + foreach ($this->candidates as $candidate) { + $candidateDistance = levenshtein($needle, $candidate); + + if ($candidateDistance < $distance) { + $word = $candidate; + $distance = $candidateDistance; + } + } + + return $word; + } +} diff --git a/tools/php-cs-fixer/vendor/psr/container/.gitignore b/tools/php-cs-fixer/vendor/psr/container/.gitignore new file mode 100644 index 00000000..b2395aa0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/psr/container/.gitignore @@ -0,0 +1,3 @@ +composer.lock +composer.phar +/vendor/ diff --git a/tools/php-cs-fixer/vendor/psr/container/LICENSE b/tools/php-cs-fixer/vendor/psr/container/LICENSE new file mode 100644 index 00000000..2877a489 --- /dev/null +++ b/tools/php-cs-fixer/vendor/psr/container/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013-2016 container-interop +Copyright (c) 2016 PHP Framework Interoperability Group + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/psr/container/README.md b/tools/php-cs-fixer/vendor/psr/container/README.md new file mode 100644 index 00000000..1b9d9e57 --- /dev/null +++ b/tools/php-cs-fixer/vendor/psr/container/README.md @@ -0,0 +1,13 @@ +Container interface +============== + +This repository holds all interfaces related to [PSR-11 (Container Interface)][psr-url]. + +Note that this is not a Container implementation of its own. It is merely abstractions that describe the components of a Dependency Injection Container. + +The installable [package][package-url] and [implementations][implementation-url] are listed on Packagist. + +[psr-url]: https://www.php-fig.org/psr/psr-11/ +[package-url]: https://packagist.org/packages/psr/container +[implementation-url]: https://packagist.org/providers/psr/container-implementation + diff --git a/tools/php-cs-fixer/vendor/psr/container/composer.json b/tools/php-cs-fixer/vendor/psr/container/composer.json new file mode 100644 index 00000000..baf6cd1a --- /dev/null +++ b/tools/php-cs-fixer/vendor/psr/container/composer.json @@ -0,0 +1,27 @@ +{ + "name": "psr/container", + "type": "library", + "description": "Common Container Interface (PHP FIG PSR-11)", + "keywords": ["psr", "psr-11", "container", "container-interop", "container-interface"], + "homepage": "https://github.com/php-fig/container", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": ">=7.4.0" + }, + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + } +} diff --git a/tools/php-cs-fixer/vendor/psr/container/src/ContainerExceptionInterface.php b/tools/php-cs-fixer/vendor/psr/container/src/ContainerExceptionInterface.php new file mode 100644 index 00000000..0f213f2f --- /dev/null +++ b/tools/php-cs-fixer/vendor/psr/container/src/ContainerExceptionInterface.php @@ -0,0 +1,12 @@ +=7.2.0" + }, + "autoload": { + "psr-4": { + "Psr\\EventDispatcher\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/tools/php-cs-fixer/vendor/psr/event-dispatcher/src/EventDispatcherInterface.php b/tools/php-cs-fixer/vendor/psr/event-dispatcher/src/EventDispatcherInterface.php new file mode 100644 index 00000000..4306fa91 --- /dev/null +++ b/tools/php-cs-fixer/vendor/psr/event-dispatcher/src/EventDispatcherInterface.php @@ -0,0 +1,21 @@ +logger = $logger; + } + + public function doSomething() + { + if ($this->logger) { + $this->logger->info('Doing work'); + } + + try { + $this->doSomethingElse(); + } catch (Exception $exception) { + $this->logger->error('Oh no!', array('exception' => $exception)); + } + + // do something useful + } +} +``` + +You can then pick one of the implementations of the interface to get a logger. + +If you want to implement the interface, you can require this package and +implement `Psr\Log\LoggerInterface` in your code. Please read the +[specification text](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md) +for details. diff --git a/tools/php-cs-fixer/vendor/psr/log/composer.json b/tools/php-cs-fixer/vendor/psr/log/composer.json new file mode 100644 index 00000000..879fc6f5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/psr/log/composer.json @@ -0,0 +1,26 @@ +{ + "name": "psr/log", + "description": "Common interface for logging libraries", + "keywords": ["psr", "psr-3", "log"], + "homepage": "https://github.com/php-fig/log", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": ">=8.0.0" + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + } +} diff --git a/tools/php-cs-fixer/vendor/psr/log/src/AbstractLogger.php b/tools/php-cs-fixer/vendor/psr/log/src/AbstractLogger.php new file mode 100644 index 00000000..d60a091a --- /dev/null +++ b/tools/php-cs-fixer/vendor/psr/log/src/AbstractLogger.php @@ -0,0 +1,15 @@ +logger = $logger; + } +} diff --git a/tools/php-cs-fixer/vendor/psr/log/src/LoggerInterface.php b/tools/php-cs-fixer/vendor/psr/log/src/LoggerInterface.php new file mode 100644 index 00000000..b3a24b5f --- /dev/null +++ b/tools/php-cs-fixer/vendor/psr/log/src/LoggerInterface.php @@ -0,0 +1,125 @@ +log(LogLevel::EMERGENCY, $message, $context); + } + + /** + * Action must be taken immediately. + * + * Example: Entire website down, database unavailable, etc. This should + * trigger the SMS alerts and wake you up. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function alert(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::ALERT, $message, $context); + } + + /** + * Critical conditions. + * + * Example: Application component unavailable, unexpected exception. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function critical(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::CRITICAL, $message, $context); + } + + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function error(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::ERROR, $message, $context); + } + + /** + * Exceptional occurrences that are not errors. + * + * Example: Use of deprecated APIs, poor use of an API, undesirable things + * that are not necessarily wrong. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function warning(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::WARNING, $message, $context); + } + + /** + * Normal but significant events. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function notice(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::NOTICE, $message, $context); + } + + /** + * Interesting events. + * + * Example: User logs in, SQL logs. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function info(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::INFO, $message, $context); + } + + /** + * Detailed debug information. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function debug(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::DEBUG, $message, $context); + } + + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param string|\Stringable $message + * @param array $context + * + * @return void + * + * @throws \Psr\Log\InvalidArgumentException + */ + abstract public function log($level, string|\Stringable $message, array $context = []): void; +} diff --git a/tools/php-cs-fixer/vendor/psr/log/src/NullLogger.php b/tools/php-cs-fixer/vendor/psr/log/src/NullLogger.php new file mode 100644 index 00000000..c1cc3c06 --- /dev/null +++ b/tools/php-cs-fixer/vendor/psr/log/src/NullLogger.php @@ -0,0 +1,30 @@ +logger) { }` + * blocks. + */ +class NullLogger extends AbstractLogger +{ + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param string|\Stringable $message + * @param array $context + * + * @return void + * + * @throws \Psr\Log\InvalidArgumentException + */ + public function log($level, string|\Stringable $message, array $context = []): void + { + // noop + } +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/ChangeLog.md b/tools/php-cs-fixer/vendor/sebastian/diff/ChangeLog.md new file mode 100644 index 00000000..9142e50f --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/ChangeLog.md @@ -0,0 +1,120 @@ +# ChangeLog + +All notable changes are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles. + +## [5.0.3] - 2023-05-01 + +### Changed + +* [#119](https://github.com/sebastianbergmann/diff/pull/119): Improve performance of `TimeEfficientLongestCommonSubsequenceCalculator` + +## [5.0.2] - 2023-05-01 + +### Changed + +* [#118](https://github.com/sebastianbergmann/diff/pull/118): Improve performance of `MemoryEfficientLongestCommonSubsequenceCalculator` + +## [5.0.1] - 2023-03-23 + +### Fixed + +* [#115](https://github.com/sebastianbergmann/diff/pull/115): `Parser::parseFileDiff()` does not handle diffs correctly that only add lines or only remove lines + +## [5.0.0] - 2023-02-03 + +### Changed + +* Passing a `DiffOutputBuilderInterface` instance to `Differ::__construct()` is no longer optional + +### Removed + +* Removed support for PHP 7.3, PHP 7.4, and PHP 8.0 + +## [4.0.4] - 2020-10-26 + +### Fixed + +* `SebastianBergmann\Diff\Exception` now correctly extends `\Throwable` + +## [4.0.3] - 2020-09-28 + +### Changed + +* Changed PHP version constraint in `composer.json` from `^7.3 || ^8.0` to `>=7.3` + +## [4.0.2] - 2020-06-30 + +### Added + +* This component is now supported on PHP 8 + +## [4.0.1] - 2020-05-08 + +### Fixed + +* [#99](https://github.com/sebastianbergmann/diff/pull/99): Regression in unified diff output of identical strings + +## [4.0.0] - 2020-02-07 + +### Removed + +* Removed support for PHP 7.1 and PHP 7.2 + +## [3.0.2] - 2019-02-04 + +### Changed + +* `Chunk::setLines()` now ensures that the `$lines` array only contains `Line` objects + +## [3.0.1] - 2018-06-10 + +### Fixed + +* Removed `"minimum-stability": "dev",` from `composer.json` + +## [3.0.0] - 2018-02-01 + +* The `StrictUnifiedDiffOutputBuilder` implementation of the `DiffOutputBuilderInterface` was added + +### Changed + +* The default `DiffOutputBuilderInterface` implementation now generates context lines (unchanged lines) + +### Removed + +* Removed support for PHP 7.0 + +### Fixed + +* [#70](https://github.com/sebastianbergmann/diff/issues/70): Diffing of arrays no longer works + +## [2.0.1] - 2017-08-03 + +### Fixed + +* [#66](https://github.com/sebastianbergmann/diff/pull/66): Restored backwards compatibility for PHPUnit 6.1.4, 6.2.0, 6.2.1, 6.2.2, and 6.2.3 + +## [2.0.0] - 2017-07-11 [YANKED] + +### Added + +* [#64](https://github.com/sebastianbergmann/diff/pull/64): Show line numbers for chunks of a diff + +### Removed + +* This component is no longer supported on PHP 5.6 + +[5.0.3]: https://github.com/sebastianbergmann/diff/compare/5.0.2...5.0.3 +[5.0.2]: https://github.com/sebastianbergmann/diff/compare/5.0.1...5.0.2 +[5.0.1]: https://github.com/sebastianbergmann/diff/compare/5.0.0...5.0.1 +[5.0.0]: https://github.com/sebastianbergmann/diff/compare/4.0.4...5.0.0 +[4.0.4]: https://github.com/sebastianbergmann/diff/compare/4.0.3...4.0.4 +[4.0.3]: https://github.com/sebastianbergmann/diff/compare/4.0.2...4.0.3 +[4.0.2]: https://github.com/sebastianbergmann/diff/compare/4.0.1...4.0.2 +[4.0.1]: https://github.com/sebastianbergmann/diff/compare/4.0.0...4.0.1 +[4.0.0]: https://github.com/sebastianbergmann/diff/compare/3.0.2...4.0.0 +[3.0.2]: https://github.com/sebastianbergmann/diff/compare/3.0.1...3.0.2 +[3.0.1]: https://github.com/sebastianbergmann/diff/compare/3.0.0...3.0.1 +[3.0.0]: https://github.com/sebastianbergmann/diff/compare/2.0...3.0.0 +[2.0.1]: https://github.com/sebastianbergmann/diff/compare/c341c98ce083db77f896a0aa64f5ee7652915970...2.0.1 +[2.0.0]: https://github.com/sebastianbergmann/diff/compare/1.4...c341c98ce083db77f896a0aa64f5ee7652915970 diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/LICENSE b/tools/php-cs-fixer/vendor/sebastian/diff/LICENSE new file mode 100644 index 00000000..a453252d --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2002-2023, Sebastian Bergmann +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/README.md b/tools/php-cs-fixer/vendor/sebastian/diff/README.md new file mode 100644 index 00000000..539dc59e --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/README.md @@ -0,0 +1,206 @@ +[![Latest Stable Version](https://poser.pugx.org/sebastian/diff/v/stable.png)](https://packagist.org/packages/sebastian/diff) +[![CI Status](https://github.com/sebastianbergmann/diff/workflows/CI/badge.svg)](https://github.com/sebastianbergmann/diff/actions) +[![Type Coverage](https://shepherd.dev/github/sebastianbergmann/diff/coverage.svg)](https://shepherd.dev/github/sebastianbergmann/diff) +[![codecov](https://codecov.io/gh/sebastianbergmann/diff/branch/main/graph/badge.svg)](https://codecov.io/gh/sebastianbergmann/diff) + +# sebastian/diff + +Diff implementation for PHP, factored out of PHPUnit into a stand-alone component. + +## Installation + +You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/): + +``` +composer require sebastian/diff +``` + +If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency: + +``` +composer require --dev sebastian/diff +``` + +### Usage + +#### Generating diff + +The `Differ` class can be used to generate a textual representation of the difference between two strings: + +```php +diff('foo', 'bar'); +``` + +The code above yields the output below: +```diff +--- Original ++++ New +@@ @@ +-foo ++bar +``` + +There are three output builders available in this package: + +#### UnifiedDiffOutputBuilder + +This is default builder, which generates the output close to udiff and is used by PHPUnit. + +```php +diff('foo', 'bar'); +``` + +#### StrictUnifiedDiffOutputBuilder + +Generates (strict) Unified diff's (unidiffs) with hunks, +similar to `diff -u` and compatible with `patch` and `git apply`. + +```php + true, // ranges of length one are rendered with the trailing `,1` + 'commonLineThreshold' => 6, // number of same lines before ending a new hunk and creating a new one (if needed) + 'contextLines' => 3, // like `diff: -u, -U NUM, --unified[=NUM]`, for patch/git apply compatibility best to keep at least @ 3 + 'fromFile' => '', + 'fromFileDate' => null, + 'toFile' => '', + 'toFileDate' => null, +]); + +$differ = new Differ($builder); +print $differ->diff('foo', 'bar'); +``` + +#### DiffOnlyOutputBuilder + +Output only the lines that differ. + +```php +diff('foo', 'bar'); +``` + +#### DiffOutputBuilderInterface + +You can pass any output builder to the `Differ` class as longs as it implements the `DiffOutputBuilderInterface`. + +#### Parsing diff + +The `Parser` class can be used to parse a unified diff into an object graph: + +```php +use SebastianBergmann\Diff\Parser; +use SebastianBergmann\Git; + +$git = new Git('/usr/local/src/money'); + +$diff = $git->getDiff( + '948a1a07768d8edd10dcefa8315c1cbeffb31833', + 'c07a373d2399f3e686234c4f7f088d635eb9641b' +); + +$parser = new Parser; + +print_r($parser->parse($diff)); +``` + +The code above yields the output below: + + Array + ( + [0] => SebastianBergmann\Diff\Diff Object + ( + [from:SebastianBergmann\Diff\Diff:private] => a/tests/MoneyTest.php + [to:SebastianBergmann\Diff\Diff:private] => b/tests/MoneyTest.php + [chunks:SebastianBergmann\Diff\Diff:private] => Array + ( + [0] => SebastianBergmann\Diff\Chunk Object + ( + [start:SebastianBergmann\Diff\Chunk:private] => 87 + [startRange:SebastianBergmann\Diff\Chunk:private] => 7 + [end:SebastianBergmann\Diff\Chunk:private] => 87 + [endRange:SebastianBergmann\Diff\Chunk:private] => 7 + [lines:SebastianBergmann\Diff\Chunk:private] => Array + ( + [0] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => * @covers SebastianBergmann\Money\Money::add + ) + + [1] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => * @covers SebastianBergmann\Money\Money::newMoney + ) + + [2] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => */ + ) + + [3] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 2 + [content:SebastianBergmann\Diff\Line:private] => public function testAnotherMoneyWithSameCurrencyObjectCanBeAdded() + ) + + [4] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 1 + [content:SebastianBergmann\Diff\Line:private] => public function testAnotherMoneyObjectWithSameCurrencyCanBeAdded() + ) + + [5] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => { + ) + + [6] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => $a = new Money(1, new Currency('EUR')); + ) + + [7] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => $b = new Money(2, new Currency('EUR')); + ) + ) + ) + ) + ) + ) + +Note: If the chunk size is 0 lines, i.e., `getStartRange()` or `getEndRange()` return 0, the number of line returned by `getStart()` or `getEnd()` is one lower than one would expect. It is the line number after which the chunk should be inserted or deleted; in all other cases, it gives the first line number of the replaced range of lines. diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/SECURITY.md b/tools/php-cs-fixer/vendor/sebastian/diff/SECURITY.md new file mode 100644 index 00000000..d88ff001 --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/SECURITY.md @@ -0,0 +1,30 @@ +# Security Policy + +If you believe you have found a security vulnerability in the library that is developed in this repository, please report it to us through coordinated disclosure. + +**Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.** + +Instead, please email `sebastian@phpunit.de`. + +Please include as much of the information listed below as you can to help us better understand and resolve the issue: + +* The type of issue +* Full paths of source file(s) related to the manifestation of the issue +* The location of the affected source code (tag/branch/commit or direct URL) +* Any special configuration required to reproduce the issue +* Step-by-step instructions to reproduce the issue +* Proof-of-concept or exploit code (if possible) +* Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +## Web Context + +The library that is developed in this repository was either extracted from [PHPUnit](https://github.com/sebastianbergmann/phpunit) or developed specifically as a dependency for PHPUnit. + +The library is developed with a focus on development environments and the command-line. No specific testing or hardening with regard to using the library in an HTTP or web context or with untrusted input data is performed. The library might also contain functionality that intentionally exposes internal application data for debugging purposes. + +If the library is used in a web application, the application developer is responsible for filtering inputs or escaping outputs as necessary and for verifying that the used functionality is safe for use within the intended context. + +Vulnerabilities specific to the use outside a development context will be fixed as applicable, provided that the fix does not have an averse effect on the primary use case for development purposes. + diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/composer.json b/tools/php-cs-fixer/vendor/sebastian/diff/composer.json new file mode 100644 index 00000000..cd37ef6b --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/composer.json @@ -0,0 +1,51 @@ +{ + "name": "sebastian/diff", + "description": "Diff implementation", + "keywords": ["diff", "udiff", "unidiff", "unified diff"], + "homepage": "https://github.com/sebastianbergmann/diff", + "license": "BSD-3-Clause", + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + } + ], + "support": { + "issues": "https://github.com/sebastianbergmann/diff/issues", + "security": "https://github.com/sebastianbergmann/diff/security/policy" + }, + "prefer-stable": true, + "config": { + "platform": { + "php": "8.1.0" + }, + "optimize-autoloader": true, + "sort-packages": true + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.0", + "symfony/process": "^4.2 || ^5" + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "autoload-dev": { + "classmap": [ + "tests/" + ] + }, + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + } +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/Chunk.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/Chunk.php new file mode 100644 index 00000000..cdfdf00b --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/Chunk.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +final class Chunk +{ + private int $start; + private int $startRange; + private int $end; + private int $endRange; + private array $lines; + + public function __construct(int $start = 0, int $startRange = 1, int $end = 0, int $endRange = 1, array $lines = []) + { + $this->start = $start; + $this->startRange = $startRange; + $this->end = $end; + $this->endRange = $endRange; + $this->lines = $lines; + } + + public function getStart(): int + { + return $this->start; + } + + public function getStartRange(): int + { + return $this->startRange; + } + + public function getEnd(): int + { + return $this->end; + } + + public function getEndRange(): int + { + return $this->endRange; + } + + /** + * @psalm-return list + */ + public function getLines(): array + { + return $this->lines; + } + + /** + * @psalm-param list $lines + */ + public function setLines(array $lines): void + { + foreach ($lines as $line) { + if (!$line instanceof Line) { + throw new InvalidArgumentException; + } + } + + $this->lines = $lines; + } +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/Diff.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/Diff.php new file mode 100644 index 00000000..3376b723 --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/Diff.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +final class Diff +{ + private string $from; + private string $to; + + /** + * @psalm-var list + */ + private array $chunks; + + /** + * @psalm-param list $chunks + */ + public function __construct(string $from, string $to, array $chunks = []) + { + $this->from = $from; + $this->to = $to; + $this->chunks = $chunks; + } + + public function getFrom(): string + { + return $this->from; + } + + public function getTo(): string + { + return $this->to; + } + + /** + * @psalm-return list + */ + public function getChunks(): array + { + return $this->chunks; + } + + /** + * @psalm-param list $chunks + */ + public function setChunks(array $chunks): void + { + $this->chunks = $chunks; + } +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/Differ.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/Differ.php new file mode 100644 index 00000000..19ccf97c --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/Differ.php @@ -0,0 +1,239 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +use const PHP_INT_SIZE; +use const PREG_SPLIT_DELIM_CAPTURE; +use const PREG_SPLIT_NO_EMPTY; +use function array_shift; +use function array_unshift; +use function array_values; +use function count; +use function current; +use function end; +use function is_string; +use function key; +use function min; +use function preg_split; +use function prev; +use function reset; +use function str_ends_with; +use function substr; +use SebastianBergmann\Diff\Output\DiffOutputBuilderInterface; + +final class Differ +{ + public const OLD = 0; + public const ADDED = 1; + public const REMOVED = 2; + public const DIFF_LINE_END_WARNING = 3; + public const NO_LINE_END_EOF_WARNING = 4; + private DiffOutputBuilderInterface $outputBuilder; + + public function __construct(DiffOutputBuilderInterface $outputBuilder) + { + $this->outputBuilder = $outputBuilder; + } + + public function diff(array|string $from, array|string $to, LongestCommonSubsequenceCalculator $lcs = null): string + { + $diff = $this->diffToArray($from, $to, $lcs); + + return $this->outputBuilder->getDiff($diff); + } + + public function diffToArray(array|string $from, array|string $to, LongestCommonSubsequenceCalculator $lcs = null): array + { + if (is_string($from)) { + $from = $this->splitStringByLines($from); + } + + if (is_string($to)) { + $to = $this->splitStringByLines($to); + } + + [$from, $to, $start, $end] = self::getArrayDiffParted($from, $to); + + if ($lcs === null) { + $lcs = $this->selectLcsImplementation($from, $to); + } + + $common = $lcs->calculate(array_values($from), array_values($to)); + $diff = []; + + foreach ($start as $token) { + $diff[] = [$token, self::OLD]; + } + + reset($from); + reset($to); + + foreach ($common as $token) { + while (($fromToken = reset($from)) !== $token) { + $diff[] = [array_shift($from), self::REMOVED]; + } + + while (($toToken = reset($to)) !== $token) { + $diff[] = [array_shift($to), self::ADDED]; + } + + $diff[] = [$token, self::OLD]; + + array_shift($from); + array_shift($to); + } + + while (($token = array_shift($from)) !== null) { + $diff[] = [$token, self::REMOVED]; + } + + while (($token = array_shift($to)) !== null) { + $diff[] = [$token, self::ADDED]; + } + + foreach ($end as $token) { + $diff[] = [$token, self::OLD]; + } + + if ($this->detectUnmatchedLineEndings($diff)) { + array_unshift($diff, ["#Warning: Strings contain different line endings!\n", self::DIFF_LINE_END_WARNING]); + } + + return $diff; + } + + private function splitStringByLines(string $input): array + { + return preg_split('/(.*\R)/', $input, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); + } + + private function selectLcsImplementation(array $from, array $to): LongestCommonSubsequenceCalculator + { + // We do not want to use the time-efficient implementation if its memory + // footprint will probably exceed this value. Note that the footprint + // calculation is only an estimation for the matrix and the LCS method + // will typically allocate a bit more memory than this. + $memoryLimit = 100 * 1024 * 1024; + + if ($this->calculateEstimatedFootprint($from, $to) > $memoryLimit) { + return new MemoryEfficientLongestCommonSubsequenceCalculator; + } + + return new TimeEfficientLongestCommonSubsequenceCalculator; + } + + private function calculateEstimatedFootprint(array $from, array $to): float|int + { + $itemSize = PHP_INT_SIZE === 4 ? 76 : 144; + + return $itemSize * min(count($from), count($to)) ** 2; + } + + private function detectUnmatchedLineEndings(array $diff): bool + { + $newLineBreaks = ['' => true]; + $oldLineBreaks = ['' => true]; + + foreach ($diff as $entry) { + if (self::OLD === $entry[1]) { + $ln = $this->getLinebreak($entry[0]); + $oldLineBreaks[$ln] = true; + $newLineBreaks[$ln] = true; + } elseif (self::ADDED === $entry[1]) { + $newLineBreaks[$this->getLinebreak($entry[0])] = true; + } elseif (self::REMOVED === $entry[1]) { + $oldLineBreaks[$this->getLinebreak($entry[0])] = true; + } + } + + // if either input or output is a single line without breaks than no warning should be raised + if (['' => true] === $newLineBreaks || ['' => true] === $oldLineBreaks) { + return false; + } + + // two-way compare + foreach ($newLineBreaks as $break => $set) { + if (!isset($oldLineBreaks[$break])) { + return true; + } + } + + foreach ($oldLineBreaks as $break => $set) { + if (!isset($newLineBreaks[$break])) { + return true; + } + } + + return false; + } + + private function getLinebreak($line): string + { + if (!is_string($line)) { + return ''; + } + + $lc = substr($line, -1); + + if ("\r" === $lc) { + return "\r"; + } + + if ("\n" !== $lc) { + return ''; + } + + if (str_ends_with($line, "\r\n")) { + return "\r\n"; + } + + return "\n"; + } + + private static function getArrayDiffParted(array &$from, array &$to): array + { + $start = []; + $end = []; + + reset($to); + + foreach ($from as $k => $v) { + $toK = key($to); + + if ($toK === $k && $v === $to[$k]) { + $start[$k] = $v; + + unset($from[$k], $to[$k]); + } else { + break; + } + } + + end($from); + end($to); + + do { + $fromK = key($from); + $toK = key($to); + + if (null === $fromK || null === $toK || current($from) !== current($to)) { + break; + } + + prev($from); + prev($to); + + $end = [$fromK => $from[$fromK]] + $end; + unset($from[$fromK], $to[$toK]); + } while (true); + + return [$from, $to, $start, $end]; + } +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/Exception/ConfigurationException.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/Exception/ConfigurationException.php new file mode 100644 index 00000000..85f066c2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/Exception/ConfigurationException.php @@ -0,0 +1,37 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +use function gettype; +use function is_object; +use function sprintf; +use Exception; + +final class ConfigurationException extends InvalidArgumentException +{ + public function __construct( + string $option, + string $expected, + $value, + int $code = 0, + Exception $previous = null + ) { + parent::__construct( + sprintf( + 'Option "%s" must be %s, got "%s".', + $option, + $expected, + is_object($value) ? $value::class : (null === $value ? '' : gettype($value) . '#' . $value) + ), + $code, + $previous + ); + } +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/Exception/Exception.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/Exception/Exception.php new file mode 100644 index 00000000..e20d3203 --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/Exception/Exception.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +use Throwable; + +interface Exception extends Throwable +{ +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/Exception/InvalidArgumentException.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/Exception/InvalidArgumentException.php new file mode 100644 index 00000000..846ac3fb --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/Exception/InvalidArgumentException.php @@ -0,0 +1,14 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +class InvalidArgumentException extends \InvalidArgumentException implements Exception +{ +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/Line.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/Line.php new file mode 100644 index 00000000..a9106a25 --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/Line.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +final class Line +{ + public const ADDED = 1; + public const REMOVED = 2; + public const UNCHANGED = 3; + private int $type; + private string $content; + + public function __construct(int $type = self::UNCHANGED, string $content = '') + { + $this->type = $type; + $this->content = $content; + } + + public function getContent(): string + { + return $this->content; + } + + public function getType(): int + { + return $this->type; + } +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/LongestCommonSubsequenceCalculator.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/LongestCommonSubsequenceCalculator.php new file mode 100644 index 00000000..dea8fe1c --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/LongestCommonSubsequenceCalculator.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +interface LongestCommonSubsequenceCalculator +{ + /** + * Calculates the longest common subsequence of two arrays. + */ + public function calculate(array $from, array $to): array; +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/MemoryEfficientLongestCommonSubsequenceCalculator.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/MemoryEfficientLongestCommonSubsequenceCalculator.php new file mode 100644 index 00000000..a46de07d --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/MemoryEfficientLongestCommonSubsequenceCalculator.php @@ -0,0 +1,93 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +use function array_fill; +use function array_merge; +use function array_reverse; +use function array_slice; +use function count; +use function in_array; +use function max; + +final class MemoryEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator +{ + /** + * @inheritDoc + */ + public function calculate(array $from, array $to): array + { + $cFrom = count($from); + $cTo = count($to); + + if ($cFrom === 0) { + return []; + } + + if ($cFrom === 1) { + if (in_array($from[0], $to, true)) { + return [$from[0]]; + } + + return []; + } + + $i = (int) ($cFrom / 2); + $fromStart = array_slice($from, 0, $i); + $fromEnd = array_slice($from, $i); + $llB = $this->length($fromStart, $to); + $llE = $this->length(array_reverse($fromEnd), array_reverse($to)); + $jMax = 0; + $max = 0; + + for ($j = 0; $j <= $cTo; $j++) { + $m = $llB[$j] + $llE[$cTo - $j]; + + if ($m >= $max) { + $max = $m; + $jMax = $j; + } + } + + $toStart = array_slice($to, 0, $jMax); + $toEnd = array_slice($to, $jMax); + + return array_merge( + $this->calculate($fromStart, $toStart), + $this->calculate($fromEnd, $toEnd) + ); + } + + private function length(array $from, array $to): array + { + $current = array_fill(0, count($to) + 1, 0); + $cFrom = count($from); + $cTo = count($to); + + for ($i = 0; $i < $cFrom; $i++) { + $prev = $current; + + for ($j = 0; $j < $cTo; $j++) { + if ($from[$i] === $to[$j]) { + $current[$j + 1] = $prev[$j] + 1; + } else { + // don't use max() to avoid function call overhead + if ($current[$j] > $prev[$j + 1]) { + $current[$j + 1] = $current[$j]; + } else { + $current[$j + 1] = $prev[$j + 1]; + } + } + } + } + + return $current; + } +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/Output/AbstractChunkOutputBuilder.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/Output/AbstractChunkOutputBuilder.php new file mode 100644 index 00000000..6c706839 --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/Output/AbstractChunkOutputBuilder.php @@ -0,0 +1,52 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff\Output; + +use function count; + +abstract class AbstractChunkOutputBuilder implements DiffOutputBuilderInterface +{ + /** + * Takes input of the diff array and returns the common parts. + * Iterates through diff line by line. + */ + protected function getCommonChunks(array $diff, int $lineThreshold = 5): array + { + $diffSize = count($diff); + $capturing = false; + $chunkStart = 0; + $chunkSize = 0; + $commonChunks = []; + + for ($i = 0; $i < $diffSize; $i++) { + if ($diff[$i][1] === 0 /* OLD */) { + if ($capturing === false) { + $capturing = true; + $chunkStart = $i; + $chunkSize = 0; + } else { + $chunkSize++; + } + } elseif ($capturing !== false) { + if ($chunkSize >= $lineThreshold) { + $commonChunks[$chunkStart] = $chunkStart + $chunkSize; + } + + $capturing = false; + } + } + + if ($capturing !== false && $chunkSize >= $lineThreshold) { + $commonChunks[$chunkStart] = $chunkStart + $chunkSize; + } + + return $commonChunks; + } +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php new file mode 100644 index 00000000..fd6ce768 --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff\Output; + +use function fclose; +use function fopen; +use function fwrite; +use function str_ends_with; +use function stream_get_contents; +use function substr; +use SebastianBergmann\Diff\Differ; + +/** + * Builds a diff string representation in a loose unified diff format + * listing only changes lines. Does not include line numbers. + */ +final class DiffOnlyOutputBuilder implements DiffOutputBuilderInterface +{ + private string $header; + + public function __construct(string $header = "--- Original\n+++ New\n") + { + $this->header = $header; + } + + public function getDiff(array $diff): string + { + $buffer = fopen('php://memory', 'r+b'); + + if ('' !== $this->header) { + fwrite($buffer, $this->header); + + if (!str_ends_with($this->header, "\n")) { + fwrite($buffer, "\n"); + } + } + + foreach ($diff as $diffEntry) { + if ($diffEntry[1] === Differ::ADDED) { + fwrite($buffer, '+' . $diffEntry[0]); + } elseif ($diffEntry[1] === Differ::REMOVED) { + fwrite($buffer, '-' . $diffEntry[0]); + } elseif ($diffEntry[1] === Differ::DIFF_LINE_END_WARNING) { + fwrite($buffer, ' ' . $diffEntry[0]); + + continue; // Warnings should not be tested for line break, it will always be there + } else { /* Not changed (old) 0 */ + continue; // we didn't write the not-changed line, so do not add a line break either + } + + $lc = substr($diffEntry[0], -1); + + if ($lc !== "\n" && $lc !== "\r") { + fwrite($buffer, "\n"); // \No newline at end of file + } + } + + $diff = stream_get_contents($buffer, -1, 0); + fclose($buffer); + + return $diff; + } +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/Output/DiffOutputBuilderInterface.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/Output/DiffOutputBuilderInterface.php new file mode 100644 index 00000000..0e18f9f2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/Output/DiffOutputBuilderInterface.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff\Output; + +/** + * Defines how an output builder should take a generated + * diff array and return a string representation of that diff. + */ +interface DiffOutputBuilderInterface +{ + public function getDiff(array $diff): string; +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php new file mode 100644 index 00000000..3eb7428d --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php @@ -0,0 +1,326 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff\Output; + +use function array_merge; +use function array_splice; +use function count; +use function fclose; +use function fopen; +use function fwrite; +use function is_bool; +use function is_int; +use function is_string; +use function max; +use function min; +use function sprintf; +use function stream_get_contents; +use function substr; +use SebastianBergmann\Diff\ConfigurationException; +use SebastianBergmann\Diff\Differ; + +/** + * Strict Unified diff output builder. + * + * Generates (strict) Unified diff's (unidiffs) with hunks. + */ +final class StrictUnifiedDiffOutputBuilder implements DiffOutputBuilderInterface +{ + private static array $default = [ + 'collapseRanges' => true, // ranges of length one are rendered with the trailing `,1` + 'commonLineThreshold' => 6, // number of same lines before ending a new hunk and creating a new one (if needed) + 'contextLines' => 3, // like `diff: -u, -U NUM, --unified[=NUM]`, for patch/git apply compatibility best to keep at least @ 3 + 'fromFile' => null, + 'fromFileDate' => null, + 'toFile' => null, + 'toFileDate' => null, + ]; + private bool $changed; + private bool $collapseRanges; + + /** + * @psalm-var positive-int + */ + private int $commonLineThreshold; + private string $header; + + /** + * @psalm-var positive-int + */ + private int $contextLines; + + public function __construct(array $options = []) + { + $options = array_merge(self::$default, $options); + + if (!is_bool($options['collapseRanges'])) { + throw new ConfigurationException('collapseRanges', 'a bool', $options['collapseRanges']); + } + + if (!is_int($options['contextLines']) || $options['contextLines'] < 0) { + throw new ConfigurationException('contextLines', 'an int >= 0', $options['contextLines']); + } + + if (!is_int($options['commonLineThreshold']) || $options['commonLineThreshold'] <= 0) { + throw new ConfigurationException('commonLineThreshold', 'an int > 0', $options['commonLineThreshold']); + } + + $this->assertString($options, 'fromFile'); + $this->assertString($options, 'toFile'); + $this->assertStringOrNull($options, 'fromFileDate'); + $this->assertStringOrNull($options, 'toFileDate'); + + $this->header = sprintf( + "--- %s%s\n+++ %s%s\n", + $options['fromFile'], + null === $options['fromFileDate'] ? '' : "\t" . $options['fromFileDate'], + $options['toFile'], + null === $options['toFileDate'] ? '' : "\t" . $options['toFileDate'] + ); + + $this->collapseRanges = $options['collapseRanges']; + $this->commonLineThreshold = $options['commonLineThreshold']; + $this->contextLines = $options['contextLines']; + } + + public function getDiff(array $diff): string + { + if (0 === count($diff)) { + return ''; + } + + $this->changed = false; + + $buffer = fopen('php://memory', 'r+b'); + fwrite($buffer, $this->header); + + $this->writeDiffHunks($buffer, $diff); + + if (!$this->changed) { + fclose($buffer); + + return ''; + } + + $diff = stream_get_contents($buffer, -1, 0); + + fclose($buffer); + + // If the last char is not a linebreak: add it. + // This might happen when both the `from` and `to` do not have a trailing linebreak + $last = substr($diff, -1); + + return "\n" !== $last && "\r" !== $last + ? $diff . "\n" + : $diff; + } + + private function writeDiffHunks($output, array $diff): void + { + // detect "No newline at end of file" and insert into `$diff` if needed + + $upperLimit = count($diff); + + if (0 === $diff[$upperLimit - 1][1]) { + $lc = substr($diff[$upperLimit - 1][0], -1); + + if ("\n" !== $lc) { + array_splice($diff, $upperLimit, 0, [["\n\\ No newline at end of file\n", Differ::NO_LINE_END_EOF_WARNING]]); + } + } else { + // search back for the last `+` and `-` line, + // check if it has a trailing linebreak, else add a warning under it + $toFind = [1 => true, 2 => true]; + + for ($i = $upperLimit - 1; $i >= 0; $i--) { + if (isset($toFind[$diff[$i][1]])) { + unset($toFind[$diff[$i][1]]); + $lc = substr($diff[$i][0], -1); + + if ("\n" !== $lc) { + array_splice($diff, $i + 1, 0, [["\n\\ No newline at end of file\n", Differ::NO_LINE_END_EOF_WARNING]]); + } + + if (!count($toFind)) { + break; + } + } + } + } + + // write hunks to output buffer + + $cutOff = max($this->commonLineThreshold, $this->contextLines); + $hunkCapture = false; + $sameCount = $toRange = $fromRange = 0; + $toStart = $fromStart = 1; + $i = 0; + + /** @var int $i */ + foreach ($diff as $i => $entry) { + if (0 === $entry[1]) { // same + if (false === $hunkCapture) { + $fromStart++; + $toStart++; + + continue; + } + + $sameCount++; + $toRange++; + $fromRange++; + + if ($sameCount === $cutOff) { + $contextStartOffset = ($hunkCapture - $this->contextLines) < 0 + ? $hunkCapture + : $this->contextLines; + + // note: $contextEndOffset = $this->contextLines; + // + // because we never go beyond the end of the diff. + // with the cutoff/contextlines here the follow is never true; + // + // if ($i - $cutOff + $this->contextLines + 1 > \count($diff)) { + // $contextEndOffset = count($diff) - 1; + // } + // + // ; that would be true for a trailing incomplete hunk case which is dealt with after this loop + + $this->writeHunk( + $diff, + $hunkCapture - $contextStartOffset, + $i - $cutOff + $this->contextLines + 1, + $fromStart - $contextStartOffset, + $fromRange - $cutOff + $contextStartOffset + $this->contextLines, + $toStart - $contextStartOffset, + $toRange - $cutOff + $contextStartOffset + $this->contextLines, + $output + ); + + $fromStart += $fromRange; + $toStart += $toRange; + + $hunkCapture = false; + $sameCount = $toRange = $fromRange = 0; + } + + continue; + } + + $sameCount = 0; + + if ($entry[1] === Differ::NO_LINE_END_EOF_WARNING) { + continue; + } + + $this->changed = true; + + if (false === $hunkCapture) { + $hunkCapture = $i; + } + + if (Differ::ADDED === $entry[1]) { // added + $toRange++; + } + + if (Differ::REMOVED === $entry[1]) { // removed + $fromRange++; + } + } + + if (false === $hunkCapture) { + return; + } + + // we end here when cutoff (commonLineThreshold) was not reached, but we were capturing a hunk, + // do not render hunk till end automatically because the number of context lines might be less than the commonLineThreshold + + $contextStartOffset = $hunkCapture - $this->contextLines < 0 + ? $hunkCapture + : $this->contextLines; + + // prevent trying to write out more common lines than there are in the diff _and_ + // do not write more than configured through the context lines + $contextEndOffset = min($sameCount, $this->contextLines); + + $fromRange -= $sameCount; + $toRange -= $sameCount; + + $this->writeHunk( + $diff, + $hunkCapture - $contextStartOffset, + $i - $sameCount + $contextEndOffset + 1, + $fromStart - $contextStartOffset, + $fromRange + $contextStartOffset + $contextEndOffset, + $toStart - $contextStartOffset, + $toRange + $contextStartOffset + $contextEndOffset, + $output + ); + } + + private function writeHunk( + array $diff, + int $diffStartIndex, + int $diffEndIndex, + int $fromStart, + int $fromRange, + int $toStart, + int $toRange, + $output + ): void { + fwrite($output, '@@ -' . $fromStart); + + if (!$this->collapseRanges || 1 !== $fromRange) { + fwrite($output, ',' . $fromRange); + } + + fwrite($output, ' +' . $toStart); + + if (!$this->collapseRanges || 1 !== $toRange) { + fwrite($output, ',' . $toRange); + } + + fwrite($output, " @@\n"); + + for ($i = $diffStartIndex; $i < $diffEndIndex; $i++) { + if ($diff[$i][1] === Differ::ADDED) { + $this->changed = true; + fwrite($output, '+' . $diff[$i][0]); + } elseif ($diff[$i][1] === Differ::REMOVED) { + $this->changed = true; + fwrite($output, '-' . $diff[$i][0]); + } elseif ($diff[$i][1] === Differ::OLD) { + fwrite($output, ' ' . $diff[$i][0]); + } elseif ($diff[$i][1] === Differ::NO_LINE_END_EOF_WARNING) { + $this->changed = true; + fwrite($output, $diff[$i][0]); + } + //} elseif ($diff[$i][1] === Differ::DIFF_LINE_END_WARNING) { // custom comment inserted by PHPUnit/diff package + // skip + //} else { + // unknown/invalid + //} + } + } + + private function assertString(array $options, string $option): void + { + if (!is_string($options[$option])) { + throw new ConfigurationException($option, 'a string', $options[$option]); + } + } + + private function assertStringOrNull(array $options, string $option): void + { + if (null !== $options[$option] && !is_string($options[$option])) { + throw new ConfigurationException($option, 'a string or ', $options[$option]); + } + } +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/Output/UnifiedDiffOutputBuilder.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/Output/UnifiedDiffOutputBuilder.php new file mode 100644 index 00000000..1483b3af --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/Output/UnifiedDiffOutputBuilder.php @@ -0,0 +1,258 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff\Output; + +use function array_splice; +use function count; +use function fclose; +use function fopen; +use function fwrite; +use function max; +use function min; +use function str_ends_with; +use function stream_get_contents; +use function strlen; +use function substr; +use SebastianBergmann\Diff\Differ; + +/** + * Builds a diff string representation in unified diff format in chunks. + */ +final class UnifiedDiffOutputBuilder extends AbstractChunkOutputBuilder +{ + private bool $collapseRanges = true; + private int $commonLineThreshold = 6; + + /** + * @psalm-var positive-int + */ + private int $contextLines = 3; + private string $header; + private bool $addLineNumbers; + + public function __construct(string $header = "--- Original\n+++ New\n", bool $addLineNumbers = false) + { + $this->header = $header; + $this->addLineNumbers = $addLineNumbers; + } + + public function getDiff(array $diff): string + { + $buffer = fopen('php://memory', 'r+b'); + + if ('' !== $this->header) { + fwrite($buffer, $this->header); + + if (!str_ends_with($this->header, "\n")) { + fwrite($buffer, "\n"); + } + } + + if (0 !== count($diff)) { + $this->writeDiffHunks($buffer, $diff); + } + + $diff = stream_get_contents($buffer, -1, 0); + + fclose($buffer); + + // If the diff is non-empty and last char is not a linebreak: add it. + // This might happen when both the `from` and `to` do not have a trailing linebreak + $last = substr($diff, -1); + + return 0 !== strlen($diff) && "\n" !== $last && "\r" !== $last + ? $diff . "\n" + : $diff; + } + + private function writeDiffHunks($output, array $diff): void + { + // detect "No newline at end of file" and insert into `$diff` if needed + + $upperLimit = count($diff); + + if (0 === $diff[$upperLimit - 1][1]) { + $lc = substr($diff[$upperLimit - 1][0], -1); + + if ("\n" !== $lc) { + array_splice($diff, $upperLimit, 0, [["\n\\ No newline at end of file\n", Differ::NO_LINE_END_EOF_WARNING]]); + } + } else { + // search back for the last `+` and `-` line, + // check if it has trailing linebreak, else add a warning under it + $toFind = [1 => true, 2 => true]; + + for ($i = $upperLimit - 1; $i >= 0; $i--) { + if (isset($toFind[$diff[$i][1]])) { + unset($toFind[$diff[$i][1]]); + $lc = substr($diff[$i][0], -1); + + if ("\n" !== $lc) { + array_splice($diff, $i + 1, 0, [["\n\\ No newline at end of file\n", Differ::NO_LINE_END_EOF_WARNING]]); + } + + if (!count($toFind)) { + break; + } + } + } + } + + // write hunks to output buffer + + $cutOff = max($this->commonLineThreshold, $this->contextLines); + $hunkCapture = false; + $sameCount = $toRange = $fromRange = 0; + $toStart = $fromStart = 1; + $i = 0; + + /** @var int $i */ + foreach ($diff as $i => $entry) { + if (0 === $entry[1]) { // same + if (false === $hunkCapture) { + $fromStart++; + $toStart++; + + continue; + } + + $sameCount++; + $toRange++; + $fromRange++; + + if ($sameCount === $cutOff) { + $contextStartOffset = ($hunkCapture - $this->contextLines) < 0 + ? $hunkCapture + : $this->contextLines; + + // note: $contextEndOffset = $this->contextLines; + // + // because we never go beyond the end of the diff. + // with the cutoff/contextlines here the follow is never true; + // + // if ($i - $cutOff + $this->contextLines + 1 > \count($diff)) { + // $contextEndOffset = count($diff) - 1; + // } + // + // ; that would be true for a trailing incomplete hunk case which is dealt with after this loop + + $this->writeHunk( + $diff, + $hunkCapture - $contextStartOffset, + $i - $cutOff + $this->contextLines + 1, + $fromStart - $contextStartOffset, + $fromRange - $cutOff + $contextStartOffset + $this->contextLines, + $toStart - $contextStartOffset, + $toRange - $cutOff + $contextStartOffset + $this->contextLines, + $output + ); + + $fromStart += $fromRange; + $toStart += $toRange; + + $hunkCapture = false; + $sameCount = $toRange = $fromRange = 0; + } + + continue; + } + + $sameCount = 0; + + if ($entry[1] === Differ::NO_LINE_END_EOF_WARNING) { + continue; + } + + if (false === $hunkCapture) { + $hunkCapture = $i; + } + + if (Differ::ADDED === $entry[1]) { + $toRange++; + } + + if (Differ::REMOVED === $entry[1]) { + $fromRange++; + } + } + + if (false === $hunkCapture) { + return; + } + + // we end here when cutoff (commonLineThreshold) was not reached, but we were capturing a hunk, + // do not render hunk till end automatically because the number of context lines might be less than the commonLineThreshold + + $contextStartOffset = $hunkCapture - $this->contextLines < 0 + ? $hunkCapture + : $this->contextLines; + + // prevent trying to write out more common lines than there are in the diff _and_ + // do not write more than configured through the context lines + $contextEndOffset = min($sameCount, $this->contextLines); + + $fromRange -= $sameCount; + $toRange -= $sameCount; + + $this->writeHunk( + $diff, + $hunkCapture - $contextStartOffset, + $i - $sameCount + $contextEndOffset + 1, + $fromStart - $contextStartOffset, + $fromRange + $contextStartOffset + $contextEndOffset, + $toStart - $contextStartOffset, + $toRange + $contextStartOffset + $contextEndOffset, + $output + ); + } + + private function writeHunk( + array $diff, + int $diffStartIndex, + int $diffEndIndex, + int $fromStart, + int $fromRange, + int $toStart, + int $toRange, + $output + ): void { + if ($this->addLineNumbers) { + fwrite($output, '@@ -' . $fromStart); + + if (!$this->collapseRanges || 1 !== $fromRange) { + fwrite($output, ',' . $fromRange); + } + + fwrite($output, ' +' . $toStart); + + if (!$this->collapseRanges || 1 !== $toRange) { + fwrite($output, ',' . $toRange); + } + + fwrite($output, " @@\n"); + } else { + fwrite($output, "@@ @@\n"); + } + + for ($i = $diffStartIndex; $i < $diffEndIndex; $i++) { + if ($diff[$i][1] === Differ::ADDED) { + fwrite($output, '+' . $diff[$i][0]); + } elseif ($diff[$i][1] === Differ::REMOVED) { + fwrite($output, '-' . $diff[$i][0]); + } elseif ($diff[$i][1] === Differ::OLD) { + fwrite($output, ' ' . $diff[$i][0]); + } elseif ($diff[$i][1] === Differ::NO_LINE_END_EOF_WARNING) { + fwrite($output, "\n"); // $diff[$i][0] + } else { /* Not changed (old) Differ::OLD or Warning Differ::DIFF_LINE_END_WARNING */ + fwrite($output, ' ' . $diff[$i][0]); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/Parser.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/Parser.php new file mode 100644 index 00000000..698b815c --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/Parser.php @@ -0,0 +1,108 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +use function array_pop; +use function count; +use function max; +use function preg_match; +use function preg_split; + +/** + * Unified diff parser. + */ +final class Parser +{ + /** + * @return Diff[] + */ + public function parse(string $string): array + { + $lines = preg_split('(\r\n|\r|\n)', $string); + + if (!empty($lines) && $lines[count($lines) - 1] === '') { + array_pop($lines); + } + + $lineCount = count($lines); + $diffs = []; + $diff = null; + $collected = []; + + for ($i = 0; $i < $lineCount; $i++) { + if (preg_match('#^---\h+"?(?P[^\\v\\t"]+)#', $lines[$i], $fromMatch) && + preg_match('#^\\+\\+\\+\\h+"?(?P[^\\v\\t"]+)#', $lines[$i + 1], $toMatch)) { + if ($diff !== null) { + $this->parseFileDiff($diff, $collected); + + $diffs[] = $diff; + $collected = []; + } + + $diff = new Diff($fromMatch['file'], $toMatch['file']); + + $i++; + } else { + if (preg_match('/^(?:diff --git |index [\da-f.]+|[+-]{3} [ab])/', $lines[$i])) { + continue; + } + + $collected[] = $lines[$i]; + } + } + + if ($diff !== null && count($collected)) { + $this->parseFileDiff($diff, $collected); + + $diffs[] = $diff; + } + + return $diffs; + } + + private function parseFileDiff(Diff $diff, array $lines): void + { + $chunks = []; + $chunk = null; + $diffLines = []; + + foreach ($lines as $line) { + if (preg_match('/^@@\s+-(?P\d+)(?:,\s*(?P\d+))?\s+\+(?P\d+)(?:,\s*(?P\d+))?\s+@@/', $line, $match, PREG_UNMATCHED_AS_NULL)) { + $chunk = new Chunk( + (int) $match['start'], + isset($match['startrange']) ? max(0, (int) $match['startrange']) : 1, + (int) $match['end'], + isset($match['endrange']) ? max(0, (int) $match['endrange']) : 1 + ); + + $chunks[] = $chunk; + $diffLines = []; + + continue; + } + + if (preg_match('/^(?P[+ -])?(?P.*)/', $line, $match)) { + $type = Line::UNCHANGED; + + if ($match['type'] === '+') { + $type = Line::ADDED; + } elseif ($match['type'] === '-') { + $type = Line::REMOVED; + } + + $diffLines[] = new Line($type, $match['line']); + + $chunk?->setLines($diffLines); + } + } + + $diff->setChunks($chunks); + } +} diff --git a/tools/php-cs-fixer/vendor/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php b/tools/php-cs-fixer/vendor/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php new file mode 100644 index 00000000..93b76288 --- /dev/null +++ b/tools/php-cs-fixer/vendor/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +use function array_reverse; +use function count; +use function max; +use SplFixedArray; + +final class TimeEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator +{ + /** + * @inheritDoc + */ + public function calculate(array $from, array $to): array + { + $common = []; + $fromLength = count($from); + $toLength = count($to); + $width = $fromLength + 1; + $matrix = new SplFixedArray($width * ($toLength + 1)); + + for ($i = 0; $i <= $fromLength; $i++) { + $matrix[$i] = 0; + } + + for ($j = 0; $j <= $toLength; $j++) { + $matrix[$j * $width] = 0; + } + + for ($i = 1; $i <= $fromLength; $i++) { + for ($j = 1; $j <= $toLength; $j++) { + $o = ($j * $width) + $i; + + // don't use max() to avoid function call overhead + $firstOrLast = $from[$i - 1] === $to[$j - 1] ? $matrix[$o - $width - 1] + 1 : 0; + + if ($matrix[$o - 1] > $matrix[$o - $width]) { + if ($firstOrLast > $matrix[$o - 1]) { + $matrix[$o] = $firstOrLast; + } else { + $matrix[$o] = $matrix[$o - 1]; + } + } else { + if ($firstOrLast > $matrix[$o - $width]) { + $matrix[$o] = $firstOrLast; + } else { + $matrix[$o] = $matrix[$o - $width]; + } + } + } + } + + $i = $fromLength; + $j = $toLength; + + while ($i > 0 && $j > 0) { + if ($from[$i - 1] === $to[$j - 1]) { + $common[] = $from[$i - 1]; + $i--; + $j--; + } else { + $o = ($j * $width) + $i; + + if ($matrix[$o - $width] > $matrix[$o - 1]) { + $j--; + } else { + $i--; + } + } + } + + return array_reverse($common); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Application.php b/tools/php-cs-fixer/vendor/symfony/console/Application.php new file mode 100644 index 00000000..07cc6d67 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Application.php @@ -0,0 +1,1284 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Command\CompleteCommand; +use Symfony\Component\Console\Command\DumpCompletionCommand; +use Symfony\Component\Console\Command\HelpCommand; +use Symfony\Component\Console\Command\LazyCommand; +use Symfony\Component\Console\Command\ListCommand; +use Symfony\Component\Console\Command\SignalableCommandInterface; +use Symfony\Component\Console\CommandLoader\CommandLoaderInterface; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Completion\Suggestion; +use Symfony\Component\Console\Event\ConsoleCommandEvent; +use Symfony\Component\Console\Event\ConsoleErrorEvent; +use Symfony\Component\Console\Event\ConsoleSignalEvent; +use Symfony\Component\Console\Event\ConsoleTerminateEvent; +use Symfony\Component\Console\Exception\CommandNotFoundException; +use Symfony\Component\Console\Exception\ExceptionInterface; +use Symfony\Component\Console\Exception\LogicException; +use Symfony\Component\Console\Exception\NamespaceNotFoundException; +use Symfony\Component\Console\Exception\RuntimeException; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Helper\DebugFormatterHelper; +use Symfony\Component\Console\Helper\DescriptorHelper; +use Symfony\Component\Console\Helper\FormatterHelper; +use Symfony\Component\Console\Helper\Helper; +use Symfony\Component\Console\Helper\HelperSet; +use Symfony\Component\Console\Helper\ProcessHelper; +use Symfony\Component\Console\Helper\QuestionHelper; +use Symfony\Component\Console\Input\ArgvInput; +use Symfony\Component\Console\Input\ArrayInput; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputAwareInterface; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\ConsoleOutput; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\SignalRegistry\SignalRegistry; +use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\ErrorHandler\ErrorHandler; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; +use Symfony\Contracts\Service\ResetInterface; + +/** + * An Application is the container for a collection of commands. + * + * It is the main entry point of a Console application. + * + * This class is optimized for a standard CLI environment. + * + * Usage: + * + * $app = new Application('myapp', '1.0 (stable)'); + * $app->add(new SimpleCommand()); + * $app->run(); + * + * @author Fabien Potencier + */ +class Application implements ResetInterface +{ + private array $commands = []; + private bool $wantHelps = false; + private ?Command $runningCommand = null; + private string $name; + private string $version; + private ?CommandLoaderInterface $commandLoader = null; + private bool $catchExceptions = true; + private bool $catchErrors = false; + private bool $autoExit = true; + private InputDefinition $definition; + private HelperSet $helperSet; + private ?EventDispatcherInterface $dispatcher = null; + private Terminal $terminal; + private string $defaultCommand; + private bool $singleCommand = false; + private bool $initialized = false; + private ?SignalRegistry $signalRegistry = null; + private array $signalsToDispatchEvent = []; + + public function __construct(string $name = 'UNKNOWN', string $version = 'UNKNOWN') + { + $this->name = $name; + $this->version = $version; + $this->terminal = new Terminal(); + $this->defaultCommand = 'list'; + if (\defined('SIGINT') && SignalRegistry::isSupported()) { + $this->signalRegistry = new SignalRegistry(); + $this->signalsToDispatchEvent = [\SIGINT, \SIGTERM, \SIGUSR1, \SIGUSR2]; + } + } + + /** + * @final + */ + public function setDispatcher(EventDispatcherInterface $dispatcher): void + { + $this->dispatcher = $dispatcher; + } + + public function setCommandLoader(CommandLoaderInterface $commandLoader): void + { + $this->commandLoader = $commandLoader; + } + + public function getSignalRegistry(): SignalRegistry + { + if (!$this->signalRegistry) { + throw new RuntimeException('Signals are not supported. Make sure that the "pcntl" extension is installed and that "pcntl_*" functions are not disabled by your php.ini\'s "disable_functions" directive.'); + } + + return $this->signalRegistry; + } + + public function setSignalsToDispatchEvent(int ...$signalsToDispatchEvent): void + { + $this->signalsToDispatchEvent = $signalsToDispatchEvent; + } + + /** + * Runs the current application. + * + * @return int 0 if everything went fine, or an error code + * + * @throws \Exception When running fails. Bypass this when {@link setCatchExceptions()}. + */ + public function run(InputInterface $input = null, OutputInterface $output = null): int + { + if (\function_exists('putenv')) { + @putenv('LINES='.$this->terminal->getHeight()); + @putenv('COLUMNS='.$this->terminal->getWidth()); + } + + $input ??= new ArgvInput(); + $output ??= new ConsoleOutput(); + + $renderException = function (\Throwable $e) use ($output) { + if ($output instanceof ConsoleOutputInterface) { + $this->renderThrowable($e, $output->getErrorOutput()); + } else { + $this->renderThrowable($e, $output); + } + }; + if ($phpHandler = set_exception_handler($renderException)) { + restore_exception_handler(); + if (!\is_array($phpHandler) || !$phpHandler[0] instanceof ErrorHandler) { + $errorHandler = true; + } elseif ($errorHandler = $phpHandler[0]->setExceptionHandler($renderException)) { + $phpHandler[0]->setExceptionHandler($errorHandler); + } + } + + $this->configureIO($input, $output); + + try { + $exitCode = $this->doRun($input, $output); + } catch (\Throwable $e) { + if ($e instanceof \Exception && !$this->catchExceptions) { + throw $e; + } + if (!$e instanceof \Exception && !$this->catchErrors) { + throw $e; + } + + $renderException($e); + + $exitCode = $e->getCode(); + if (is_numeric($exitCode)) { + $exitCode = (int) $exitCode; + if ($exitCode <= 0) { + $exitCode = 1; + } + } else { + $exitCode = 1; + } + } finally { + // if the exception handler changed, keep it + // otherwise, unregister $renderException + if (!$phpHandler) { + if (set_exception_handler($renderException) === $renderException) { + restore_exception_handler(); + } + restore_exception_handler(); + } elseif (!$errorHandler) { + $finalHandler = $phpHandler[0]->setExceptionHandler(null); + if ($finalHandler !== $renderException) { + $phpHandler[0]->setExceptionHandler($finalHandler); + } + } + } + + if ($this->autoExit) { + if ($exitCode > 255) { + $exitCode = 255; + } + + exit($exitCode); + } + + return $exitCode; + } + + /** + * Runs the current application. + * + * @return int 0 if everything went fine, or an error code + */ + public function doRun(InputInterface $input, OutputInterface $output): int + { + if (true === $input->hasParameterOption(['--version', '-V'], true)) { + $output->writeln($this->getLongVersion()); + + return 0; + } + + try { + // Makes ArgvInput::getFirstArgument() able to distinguish an option from an argument. + $input->bind($this->getDefinition()); + } catch (ExceptionInterface) { + // Errors must be ignored, full binding/validation happens later when the command is known. + } + + $name = $this->getCommandName($input); + if (true === $input->hasParameterOption(['--help', '-h'], true)) { + if (!$name) { + $name = 'help'; + $input = new ArrayInput(['command_name' => $this->defaultCommand]); + } else { + $this->wantHelps = true; + } + } + + if (!$name) { + $name = $this->defaultCommand; + $definition = $this->getDefinition(); + $definition->setArguments(array_merge( + $definition->getArguments(), + [ + 'command' => new InputArgument('command', InputArgument::OPTIONAL, $definition->getArgument('command')->getDescription(), $name), + ] + )); + } + + try { + $this->runningCommand = null; + // the command name MUST be the first element of the input + $command = $this->find($name); + } catch (\Throwable $e) { + if (($e instanceof CommandNotFoundException && !$e instanceof NamespaceNotFoundException) && 1 === \count($alternatives = $e->getAlternatives()) && $input->isInteractive()) { + $alternative = $alternatives[0]; + + $style = new SymfonyStyle($input, $output); + $output->writeln(''); + $formattedBlock = (new FormatterHelper())->formatBlock(sprintf('Command "%s" is not defined.', $name), 'error', true); + $output->writeln($formattedBlock); + if (!$style->confirm(sprintf('Do you want to run "%s" instead? ', $alternative), false)) { + if (null !== $this->dispatcher) { + $event = new ConsoleErrorEvent($input, $output, $e); + $this->dispatcher->dispatch($event, ConsoleEvents::ERROR); + + return $event->getExitCode(); + } + + return 1; + } + + $command = $this->find($alternative); + } else { + if (null !== $this->dispatcher) { + $event = new ConsoleErrorEvent($input, $output, $e); + $this->dispatcher->dispatch($event, ConsoleEvents::ERROR); + + if (0 === $event->getExitCode()) { + return 0; + } + + $e = $event->getError(); + } + + try { + if ($e instanceof CommandNotFoundException && $namespace = $this->findNamespace($name)) { + $helper = new DescriptorHelper(); + $helper->describe($output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output, $this, [ + 'format' => 'txt', + 'raw_text' => false, + 'namespace' => $namespace, + 'short' => false, + ]); + + return isset($event) ? $event->getExitCode() : 1; + } + + throw $e; + } catch (NamespaceNotFoundException) { + throw $e; + } + } + } + + if ($command instanceof LazyCommand) { + $command = $command->getCommand(); + } + + $this->runningCommand = $command; + $exitCode = $this->doRunCommand($command, $input, $output); + $this->runningCommand = null; + + return $exitCode; + } + + public function reset(): void + { + } + + public function setHelperSet(HelperSet $helperSet): void + { + $this->helperSet = $helperSet; + } + + /** + * Get the helper set associated with the command. + */ + public function getHelperSet(): HelperSet + { + return $this->helperSet ??= $this->getDefaultHelperSet(); + } + + public function setDefinition(InputDefinition $definition): void + { + $this->definition = $definition; + } + + /** + * Gets the InputDefinition related to this Application. + */ + public function getDefinition(): InputDefinition + { + $this->definition ??= $this->getDefaultInputDefinition(); + + if ($this->singleCommand) { + $inputDefinition = $this->definition; + $inputDefinition->setArguments(); + + return $inputDefinition; + } + + return $this->definition; + } + + /** + * Adds suggestions to $suggestions for the current completion input (e.g. option or argument). + */ + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + if ( + CompletionInput::TYPE_ARGUMENT_VALUE === $input->getCompletionType() + && 'command' === $input->getCompletionName() + ) { + foreach ($this->all() as $name => $command) { + // skip hidden commands and aliased commands as they already get added below + if ($command->isHidden() || $command->getName() !== $name) { + continue; + } + $suggestions->suggestValue(new Suggestion($command->getName(), $command->getDescription())); + foreach ($command->getAliases() as $name) { + $suggestions->suggestValue(new Suggestion($name, $command->getDescription())); + } + } + + return; + } + + if (CompletionInput::TYPE_OPTION_NAME === $input->getCompletionType()) { + $suggestions->suggestOptions($this->getDefinition()->getOptions()); + + return; + } + } + + /** + * Gets the help message. + */ + public function getHelp(): string + { + return $this->getLongVersion(); + } + + /** + * Gets whether to catch exceptions or not during commands execution. + */ + public function areExceptionsCaught(): bool + { + return $this->catchExceptions; + } + + /** + * Sets whether to catch exceptions or not during commands execution. + */ + public function setCatchExceptions(bool $boolean): void + { + $this->catchExceptions = $boolean; + } + + /** + * Sets whether to catch errors or not during commands execution. + */ + public function setCatchErrors(bool $catchErrors = true): void + { + $this->catchErrors = $catchErrors; + } + + /** + * Gets whether to automatically exit after a command execution or not. + */ + public function isAutoExitEnabled(): bool + { + return $this->autoExit; + } + + /** + * Sets whether to automatically exit after a command execution or not. + */ + public function setAutoExit(bool $boolean): void + { + $this->autoExit = $boolean; + } + + /** + * Gets the name of the application. + */ + public function getName(): string + { + return $this->name; + } + + /** + * Sets the application name. + */ + public function setName(string $name): void + { + $this->name = $name; + } + + /** + * Gets the application version. + */ + public function getVersion(): string + { + return $this->version; + } + + /** + * Sets the application version. + */ + public function setVersion(string $version): void + { + $this->version = $version; + } + + /** + * Returns the long version of the application. + */ + public function getLongVersion(): string + { + if ('UNKNOWN' !== $this->getName()) { + if ('UNKNOWN' !== $this->getVersion()) { + return sprintf('%s %s', $this->getName(), $this->getVersion()); + } + + return $this->getName(); + } + + return 'Console Tool'; + } + + /** + * Registers a new command. + */ + public function register(string $name): Command + { + return $this->add(new Command($name)); + } + + /** + * Adds an array of command objects. + * + * If a Command is not enabled it will not be added. + * + * @param Command[] $commands An array of commands + */ + public function addCommands(array $commands): void + { + foreach ($commands as $command) { + $this->add($command); + } + } + + /** + * Adds a command object. + * + * If a command with the same name already exists, it will be overridden. + * If the command is not enabled it will not be added. + */ + public function add(Command $command): ?Command + { + $this->init(); + + $command->setApplication($this); + + if (!$command->isEnabled()) { + $command->setApplication(null); + + return null; + } + + if (!$command instanceof LazyCommand) { + // Will throw if the command is not correctly initialized. + $command->getDefinition(); + } + + if (!$command->getName()) { + throw new LogicException(sprintf('The command defined in "%s" cannot have an empty name.', get_debug_type($command))); + } + + $this->commands[$command->getName()] = $command; + + foreach ($command->getAliases() as $alias) { + $this->commands[$alias] = $command; + } + + return $command; + } + + /** + * Returns a registered command by name or alias. + * + * @throws CommandNotFoundException When given command name does not exist + */ + public function get(string $name): Command + { + $this->init(); + + if (!$this->has($name)) { + throw new CommandNotFoundException(sprintf('The command "%s" does not exist.', $name)); + } + + // When the command has a different name than the one used at the command loader level + if (!isset($this->commands[$name])) { + throw new CommandNotFoundException(sprintf('The "%s" command cannot be found because it is registered under multiple names. Make sure you don\'t set a different name via constructor or "setName()".', $name)); + } + + $command = $this->commands[$name]; + + if ($this->wantHelps) { + $this->wantHelps = false; + + $helpCommand = $this->get('help'); + $helpCommand->setCommand($command); + + return $helpCommand; + } + + return $command; + } + + /** + * Returns true if the command exists, false otherwise. + */ + public function has(string $name): bool + { + $this->init(); + + return isset($this->commands[$name]) || ($this->commandLoader?->has($name) && $this->add($this->commandLoader->get($name))); + } + + /** + * Returns an array of all unique namespaces used by currently registered commands. + * + * It does not return the global namespace which always exists. + * + * @return string[] + */ + public function getNamespaces(): array + { + $namespaces = []; + foreach ($this->all() as $command) { + if ($command->isHidden()) { + continue; + } + + $namespaces[] = $this->extractAllNamespaces($command->getName()); + + foreach ($command->getAliases() as $alias) { + $namespaces[] = $this->extractAllNamespaces($alias); + } + } + + return array_values(array_unique(array_filter(array_merge([], ...$namespaces)))); + } + + /** + * Finds a registered namespace by a name or an abbreviation. + * + * @throws NamespaceNotFoundException When namespace is incorrect or ambiguous + */ + public function findNamespace(string $namespace): string + { + $allNamespaces = $this->getNamespaces(); + $expr = implode('[^:]*:', array_map('preg_quote', explode(':', $namespace))).'[^:]*'; + $namespaces = preg_grep('{^'.$expr.'}', $allNamespaces); + + if (empty($namespaces)) { + $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace); + + if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) { + if (1 == \count($alternatives)) { + $message .= "\n\nDid you mean this?\n "; + } else { + $message .= "\n\nDid you mean one of these?\n "; + } + + $message .= implode("\n ", $alternatives); + } + + throw new NamespaceNotFoundException($message, $alternatives); + } + + $exact = \in_array($namespace, $namespaces, true); + if (\count($namespaces) > 1 && !$exact) { + throw new NamespaceNotFoundException(sprintf("The namespace \"%s\" is ambiguous.\nDid you mean one of these?\n%s.", $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))), array_values($namespaces)); + } + + return $exact ? $namespace : reset($namespaces); + } + + /** + * Finds a command by name or alias. + * + * Contrary to get, this command tries to find the best + * match if you give it an abbreviation of a name or alias. + * + * @throws CommandNotFoundException When command name is incorrect or ambiguous + */ + public function find(string $name): Command + { + $this->init(); + + $aliases = []; + + foreach ($this->commands as $command) { + foreach ($command->getAliases() as $alias) { + if (!$this->has($alias)) { + $this->commands[$alias] = $command; + } + } + } + + if ($this->has($name)) { + return $this->get($name); + } + + $allCommands = $this->commandLoader ? array_merge($this->commandLoader->getNames(), array_keys($this->commands)) : array_keys($this->commands); + $expr = implode('[^:]*:', array_map('preg_quote', explode(':', $name))).'[^:]*'; + $commands = preg_grep('{^'.$expr.'}', $allCommands); + + if (empty($commands)) { + $commands = preg_grep('{^'.$expr.'}i', $allCommands); + } + + // if no commands matched or we just matched namespaces + if (empty($commands) || \count(preg_grep('{^'.$expr.'$}i', $commands)) < 1) { + if (false !== $pos = strrpos($name, ':')) { + // check if a namespace exists and contains commands + $this->findNamespace(substr($name, 0, $pos)); + } + + $message = sprintf('Command "%s" is not defined.', $name); + + if ($alternatives = $this->findAlternatives($name, $allCommands)) { + // remove hidden commands + $alternatives = array_filter($alternatives, fn ($name) => !$this->get($name)->isHidden()); + + if (1 == \count($alternatives)) { + $message .= "\n\nDid you mean this?\n "; + } else { + $message .= "\n\nDid you mean one of these?\n "; + } + $message .= implode("\n ", $alternatives); + } + + throw new CommandNotFoundException($message, array_values($alternatives)); + } + + // filter out aliases for commands which are already on the list + if (\count($commands) > 1) { + $commandList = $this->commandLoader ? array_merge(array_flip($this->commandLoader->getNames()), $this->commands) : $this->commands; + $commands = array_unique(array_filter($commands, function ($nameOrAlias) use (&$commandList, $commands, &$aliases) { + if (!$commandList[$nameOrAlias] instanceof Command) { + $commandList[$nameOrAlias] = $this->commandLoader->get($nameOrAlias); + } + + $commandName = $commandList[$nameOrAlias]->getName(); + + $aliases[$nameOrAlias] = $commandName; + + return $commandName === $nameOrAlias || !\in_array($commandName, $commands); + })); + } + + if (\count($commands) > 1) { + $usableWidth = $this->terminal->getWidth() - 10; + $abbrevs = array_values($commands); + $maxLen = 0; + foreach ($abbrevs as $abbrev) { + $maxLen = max(Helper::width($abbrev), $maxLen); + } + $abbrevs = array_map(function ($cmd) use ($commandList, $usableWidth, $maxLen, &$commands) { + if ($commandList[$cmd]->isHidden()) { + unset($commands[array_search($cmd, $commands)]); + + return false; + } + + $abbrev = str_pad($cmd, $maxLen, ' ').' '.$commandList[$cmd]->getDescription(); + + return Helper::width($abbrev) > $usableWidth ? Helper::substr($abbrev, 0, $usableWidth - 3).'...' : $abbrev; + }, array_values($commands)); + + if (\count($commands) > 1) { + $suggestions = $this->getAbbreviationSuggestions(array_filter($abbrevs)); + + throw new CommandNotFoundException(sprintf("Command \"%s\" is ambiguous.\nDid you mean one of these?\n%s.", $name, $suggestions), array_values($commands)); + } + } + + $command = $this->get(reset($commands)); + + if ($command->isHidden()) { + throw new CommandNotFoundException(sprintf('The command "%s" does not exist.', $name)); + } + + return $command; + } + + /** + * Gets the commands (registered in the given namespace if provided). + * + * The array keys are the full names and the values the command instances. + * + * @return Command[] + */ + public function all(string $namespace = null): array + { + $this->init(); + + if (null === $namespace) { + if (!$this->commandLoader) { + return $this->commands; + } + + $commands = $this->commands; + foreach ($this->commandLoader->getNames() as $name) { + if (!isset($commands[$name]) && $this->has($name)) { + $commands[$name] = $this->get($name); + } + } + + return $commands; + } + + $commands = []; + foreach ($this->commands as $name => $command) { + if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) { + $commands[$name] = $command; + } + } + + if ($this->commandLoader) { + foreach ($this->commandLoader->getNames() as $name) { + if (!isset($commands[$name]) && $namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1) && $this->has($name)) { + $commands[$name] = $this->get($name); + } + } + } + + return $commands; + } + + /** + * Returns an array of possible abbreviations given a set of names. + * + * @return string[][] + */ + public static function getAbbreviations(array $names): array + { + $abbrevs = []; + foreach ($names as $name) { + for ($len = \strlen($name); $len > 0; --$len) { + $abbrev = substr($name, 0, $len); + $abbrevs[$abbrev][] = $name; + } + } + + return $abbrevs; + } + + public function renderThrowable(\Throwable $e, OutputInterface $output): void + { + $output->writeln('', OutputInterface::VERBOSITY_QUIET); + + $this->doRenderThrowable($e, $output); + + if (null !== $this->runningCommand) { + $output->writeln(sprintf('%s', OutputFormatter::escape(sprintf($this->runningCommand->getSynopsis(), $this->getName()))), OutputInterface::VERBOSITY_QUIET); + $output->writeln('', OutputInterface::VERBOSITY_QUIET); + } + } + + protected function doRenderThrowable(\Throwable $e, OutputInterface $output): void + { + do { + $message = trim($e->getMessage()); + if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { + $class = get_debug_type($e); + $title = sprintf(' [%s%s] ', $class, 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : ''); + $len = Helper::width($title); + } else { + $len = 0; + } + + if (str_contains($message, "@anonymous\0")) { + $message = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', fn ($m) => class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0], $message); + } + + $width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : \PHP_INT_MAX; + $lines = []; + foreach ('' !== $message ? preg_split('/\r?\n/', $message) : [] as $line) { + foreach ($this->splitStringByWidth($line, $width - 4) as $line) { + // pre-format lines to get the right string length + $lineLength = Helper::width($line) + 4; + $lines[] = [$line, $lineLength]; + + $len = max($lineLength, $len); + } + } + + $messages = []; + if (!$e instanceof ExceptionInterface || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { + $messages[] = sprintf('%s', OutputFormatter::escape(sprintf('In %s line %s:', basename($e->getFile()) ?: 'n/a', $e->getLine() ?: 'n/a'))); + } + $messages[] = $emptyLine = sprintf('%s', str_repeat(' ', $len)); + if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { + $messages[] = sprintf('%s%s', $title, str_repeat(' ', max(0, $len - Helper::width($title)))); + } + foreach ($lines as $line) { + $messages[] = sprintf(' %s %s', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1])); + } + $messages[] = $emptyLine; + $messages[] = ''; + + $output->writeln($messages, OutputInterface::VERBOSITY_QUIET); + + if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { + $output->writeln('Exception trace:', OutputInterface::VERBOSITY_QUIET); + + // exception related properties + $trace = $e->getTrace(); + + array_unshift($trace, [ + 'function' => '', + 'file' => $e->getFile() ?: 'n/a', + 'line' => $e->getLine() ?: 'n/a', + 'args' => [], + ]); + + for ($i = 0, $count = \count($trace); $i < $count; ++$i) { + $class = $trace[$i]['class'] ?? ''; + $type = $trace[$i]['type'] ?? ''; + $function = $trace[$i]['function'] ?? ''; + $file = $trace[$i]['file'] ?? 'n/a'; + $line = $trace[$i]['line'] ?? 'n/a'; + + $output->writeln(sprintf(' %s%s at %s:%s', $class, $function ? $type.$function.'()' : '', $file, $line), OutputInterface::VERBOSITY_QUIET); + } + + $output->writeln('', OutputInterface::VERBOSITY_QUIET); + } + } while ($e = $e->getPrevious()); + } + + /** + * Configures the input and output instances based on the user arguments and options. + */ + protected function configureIO(InputInterface $input, OutputInterface $output): void + { + if (true === $input->hasParameterOption(['--ansi'], true)) { + $output->setDecorated(true); + } elseif (true === $input->hasParameterOption(['--no-ansi'], true)) { + $output->setDecorated(false); + } + + if (true === $input->hasParameterOption(['--no-interaction', '-n'], true)) { + $input->setInteractive(false); + } + + switch ($shellVerbosity = (int) getenv('SHELL_VERBOSITY')) { + case -1: + $output->setVerbosity(OutputInterface::VERBOSITY_QUIET); + break; + case 1: + $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE); + break; + case 2: + $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE); + break; + case 3: + $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG); + break; + default: + $shellVerbosity = 0; + break; + } + + if (true === $input->hasParameterOption(['--quiet', '-q'], true)) { + $output->setVerbosity(OutputInterface::VERBOSITY_QUIET); + $shellVerbosity = -1; + } else { + if ($input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || 3 === $input->getParameterOption('--verbose', false, true)) { + $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG); + $shellVerbosity = 3; + } elseif ($input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || 2 === $input->getParameterOption('--verbose', false, true)) { + $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE); + $shellVerbosity = 2; + } elseif ($input->hasParameterOption('-v', true) || $input->hasParameterOption('--verbose=1', true) || $input->hasParameterOption('--verbose', true) || $input->getParameterOption('--verbose', false, true)) { + $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE); + $shellVerbosity = 1; + } + } + + if (-1 === $shellVerbosity) { + $input->setInteractive(false); + } + + if (\function_exists('putenv')) { + @putenv('SHELL_VERBOSITY='.$shellVerbosity); + } + $_ENV['SHELL_VERBOSITY'] = $shellVerbosity; + $_SERVER['SHELL_VERBOSITY'] = $shellVerbosity; + } + + /** + * Runs the current command. + * + * If an event dispatcher has been attached to the application, + * events are also dispatched during the life-cycle of the command. + * + * @return int 0 if everything went fine, or an error code + */ + protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output): int + { + foreach ($command->getHelperSet() as $helper) { + if ($helper instanceof InputAwareInterface) { + $helper->setInput($input); + } + } + + $commandSignals = $command instanceof SignalableCommandInterface ? $command->getSubscribedSignals() : []; + if ($commandSignals || $this->dispatcher && $this->signalsToDispatchEvent) { + if (!$this->signalRegistry) { + throw new RuntimeException('Unable to subscribe to signal events. Make sure that the "pcntl" extension is installed and that "pcntl_*" functions are not disabled by your php.ini\'s "disable_functions" directive.'); + } + + if (Terminal::hasSttyAvailable()) { + $sttyMode = shell_exec('stty -g'); + + foreach ([\SIGINT, \SIGTERM] as $signal) { + $this->signalRegistry->register($signal, static fn () => shell_exec('stty '.$sttyMode)); + } + } + + if ($this->dispatcher) { + // We register application signals, so that we can dispatch the event + foreach ($this->signalsToDispatchEvent as $signal) { + $event = new ConsoleSignalEvent($command, $input, $output, $signal); + + $this->signalRegistry->register($signal, function ($signal) use ($event, $command, $commandSignals) { + $this->dispatcher->dispatch($event, ConsoleEvents::SIGNAL); + $exitCode = $event->getExitCode(); + + // If the command is signalable, we call the handleSignal() method + if (\in_array($signal, $commandSignals, true)) { + $exitCode = $command->handleSignal($signal, $exitCode); + } + + if (false !== $exitCode) { + $event = new ConsoleTerminateEvent($command, $event->getInput(), $event->getOutput(), $exitCode, $signal); + $this->dispatcher->dispatch($event, ConsoleEvents::TERMINATE); + + exit($event->getExitCode()); + } + }); + } + + // then we register command signals, but not if already handled after the dispatcher + $commandSignals = array_diff($commandSignals, $this->signalsToDispatchEvent); + } + + foreach ($commandSignals as $signal) { + $this->signalRegistry->register($signal, function (int $signal) use ($command): void { + if (false !== $exitCode = $command->handleSignal($signal)) { + exit($exitCode); + } + }); + } + } + + if (null === $this->dispatcher) { + return $command->run($input, $output); + } + + // bind before the console.command event, so the listeners have access to input options/arguments + try { + $command->mergeApplicationDefinition(); + $input->bind($command->getDefinition()); + } catch (ExceptionInterface) { + // ignore invalid options/arguments for now, to allow the event listeners to customize the InputDefinition + } + + $event = new ConsoleCommandEvent($command, $input, $output); + $e = null; + + try { + $this->dispatcher->dispatch($event, ConsoleEvents::COMMAND); + + if ($event->commandShouldRun()) { + $exitCode = $command->run($input, $output); + } else { + $exitCode = ConsoleCommandEvent::RETURN_CODE_DISABLED; + } + } catch (\Throwable $e) { + $event = new ConsoleErrorEvent($input, $output, $e, $command); + $this->dispatcher->dispatch($event, ConsoleEvents::ERROR); + $e = $event->getError(); + + if (0 === $exitCode = $event->getExitCode()) { + $e = null; + } + } + + $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode); + $this->dispatcher->dispatch($event, ConsoleEvents::TERMINATE); + + if (null !== $e) { + throw $e; + } + + return $event->getExitCode(); + } + + /** + * Gets the name of the command based on input. + */ + protected function getCommandName(InputInterface $input): ?string + { + return $this->singleCommand ? $this->defaultCommand : $input->getFirstArgument(); + } + + /** + * Gets the default input definition. + */ + protected function getDefaultInputDefinition(): InputDefinition + { + return new InputDefinition([ + new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'), + new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display help for the given command. When no command is given display help for the '.$this->defaultCommand.' command'), + new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message'), + new InputOption('--verbose', '-v|vv|vvv', InputOption::VALUE_NONE, 'Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug'), + new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'), + new InputOption('--ansi', '', InputOption::VALUE_NEGATABLE, 'Force (or disable --no-ansi) ANSI output', null), + new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'), + ]); + } + + /** + * Gets the default commands that should always be available. + * + * @return Command[] + */ + protected function getDefaultCommands(): array + { + return [new HelpCommand(), new ListCommand(), new CompleteCommand(), new DumpCompletionCommand()]; + } + + /** + * Gets the default helper set with the helpers that should always be available. + */ + protected function getDefaultHelperSet(): HelperSet + { + return new HelperSet([ + new FormatterHelper(), + new DebugFormatterHelper(), + new ProcessHelper(), + new QuestionHelper(), + ]); + } + + /** + * Returns abbreviated suggestions in string format. + */ + private function getAbbreviationSuggestions(array $abbrevs): string + { + return ' '.implode("\n ", $abbrevs); + } + + /** + * Returns the namespace part of the command name. + * + * This method is not part of public API and should not be used directly. + */ + public function extractNamespace(string $name, int $limit = null): string + { + $parts = explode(':', $name, -1); + + return implode(':', null === $limit ? $parts : \array_slice($parts, 0, $limit)); + } + + /** + * Finds alternative of $name among $collection, + * if nothing is found in $collection, try in $abbrevs. + * + * @return string[] + */ + private function findAlternatives(string $name, iterable $collection): array + { + $threshold = 1e3; + $alternatives = []; + + $collectionParts = []; + foreach ($collection as $item) { + $collectionParts[$item] = explode(':', $item); + } + + foreach (explode(':', $name) as $i => $subname) { + foreach ($collectionParts as $collectionName => $parts) { + $exists = isset($alternatives[$collectionName]); + if (!isset($parts[$i]) && $exists) { + $alternatives[$collectionName] += $threshold; + continue; + } elseif (!isset($parts[$i])) { + continue; + } + + $lev = levenshtein($subname, $parts[$i]); + if ($lev <= \strlen($subname) / 3 || '' !== $subname && str_contains($parts[$i], $subname)) { + $alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev; + } elseif ($exists) { + $alternatives[$collectionName] += $threshold; + } + } + } + + foreach ($collection as $item) { + $lev = levenshtein($name, $item); + if ($lev <= \strlen($name) / 3 || str_contains($item, $name)) { + $alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev; + } + } + + $alternatives = array_filter($alternatives, fn ($lev) => $lev < 2 * $threshold); + ksort($alternatives, \SORT_NATURAL | \SORT_FLAG_CASE); + + return array_keys($alternatives); + } + + /** + * Sets the default Command name. + * + * @return $this + */ + public function setDefaultCommand(string $commandName, bool $isSingleCommand = false): static + { + $this->defaultCommand = explode('|', ltrim($commandName, '|'))[0]; + + if ($isSingleCommand) { + // Ensure the command exist + $this->find($commandName); + + $this->singleCommand = true; + } + + return $this; + } + + /** + * @internal + */ + public function isSingleCommand(): bool + { + return $this->singleCommand; + } + + private function splitStringByWidth(string $string, int $width): array + { + // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly. + // additionally, array_slice() is not enough as some character has doubled width. + // we need a function to split string not by character count but by string width + if (false === $encoding = mb_detect_encoding($string, null, true)) { + return str_split($string, $width); + } + + $utf8String = mb_convert_encoding($string, 'utf8', $encoding); + $lines = []; + $line = ''; + + $offset = 0; + while (preg_match('/.{1,10000}/u', $utf8String, $m, 0, $offset)) { + $offset += \strlen($m[0]); + + foreach (preg_split('//u', $m[0]) as $char) { + // test if $char could be appended to current line + if (mb_strwidth($line.$char, 'utf8') <= $width) { + $line .= $char; + continue; + } + // if not, push current line to array and make new line + $lines[] = str_pad($line, $width); + $line = $char; + } + } + + $lines[] = \count($lines) ? str_pad($line, $width) : $line; + + mb_convert_variables($encoding, 'utf8', $lines); + + return $lines; + } + + /** + * Returns all namespaces of the command name. + * + * @return string[] + */ + private function extractAllNamespaces(string $name): array + { + // -1 as third argument is needed to skip the command short name when exploding + $parts = explode(':', $name, -1); + $namespaces = []; + + foreach ($parts as $part) { + if (\count($namespaces)) { + $namespaces[] = end($namespaces).':'.$part; + } else { + $namespaces[] = $part; + } + } + + return $namespaces; + } + + private function init(): void + { + if ($this->initialized) { + return; + } + $this->initialized = true; + + foreach ($this->getDefaultCommands() as $command) { + $this->add($command); + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Attribute/AsCommand.php b/tools/php-cs-fixer/vendor/symfony/console/Attribute/AsCommand.php new file mode 100644 index 00000000..b337f548 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Attribute/AsCommand.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Attribute; + +/** + * Service tag to autoconfigure commands. + */ +#[\Attribute(\Attribute::TARGET_CLASS)] +class AsCommand +{ + public function __construct( + public string $name, + public ?string $description = null, + array $aliases = [], + bool $hidden = false, + ) { + if (!$hidden && !$aliases) { + return; + } + + $name = explode('|', $name); + $name = array_merge($name, $aliases); + + if ($hidden && '' !== $name[0]) { + array_unshift($name, ''); + } + + $this->name = implode('|', $name); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/CHANGELOG.md b/tools/php-cs-fixer/vendor/symfony/console/CHANGELOG.md new file mode 100644 index 00000000..0ff71d2f --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/CHANGELOG.md @@ -0,0 +1,269 @@ +CHANGELOG +========= + +7.0 +--- + + * Add method `__toString()` to `InputInterface` + * Remove `Command::$defaultName` and `Command::$defaultDescription`, use the `AsCommand` attribute instead + * Require explicit argument when calling `*Command::setApplication()`, `*FormatterStyle::setForeground/setBackground()`, `Helper::setHelpSet()`, `Input*::setDefault()` and `Question::setAutocompleterCallback/setValidator()` + * Remove `StringInput::REGEX_STRING` + +6.4 +--- + + * Add `SignalMap` to map signal value to its name + * Multi-line text in vertical tables is aligned properly + * The application can also catch errors with `Application::setCatchErrors(true)` + * Add `RunCommandMessage` and `RunCommandMessageHandler` + * Dispatch `ConsoleTerminateEvent` after an exit on signal handling and add `ConsoleTerminateEvent::getInterruptingSignal()` + +6.3 +--- + + * Add support for choosing exit code while handling signal, or to not exit at all + * Add `ProgressBar::setPlaceholderFormatter` to set a placeholder attached to a instance, instead of being global. + * Add `ReStructuredTextDescriptor` + +6.2 +--- + + * Improve truecolor terminal detection in some cases + * Add support for 256 color terminals (conversion from Ansi24 to Ansi8 if terminal is capable of it) + * Deprecate calling `*Command::setApplication()`, `*FormatterStyle::setForeground/setBackground()`, `Helper::setHelpSet()`, `Input*::setDefault()`, `Question::setAutocompleterCallback/setValidator()`without any arguments + * Change the signature of `OutputFormatterStyleInterface::setForeground/setBackground()` to `setForeground/setBackground(?string)` + * Change the signature of `HelperInterface::setHelperSet()` to `setHelperSet(?HelperSet)` + +6.1 +--- + + * Add support to display table vertically when calling setVertical() + * Add method `__toString()` to `InputInterface` + * Added `OutputWrapper` to prevent truncated URL in `SymfonyStyle::createBlock`. + * Deprecate `Command::$defaultName` and `Command::$defaultDescription`, use the `AsCommand` attribute instead + * Add suggested values for arguments and options in input definition, for input completion + * Add `$resumeAt` parameter to `ProgressBar#start()`, so that one can easily 'resume' progress on longer tasks, and still get accurate `getEstimate()` and `getRemaining()` results. + +6.0 +--- + + * `Command::setHidden()` has a default value (`true`) for `$hidden` parameter and is final + * Remove `Helper::strlen()`, use `Helper::width()` instead + * Remove `Helper::strlenWithoutDecoration()`, use `Helper::removeDecoration()` instead + * `AddConsoleCommandPass` can not be configured anymore + * Remove `HelperSet::setCommand()` and `getCommand()` without replacement + +5.4 +--- + + * Add `TesterTrait::assertCommandIsSuccessful()` to test command + * Deprecate `HelperSet::setCommand()` and `getCommand()` without replacement + +5.3 +--- + + * Add `GithubActionReporter` to render annotations in a Github Action + * Add `InputOption::VALUE_NEGATABLE` flag to handle `--foo`/`--no-foo` options + * Add the `Command::$defaultDescription` static property and the `description` attribute + on the `console.command` tag to allow the `list` command to instantiate commands lazily + * Add option `--short` to the `list` command + * Add support for bright colors + * Add `#[AsCommand]` attribute for declaring commands on PHP 8 + * Add `Helper::width()` and `Helper::length()` + * The `--ansi` and `--no-ansi` options now default to `null`. + +5.2.0 +----- + + * Added `SingleCommandApplication::setAutoExit()` to allow testing via `CommandTester` + * added support for multiline responses to questions through `Question::setMultiline()` + and `Question::isMultiline()` + * Added `SignalRegistry` class to stack signals handlers + * Added support for signals: + * Added `Application::getSignalRegistry()` and `Application::setSignalsToDispatchEvent()` methods + * Added `SignalableCommandInterface` interface + * Added `TableCellStyle` class to customize table cell + * Removed `php ` prefix invocation from help messages. + +5.1.0 +----- + + * `Command::setHidden()` is final since Symfony 5.1 + * Add `SingleCommandApplication` + * Add `Cursor` class + +5.0.0 +----- + + * removed support for finding hidden commands using an abbreviation, use the full name instead + * removed `TableStyle::setCrossingChar()` method in favor of `TableStyle::setDefaultCrossingChar()` + * removed `TableStyle::setHorizontalBorderChar()` method in favor of `TableStyle::setDefaultCrossingChars()` + * removed `TableStyle::getHorizontalBorderChar()` method in favor of `TableStyle::getBorderChars()` + * removed `TableStyle::setVerticalBorderChar()` method in favor of `TableStyle::setVerticalBorderChars()` + * removed `TableStyle::getVerticalBorderChar()` method in favor of `TableStyle::getBorderChars()` + * removed support for returning `null` from `Command::execute()`, return `0` instead + * `ProcessHelper::run()` accepts only `array|Symfony\Component\Process\Process` for its `command` argument + * `Application::setDispatcher` accepts only `Symfony\Contracts\EventDispatcher\EventDispatcherInterface` + for its `dispatcher` argument + * renamed `Application::renderException()` and `Application::doRenderException()` + to `renderThrowable()` and `doRenderThrowable()` respectively. + +4.4.0 +----- + + * deprecated finding hidden commands using an abbreviation, use the full name instead + * added `Question::setTrimmable` default to true to allow the answer to be trimmed + * added method `minSecondsBetweenRedraws()` and `maxSecondsBetweenRedraws()` on `ProgressBar` + * `Application` implements `ResetInterface` + * marked all dispatched event classes as `@final` + * added support for displaying table horizontally + * deprecated returning `null` from `Command::execute()`, return `0` instead + * Deprecated the `Application::renderException()` and `Application::doRenderException()` methods, + use `renderThrowable()` and `doRenderThrowable()` instead. + * added support for the `NO_COLOR` env var (https://no-color.org/) + +4.3.0 +----- + + * added support for hyperlinks + * added `ProgressBar::iterate()` method that simplify updating the progress bar when iterating + * added `Question::setAutocompleterCallback()` to provide a callback function + that dynamically generates suggestions as the user types + +4.2.0 +----- + + * allowed passing commands as `[$process, 'ENV_VAR' => 'value']` to + `ProcessHelper::run()` to pass environment variables + * deprecated passing a command as a string to `ProcessHelper::run()`, + pass it the command as an array of its arguments instead + * made the `ProcessHelper` class final + * added `WrappableOutputFormatterInterface::formatAndWrap()` (implemented in `OutputFormatter`) + * added `capture_stderr_separately` option to `CommandTester::execute()` + +4.1.0 +----- + + * added option to run suggested command if command is not found and only 1 alternative is available + * added option to modify console output and print multiple modifiable sections + * added support for iterable messages in output `write` and `writeln` methods + +4.0.0 +----- + + * `OutputFormatter` throws an exception when unknown options are used + * removed `QuestionHelper::setInputStream()/getInputStream()` + * removed `Application::getTerminalWidth()/getTerminalHeight()` and + `Application::setTerminalDimensions()/getTerminalDimensions()` + * removed `ConsoleExceptionEvent` + * removed `ConsoleEvents::EXCEPTION` + +3.4.0 +----- + + * added `SHELL_VERBOSITY` env var to control verbosity + * added `CommandLoaderInterface`, `FactoryCommandLoader` and PSR-11 + `ContainerCommandLoader` for commands lazy-loading + * added a case-insensitive command name matching fallback + * added static `Command::$defaultName/getDefaultName()`, allowing for + commands to be registered at compile time in the application command loader. + Setting the `$defaultName` property avoids the need for filling the `command` + attribute on the `console.command` tag when using `AddConsoleCommandPass`. + +3.3.0 +----- + + * added `ExceptionListener` + * added `AddConsoleCommandPass` (originally in FrameworkBundle) + * [BC BREAK] `Input::getOption()` no longer returns the default value for options + with value optional explicitly passed empty + * added console.error event to catch exceptions thrown by other listeners + * deprecated console.exception event in favor of console.error + * added ability to handle `CommandNotFoundException` through the + `console.error` event + * deprecated default validation in `SymfonyQuestionHelper::ask` + +3.2.0 +------ + + * added `setInputs()` method to CommandTester for ease testing of commands expecting inputs + * added `setStream()` and `getStream()` methods to Input (implement StreamableInputInterface) + * added StreamableInputInterface + * added LockableTrait + +3.1.0 +----- + + * added truncate method to FormatterHelper + * added setColumnWidth(s) method to Table + +2.8.3 +----- + + * remove readline support from the question helper as it caused issues + +2.8.0 +----- + + * use readline for user input in the question helper when available to allow + the use of arrow keys + +2.6.0 +----- + + * added a Process helper + * added a DebugFormatter helper + +2.5.0 +----- + + * deprecated the dialog helper (use the question helper instead) + * deprecated TableHelper in favor of Table + * deprecated ProgressHelper in favor of ProgressBar + * added ConsoleLogger + * added a question helper + * added a way to set the process name of a command + * added a way to set a default command instead of `ListCommand` + +2.4.0 +----- + + * added a way to force terminal dimensions + * added a convenient method to detect verbosity level + * [BC BREAK] made descriptors use output instead of returning a string + +2.3.0 +----- + + * added multiselect support to the select dialog helper + * added Table Helper for tabular data rendering + * added support for events in `Application` + * added a way to normalize EOLs in `ApplicationTester::getDisplay()` and `CommandTester::getDisplay()` + * added a way to set the progress bar progress via the `setCurrent` method + * added support for multiple InputOption shortcuts, written as `'-a|-b|-c'` + * added two additional verbosity levels, VERBOSITY_VERY_VERBOSE and VERBOSITY_DEBUG + +2.2.0 +----- + + * added support for colorization on Windows via ConEmu + * add a method to Dialog Helper to ask for a question and hide the response + * added support for interactive selections in console (DialogHelper::select()) + * added support for autocompletion as you type in Dialog Helper + +2.1.0 +----- + + * added ConsoleOutputInterface + * added the possibility to disable a command (Command::isEnabled()) + * added suggestions when a command does not exist + * added a --raw option to the list command + * added support for STDERR in the console output class (errors are now sent + to STDERR) + * made the defaults (helper set, commands, input definition) in Application + more easily customizable + * added support for the shell even if readline is not available + * added support for process isolation in Symfony shell via + `--process-isolation` switch + * added support for `--`, which disables options parsing after that point + (tokens will be parsed as arguments) diff --git a/tools/php-cs-fixer/vendor/symfony/console/CI/GithubActionReporter.php b/tools/php-cs-fixer/vendor/symfony/console/CI/GithubActionReporter.php new file mode 100644 index 00000000..7e556546 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/CI/GithubActionReporter.php @@ -0,0 +1,99 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\CI; + +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Utility class for Github actions. + * + * @author Maxime Steinhausser + */ +class GithubActionReporter +{ + private OutputInterface $output; + + /** + * @see https://github.com/actions/toolkit/blob/5e5e1b7aacba68a53836a34db4a288c3c1c1585b/packages/core/src/command.ts#L80-L85 + */ + private const ESCAPED_DATA = [ + '%' => '%25', + "\r" => '%0D', + "\n" => '%0A', + ]; + + /** + * @see https://github.com/actions/toolkit/blob/5e5e1b7aacba68a53836a34db4a288c3c1c1585b/packages/core/src/command.ts#L87-L94 + */ + private const ESCAPED_PROPERTIES = [ + '%' => '%25', + "\r" => '%0D', + "\n" => '%0A', + ':' => '%3A', + ',' => '%2C', + ]; + + public function __construct(OutputInterface $output) + { + $this->output = $output; + } + + public static function isGithubActionEnvironment(): bool + { + return false !== getenv('GITHUB_ACTIONS'); + } + + /** + * Output an error using the Github annotations format. + * + * @see https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#setting-an-error-message + */ + public function error(string $message, string $file = null, int $line = null, int $col = null): void + { + $this->log('error', $message, $file, $line, $col); + } + + /** + * Output a warning using the Github annotations format. + * + * @see https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#setting-a-warning-message + */ + public function warning(string $message, string $file = null, int $line = null, int $col = null): void + { + $this->log('warning', $message, $file, $line, $col); + } + + /** + * Output a debug log using the Github annotations format. + * + * @see https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#setting-a-debug-message + */ + public function debug(string $message, string $file = null, int $line = null, int $col = null): void + { + $this->log('debug', $message, $file, $line, $col); + } + + private function log(string $type, string $message, string $file = null, int $line = null, int $col = null): void + { + // Some values must be encoded. + $message = strtr($message, self::ESCAPED_DATA); + + if (!$file) { + // No file provided, output the message solely: + $this->output->writeln(sprintf('::%s::%s', $type, $message)); + + return; + } + + $this->output->writeln(sprintf('::%s file=%s,line=%s,col=%s::%s', $type, strtr($file, self::ESCAPED_PROPERTIES), strtr($line ?? 1, self::ESCAPED_PROPERTIES), strtr($col ?? 0, self::ESCAPED_PROPERTIES), $message)); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Color.php b/tools/php-cs-fixer/vendor/symfony/console/Color.php new file mode 100644 index 00000000..60ed046a --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Color.php @@ -0,0 +1,133 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console; + +use Symfony\Component\Console\Exception\InvalidArgumentException; + +/** + * @author Fabien Potencier + */ +final class Color +{ + private const COLORS = [ + 'black' => 0, + 'red' => 1, + 'green' => 2, + 'yellow' => 3, + 'blue' => 4, + 'magenta' => 5, + 'cyan' => 6, + 'white' => 7, + 'default' => 9, + ]; + + private const BRIGHT_COLORS = [ + 'gray' => 0, + 'bright-red' => 1, + 'bright-green' => 2, + 'bright-yellow' => 3, + 'bright-blue' => 4, + 'bright-magenta' => 5, + 'bright-cyan' => 6, + 'bright-white' => 7, + ]; + + private const AVAILABLE_OPTIONS = [ + 'bold' => ['set' => 1, 'unset' => 22], + 'underscore' => ['set' => 4, 'unset' => 24], + 'blink' => ['set' => 5, 'unset' => 25], + 'reverse' => ['set' => 7, 'unset' => 27], + 'conceal' => ['set' => 8, 'unset' => 28], + ]; + + private string $foreground; + private string $background; + private array $options = []; + + public function __construct(string $foreground = '', string $background = '', array $options = []) + { + $this->foreground = $this->parseColor($foreground); + $this->background = $this->parseColor($background, true); + + foreach ($options as $option) { + if (!isset(self::AVAILABLE_OPTIONS[$option])) { + throw new InvalidArgumentException(sprintf('Invalid option specified: "%s". Expected one of (%s).', $option, implode(', ', array_keys(self::AVAILABLE_OPTIONS)))); + } + + $this->options[$option] = self::AVAILABLE_OPTIONS[$option]; + } + } + + public function apply(string $text): string + { + return $this->set().$text.$this->unset(); + } + + public function set(): string + { + $setCodes = []; + if ('' !== $this->foreground) { + $setCodes[] = $this->foreground; + } + if ('' !== $this->background) { + $setCodes[] = $this->background; + } + foreach ($this->options as $option) { + $setCodes[] = $option['set']; + } + if (0 === \count($setCodes)) { + return ''; + } + + return sprintf("\033[%sm", implode(';', $setCodes)); + } + + public function unset(): string + { + $unsetCodes = []; + if ('' !== $this->foreground) { + $unsetCodes[] = 39; + } + if ('' !== $this->background) { + $unsetCodes[] = 49; + } + foreach ($this->options as $option) { + $unsetCodes[] = $option['unset']; + } + if (0 === \count($unsetCodes)) { + return ''; + } + + return sprintf("\033[%sm", implode(';', $unsetCodes)); + } + + private function parseColor(string $color, bool $background = false): string + { + if ('' === $color) { + return ''; + } + + if ('#' === $color[0]) { + return ($background ? '4' : '3').Terminal::getColorMode()->convertFromHexToAnsiColorCode($color); + } + + if (isset(self::COLORS[$color])) { + return ($background ? '4' : '3').self::COLORS[$color]; + } + + if (isset(self::BRIGHT_COLORS[$color])) { + return ($background ? '10' : '9').self::BRIGHT_COLORS[$color]; + } + + throw new InvalidArgumentException(sprintf('Invalid "%s" color; expected one of (%s).', $color, implode(', ', array_merge(array_keys(self::COLORS), array_keys(self::BRIGHT_COLORS))))); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Command/Command.php b/tools/php-cs-fixer/vendor/symfony/console/Command/Command.php new file mode 100644 index 00000000..c4989177 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Command/Command.php @@ -0,0 +1,668 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Completion\Suggestion; +use Symfony\Component\Console\Exception\ExceptionInterface; +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\LogicException; +use Symfony\Component\Console\Helper\HelperInterface; +use Symfony\Component\Console\Helper\HelperSet; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Base class for all commands. + * + * @author Fabien Potencier + */ +class Command +{ + // see https://tldp.org/LDP/abs/html/exitcodes.html + public const SUCCESS = 0; + public const FAILURE = 1; + public const INVALID = 2; + + private ?Application $application = null; + private ?string $name = null; + private ?string $processTitle = null; + private array $aliases = []; + private InputDefinition $definition; + private bool $hidden = false; + private string $help = ''; + private string $description = ''; + private ?InputDefinition $fullDefinition = null; + private bool $ignoreValidationErrors = false; + private ?\Closure $code = null; + private array $synopsis = []; + private array $usages = []; + private ?HelperSet $helperSet = null; + + public static function getDefaultName(): ?string + { + if ($attribute = (new \ReflectionClass(static::class))->getAttributes(AsCommand::class)) { + return $attribute[0]->newInstance()->name; + } + + return null; + } + + public static function getDefaultDescription(): ?string + { + if ($attribute = (new \ReflectionClass(static::class))->getAttributes(AsCommand::class)) { + return $attribute[0]->newInstance()->description; + } + + return null; + } + + /** + * @param string|null $name The name of the command; passing null means it must be set in configure() + * + * @throws LogicException When the command name is empty + */ + public function __construct(string $name = null) + { + $this->definition = new InputDefinition(); + + if (null === $name && null !== $name = static::getDefaultName()) { + $aliases = explode('|', $name); + + if ('' === $name = array_shift($aliases)) { + $this->setHidden(true); + $name = array_shift($aliases); + } + + $this->setAliases($aliases); + } + + if (null !== $name) { + $this->setName($name); + } + + if ('' === $this->description) { + $this->setDescription(static::getDefaultDescription() ?? ''); + } + + $this->configure(); + } + + /** + * Ignores validation errors. + * + * This is mainly useful for the help command. + */ + public function ignoreValidationErrors(): void + { + $this->ignoreValidationErrors = true; + } + + public function setApplication(?Application $application): void + { + $this->application = $application; + if ($application) { + $this->setHelperSet($application->getHelperSet()); + } else { + $this->helperSet = null; + } + + $this->fullDefinition = null; + } + + public function setHelperSet(HelperSet $helperSet): void + { + $this->helperSet = $helperSet; + } + + /** + * Gets the helper set. + */ + public function getHelperSet(): ?HelperSet + { + return $this->helperSet; + } + + /** + * Gets the application instance for this command. + */ + public function getApplication(): ?Application + { + return $this->application; + } + + /** + * Checks whether the command is enabled or not in the current environment. + * + * Override this to check for x or y and return false if the command cannot + * run properly under the current conditions. + */ + public function isEnabled(): bool + { + return true; + } + + /** + * Configures the current command. + * + * @return void + */ + protected function configure() + { + } + + /** + * Executes the current command. + * + * This method is not abstract because you can use this class + * as a concrete class. In this case, instead of defining the + * execute() method, you set the code to execute by passing + * a Closure to the setCode() method. + * + * @return int 0 if everything went fine, or an exit code + * + * @throws LogicException When this abstract method is not implemented + * + * @see setCode() + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + throw new LogicException('You must override the execute() method in the concrete command class.'); + } + + /** + * Interacts with the user. + * + * This method is executed before the InputDefinition is validated. + * This means that this is the only place where the command can + * interactively ask for values of missing required arguments. + * + * @return void + */ + protected function interact(InputInterface $input, OutputInterface $output) + { + } + + /** + * Initializes the command after the input has been bound and before the input + * is validated. + * + * This is mainly useful when a lot of commands extends one main command + * where some things need to be initialized based on the input arguments and options. + * + * @see InputInterface::bind() + * @see InputInterface::validate() + * + * @return void + */ + protected function initialize(InputInterface $input, OutputInterface $output) + { + } + + /** + * Runs the command. + * + * The code to execute is either defined directly with the + * setCode() method or by overriding the execute() method + * in a sub-class. + * + * @return int The command exit code + * + * @throws ExceptionInterface When input binding fails. Bypass this by calling {@link ignoreValidationErrors()}. + * + * @see setCode() + * @see execute() + */ + public function run(InputInterface $input, OutputInterface $output): int + { + // add the application arguments and options + $this->mergeApplicationDefinition(); + + // bind the input against the command specific arguments/options + try { + $input->bind($this->getDefinition()); + } catch (ExceptionInterface $e) { + if (!$this->ignoreValidationErrors) { + throw $e; + } + } + + $this->initialize($input, $output); + + if (null !== $this->processTitle) { + if (\function_exists('cli_set_process_title')) { + if (!@cli_set_process_title($this->processTitle)) { + if ('Darwin' === \PHP_OS) { + $output->writeln('Running "cli_set_process_title" as an unprivileged user is not supported on MacOS.', OutputInterface::VERBOSITY_VERY_VERBOSE); + } else { + cli_set_process_title($this->processTitle); + } + } + } elseif (\function_exists('setproctitle')) { + setproctitle($this->processTitle); + } elseif (OutputInterface::VERBOSITY_VERY_VERBOSE === $output->getVerbosity()) { + $output->writeln('Install the proctitle PECL to be able to change the process title.'); + } + } + + if ($input->isInteractive()) { + $this->interact($input, $output); + } + + // The command name argument is often omitted when a command is executed directly with its run() method. + // It would fail the validation if we didn't make sure the command argument is present, + // since it's required by the application. + if ($input->hasArgument('command') && null === $input->getArgument('command')) { + $input->setArgument('command', $this->getName()); + } + + $input->validate(); + + if ($this->code) { + $statusCode = ($this->code)($input, $output); + } else { + $statusCode = $this->execute($input, $output); + + if (!\is_int($statusCode)) { + throw new \TypeError(sprintf('Return value of "%s::execute()" must be of the type int, "%s" returned.', static::class, get_debug_type($statusCode))); + } + } + + return is_numeric($statusCode) ? (int) $statusCode : 0; + } + + /** + * Adds suggestions to $suggestions for the current completion input (e.g. option or argument). + */ + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + $definition = $this->getDefinition(); + if (CompletionInput::TYPE_OPTION_VALUE === $input->getCompletionType() && $definition->hasOption($input->getCompletionName())) { + $definition->getOption($input->getCompletionName())->complete($input, $suggestions); + } elseif (CompletionInput::TYPE_ARGUMENT_VALUE === $input->getCompletionType() && $definition->hasArgument($input->getCompletionName())) { + $definition->getArgument($input->getCompletionName())->complete($input, $suggestions); + } + } + + /** + * Sets the code to execute when running this command. + * + * If this method is used, it overrides the code defined + * in the execute() method. + * + * @param callable $code A callable(InputInterface $input, OutputInterface $output) + * + * @return $this + * + * @throws InvalidArgumentException + * + * @see execute() + */ + public function setCode(callable $code): static + { + if ($code instanceof \Closure) { + $r = new \ReflectionFunction($code); + if (null === $r->getClosureThis()) { + set_error_handler(static function () {}); + try { + if ($c = \Closure::bind($code, $this)) { + $code = $c; + } + } finally { + restore_error_handler(); + } + } + } else { + $code = $code(...); + } + + $this->code = $code; + + return $this; + } + + /** + * Merges the application definition with the command definition. + * + * This method is not part of public API and should not be used directly. + * + * @param bool $mergeArgs Whether to merge or not the Application definition arguments to Command definition arguments + * + * @internal + */ + public function mergeApplicationDefinition(bool $mergeArgs = true): void + { + if (null === $this->application) { + return; + } + + $this->fullDefinition = new InputDefinition(); + $this->fullDefinition->setOptions($this->definition->getOptions()); + $this->fullDefinition->addOptions($this->application->getDefinition()->getOptions()); + + if ($mergeArgs) { + $this->fullDefinition->setArguments($this->application->getDefinition()->getArguments()); + $this->fullDefinition->addArguments($this->definition->getArguments()); + } else { + $this->fullDefinition->setArguments($this->definition->getArguments()); + } + } + + /** + * Sets an array of argument and option instances. + * + * @return $this + */ + public function setDefinition(array|InputDefinition $definition): static + { + if ($definition instanceof InputDefinition) { + $this->definition = $definition; + } else { + $this->definition->setDefinition($definition); + } + + $this->fullDefinition = null; + + return $this; + } + + /** + * Gets the InputDefinition attached to this Command. + */ + public function getDefinition(): InputDefinition + { + return $this->fullDefinition ?? $this->getNativeDefinition(); + } + + /** + * Gets the InputDefinition to be used to create representations of this Command. + * + * Can be overridden to provide the original command representation when it would otherwise + * be changed by merging with the application InputDefinition. + * + * This method is not part of public API and should not be used directly. + */ + public function getNativeDefinition(): InputDefinition + { + return $this->definition ?? throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', static::class)); + } + + /** + * Adds an argument. + * + * @param $mode The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL + * @param $default The default value (for InputArgument::OPTIONAL mode only) + * @param array|\Closure(CompletionInput,CompletionSuggestions):list $suggestedValues The values used for input completion + * + * @return $this + * + * @throws InvalidArgumentException When argument mode is not valid + */ + public function addArgument(string $name, int $mode = null, string $description = '', mixed $default = null, array|\Closure $suggestedValues = []): static + { + $this->definition->addArgument(new InputArgument($name, $mode, $description, $default, $suggestedValues)); + $this->fullDefinition?->addArgument(new InputArgument($name, $mode, $description, $default, $suggestedValues)); + + return $this; + } + + /** + * Adds an option. + * + * @param $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts + * @param $mode The option mode: One of the InputOption::VALUE_* constants + * @param $default The default value (must be null for InputOption::VALUE_NONE) + * @param array|\Closure(CompletionInput,CompletionSuggestions):list $suggestedValues The values used for input completion + * + * @return $this + * + * @throws InvalidArgumentException If option mode is invalid or incompatible + */ + public function addOption(string $name, string|array $shortcut = null, int $mode = null, string $description = '', mixed $default = null, array|\Closure $suggestedValues = []): static + { + $this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default, $suggestedValues)); + $this->fullDefinition?->addOption(new InputOption($name, $shortcut, $mode, $description, $default, $suggestedValues)); + + return $this; + } + + /** + * Sets the name of the command. + * + * This method can set both the namespace and the name if + * you separate them by a colon (:) + * + * $command->setName('foo:bar'); + * + * @return $this + * + * @throws InvalidArgumentException When the name is invalid + */ + public function setName(string $name): static + { + $this->validateName($name); + + $this->name = $name; + + return $this; + } + + /** + * Sets the process title of the command. + * + * This feature should be used only when creating a long process command, + * like a daemon. + * + * @return $this + */ + public function setProcessTitle(string $title): static + { + $this->processTitle = $title; + + return $this; + } + + /** + * Returns the command name. + */ + public function getName(): ?string + { + return $this->name; + } + + /** + * @param bool $hidden Whether or not the command should be hidden from the list of commands + * + * @return $this + */ + public function setHidden(bool $hidden = true): static + { + $this->hidden = $hidden; + + return $this; + } + + /** + * @return bool whether the command should be publicly shown or not + */ + public function isHidden(): bool + { + return $this->hidden; + } + + /** + * Sets the description for the command. + * + * @return $this + */ + public function setDescription(string $description): static + { + $this->description = $description; + + return $this; + } + + /** + * Returns the description for the command. + */ + public function getDescription(): string + { + return $this->description; + } + + /** + * Sets the help for the command. + * + * @return $this + */ + public function setHelp(string $help): static + { + $this->help = $help; + + return $this; + } + + /** + * Returns the help for the command. + */ + public function getHelp(): string + { + return $this->help; + } + + /** + * Returns the processed help for the command replacing the %command.name% and + * %command.full_name% patterns with the real values dynamically. + */ + public function getProcessedHelp(): string + { + $name = $this->name; + $isSingleCommand = $this->application?->isSingleCommand(); + + $placeholders = [ + '%command.name%', + '%command.full_name%', + ]; + $replacements = [ + $name, + $isSingleCommand ? $_SERVER['PHP_SELF'] : $_SERVER['PHP_SELF'].' '.$name, + ]; + + return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription()); + } + + /** + * Sets the aliases for the command. + * + * @param string[] $aliases An array of aliases for the command + * + * @return $this + * + * @throws InvalidArgumentException When an alias is invalid + */ + public function setAliases(iterable $aliases): static + { + $list = []; + + foreach ($aliases as $alias) { + $this->validateName($alias); + $list[] = $alias; + } + + $this->aliases = \is_array($aliases) ? $aliases : $list; + + return $this; + } + + /** + * Returns the aliases for the command. + */ + public function getAliases(): array + { + return $this->aliases; + } + + /** + * Returns the synopsis for the command. + * + * @param bool $short Whether to show the short version of the synopsis (with options folded) or not + */ + public function getSynopsis(bool $short = false): string + { + $key = $short ? 'short' : 'long'; + + if (!isset($this->synopsis[$key])) { + $this->synopsis[$key] = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis($short))); + } + + return $this->synopsis[$key]; + } + + /** + * Add a command usage example, it'll be prefixed with the command name. + * + * @return $this + */ + public function addUsage(string $usage): static + { + if (!str_starts_with($usage, $this->name)) { + $usage = sprintf('%s %s', $this->name, $usage); + } + + $this->usages[] = $usage; + + return $this; + } + + /** + * Returns alternative usages of the command. + */ + public function getUsages(): array + { + return $this->usages; + } + + /** + * Gets a helper instance by name. + * + * @throws LogicException if no HelperSet is defined + * @throws InvalidArgumentException if the helper is not defined + */ + public function getHelper(string $name): HelperInterface + { + if (null === $this->helperSet) { + throw new LogicException(sprintf('Cannot retrieve helper "%s" because there is no HelperSet defined. Did you forget to add your command to the application or to set the application on the command using the setApplication() method? You can also set the HelperSet directly using the setHelperSet() method.', $name)); + } + + return $this->helperSet->get($name); + } + + /** + * Validates a command name. + * + * It must be non-empty and parts can optionally be separated by ":". + * + * @throws InvalidArgumentException When the name is invalid + */ + private function validateName(string $name): void + { + if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) { + throw new InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name)); + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Command/CompleteCommand.php b/tools/php-cs-fixer/vendor/symfony/console/Command/CompleteCommand.php new file mode 100644 index 00000000..38aa737f --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Command/CompleteCommand.php @@ -0,0 +1,212 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Completion\Output\BashCompletionOutput; +use Symfony\Component\Console\Completion\Output\CompletionOutputInterface; +use Symfony\Component\Console\Completion\Output\FishCompletionOutput; +use Symfony\Component\Console\Completion\Output\ZshCompletionOutput; +use Symfony\Component\Console\Exception\CommandNotFoundException; +use Symfony\Component\Console\Exception\ExceptionInterface; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Responsible for providing the values to the shell completion. + * + * @author Wouter de Jong + */ +#[AsCommand(name: '|_complete', description: 'Internal command to provide shell completion suggestions')] +final class CompleteCommand extends Command +{ + public const COMPLETION_API_VERSION = '1'; + + private array $completionOutputs; + private bool $isDebug = false; + + /** + * @param array> $completionOutputs A list of additional completion outputs, with shell name as key and FQCN as value + */ + public function __construct(array $completionOutputs = []) + { + // must be set before the parent constructor, as the property value is used in configure() + $this->completionOutputs = $completionOutputs + [ + 'bash' => BashCompletionOutput::class, + 'fish' => FishCompletionOutput::class, + 'zsh' => ZshCompletionOutput::class, + ]; + + parent::__construct(); + } + + protected function configure(): void + { + $this + ->addOption('shell', 's', InputOption::VALUE_REQUIRED, 'The shell type ("'.implode('", "', array_keys($this->completionOutputs)).'")') + ->addOption('input', 'i', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'An array of input tokens (e.g. COMP_WORDS or argv)') + ->addOption('current', 'c', InputOption::VALUE_REQUIRED, 'The index of the "input" array that the cursor is in (e.g. COMP_CWORD)') + ->addOption('api-version', 'a', InputOption::VALUE_REQUIRED, 'The API version of the completion script') + ->addOption('symfony', 'S', InputOption::VALUE_REQUIRED, 'deprecated') + ; + } + + protected function initialize(InputInterface $input, OutputInterface $output): void + { + $this->isDebug = filter_var(getenv('SYMFONY_COMPLETION_DEBUG'), \FILTER_VALIDATE_BOOL); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + try { + // "symfony" must be kept for compat with the shell scripts generated by Symfony Console 5.4 - 6.1 + $version = $input->getOption('symfony') ? '1' : $input->getOption('api-version'); + if ($version && version_compare($version, self::COMPLETION_API_VERSION, '<')) { + $message = sprintf('Completion script version is not supported ("%s" given, ">=%s" required).', $version, self::COMPLETION_API_VERSION); + $this->log($message); + + $output->writeln($message.' Install the Symfony completion script again by using the "completion" command.'); + + return 126; + } + + $shell = $input->getOption('shell'); + if (!$shell) { + throw new \RuntimeException('The "--shell" option must be set.'); + } + + if (!$completionOutput = $this->completionOutputs[$shell] ?? false) { + throw new \RuntimeException(sprintf('Shell completion is not supported for your shell: "%s" (supported: "%s").', $shell, implode('", "', array_keys($this->completionOutputs)))); + } + + $completionInput = $this->createCompletionInput($input); + $suggestions = new CompletionSuggestions(); + + $this->log([ + '', + ''.date('Y-m-d H:i:s').'', + 'Input: ("|" indicates the cursor position)', + ' '.(string) $completionInput, + 'Command:', + ' '.(string) implode(' ', $_SERVER['argv']), + 'Messages:', + ]); + + $command = $this->findCommand($completionInput, $output); + if (null === $command) { + $this->log(' No command found, completing using the Application class.'); + + $this->getApplication()->complete($completionInput, $suggestions); + } elseif ( + $completionInput->mustSuggestArgumentValuesFor('command') + && $command->getName() !== $completionInput->getCompletionValue() + && !\in_array($completionInput->getCompletionValue(), $command->getAliases(), true) + ) { + $this->log(' No command found, completing using the Application class.'); + + // expand shortcut names ("cache:cl") into their full name ("cache:clear") + $suggestions->suggestValues(array_filter(array_merge([$command->getName()], $command->getAliases()))); + } else { + $command->mergeApplicationDefinition(); + $completionInput->bind($command->getDefinition()); + + if (CompletionInput::TYPE_OPTION_NAME === $completionInput->getCompletionType()) { + $this->log(' Completing option names for the '.($command instanceof LazyCommand ? $command->getCommand() : $command)::class.' command.'); + + $suggestions->suggestOptions($command->getDefinition()->getOptions()); + } else { + $this->log([ + ' Completing using the '.($command instanceof LazyCommand ? $command->getCommand() : $command)::class.' class.', + ' Completing '.$completionInput->getCompletionType().' for '.$completionInput->getCompletionName().'', + ]); + if (null !== $compval = $completionInput->getCompletionValue()) { + $this->log(' Current value: '.$compval.''); + } + + $command->complete($completionInput, $suggestions); + } + } + + /** @var CompletionOutputInterface $completionOutput */ + $completionOutput = new $completionOutput(); + + $this->log('Suggestions:'); + if ($options = $suggestions->getOptionSuggestions()) { + $this->log(' --'.implode(' --', array_map(fn ($o) => $o->getName(), $options))); + } elseif ($values = $suggestions->getValueSuggestions()) { + $this->log(' '.implode(' ', $values)); + } else { + $this->log(' No suggestions were provided'); + } + + $completionOutput->write($suggestions, $output); + } catch (\Throwable $e) { + $this->log([ + 'Error!', + (string) $e, + ]); + + if ($output->isDebug()) { + throw $e; + } + + return 2; + } + + return 0; + } + + private function createCompletionInput(InputInterface $input): CompletionInput + { + $currentIndex = $input->getOption('current'); + if (!$currentIndex || !ctype_digit($currentIndex)) { + throw new \RuntimeException('The "--current" option must be set and it must be an integer.'); + } + + $completionInput = CompletionInput::fromTokens($input->getOption('input'), (int) $currentIndex); + + try { + $completionInput->bind($this->getApplication()->getDefinition()); + } catch (ExceptionInterface) { + } + + return $completionInput; + } + + private function findCommand(CompletionInput $completionInput, OutputInterface $output): ?Command + { + try { + $inputName = $completionInput->getFirstArgument(); + if (null === $inputName) { + return null; + } + + return $this->getApplication()->find($inputName); + } catch (CommandNotFoundException) { + } + + return null; + } + + private function log($messages): void + { + if (!$this->isDebug) { + return; + } + + $commandName = basename($_SERVER['argv'][0]); + file_put_contents(sys_get_temp_dir().'/sf_'.$commandName.'.log', implode(\PHP_EOL, (array) $messages).\PHP_EOL, \FILE_APPEND); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Command/DumpCompletionCommand.php b/tools/php-cs-fixer/vendor/symfony/console/Command/DumpCompletionCommand.php new file mode 100644 index 00000000..be6f5459 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Command/DumpCompletionCommand.php @@ -0,0 +1,151 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Process\Process; + +/** + * Dumps the completion script for the current shell. + * + * @author Wouter de Jong + */ +#[AsCommand(name: 'completion', description: 'Dump the shell completion script')] +final class DumpCompletionCommand extends Command +{ + private array $supportedShells; + + protected function configure(): void + { + $fullCommand = $_SERVER['PHP_SELF']; + $commandName = basename($fullCommand); + $fullCommand = @realpath($fullCommand) ?: $fullCommand; + + $shell = $this->guessShell(); + [$rcFile, $completionFile] = match ($shell) { + 'fish' => ['~/.config/fish/config.fish', "/etc/fish/completions/$commandName.fish"], + 'zsh' => ['~/.zshrc', '$fpath[1]/_'.$commandName], + default => ['~/.bashrc', "/etc/bash_completion.d/$commandName"], + }; + + $supportedShells = implode(', ', $this->getSupportedShells()); + + $this + ->setHelp(<<%command.name% command dumps the shell completion script required +to use shell autocompletion (currently, {$supportedShells} completion are supported). + +Static installation +------------------- + +Dump the script to a global completion file and restart your shell: + + %command.full_name% {$shell} | sudo tee {$completionFile} + +Or dump the script to a local file and source it: + + %command.full_name% {$shell} > completion.sh + + # source the file whenever you use the project + source completion.sh + + # or add this line at the end of your "{$rcFile}" file: + source /path/to/completion.sh + +Dynamic installation +-------------------- + +Add this to the end of your shell configuration file (e.g. "{$rcFile}"): + + eval "$({$fullCommand} completion {$shell})" +EOH + ) + ->addArgument('shell', InputArgument::OPTIONAL, 'The shell type (e.g. "bash"), the value of the "$SHELL" env var will be used if this is not given', null, $this->getSupportedShells(...)) + ->addOption('debug', null, InputOption::VALUE_NONE, 'Tail the completion debug log') + ; + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $commandName = basename($_SERVER['argv'][0]); + + if ($input->getOption('debug')) { + $this->tailDebugLog($commandName, $output); + + return 0; + } + + $shell = $input->getArgument('shell') ?? self::guessShell(); + $completionFile = __DIR__.'/../Resources/completion.'.$shell; + if (!file_exists($completionFile)) { + $supportedShells = $this->getSupportedShells(); + + if ($output instanceof ConsoleOutputInterface) { + $output = $output->getErrorOutput(); + } + if ($shell) { + $output->writeln(sprintf('Detected shell "%s", which is not supported by Symfony shell completion (supported shells: "%s").', $shell, implode('", "', $supportedShells))); + } else { + $output->writeln(sprintf('Shell not detected, Symfony shell completion only supports "%s").', implode('", "', $supportedShells))); + } + + return 2; + } + + $output->write(str_replace(['{{ COMMAND_NAME }}', '{{ VERSION }}'], [$commandName, CompleteCommand::COMPLETION_API_VERSION], file_get_contents($completionFile))); + + return 0; + } + + private static function guessShell(): string + { + return basename($_SERVER['SHELL'] ?? ''); + } + + private function tailDebugLog(string $commandName, OutputInterface $output): void + { + $debugFile = sys_get_temp_dir().'/sf_'.$commandName.'.log'; + if (!file_exists($debugFile)) { + touch($debugFile); + } + $process = new Process(['tail', '-f', $debugFile], null, null, null, 0); + $process->run(function (string $type, string $line) use ($output): void { + $output->write($line); + }); + } + + /** + * @return string[] + */ + private function getSupportedShells(): array + { + if (isset($this->supportedShells)) { + return $this->supportedShells; + } + + $shells = []; + + foreach (new \DirectoryIterator(__DIR__.'/../Resources/') as $file) { + if (str_starts_with($file->getBasename(), 'completion.') && $file->isFile()) { + $shells[] = $file->getExtension(); + } + } + sort($shells); + + return $this->supportedShells = $shells; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Command/HelpCommand.php b/tools/php-cs-fixer/vendor/symfony/console/Command/HelpCommand.php new file mode 100644 index 00000000..a2a72dab --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Command/HelpCommand.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +use Symfony\Component\Console\Descriptor\ApplicationDescription; +use Symfony\Component\Console\Helper\DescriptorHelper; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * HelpCommand displays the help for a given command. + * + * @author Fabien Potencier + */ +class HelpCommand extends Command +{ + private Command $command; + + protected function configure(): void + { + $this->ignoreValidationErrors(); + + $this + ->setName('help') + ->setDefinition([ + new InputArgument('command_name', InputArgument::OPTIONAL, 'The command name', 'help', fn () => array_keys((new ApplicationDescription($this->getApplication()))->getCommands())), + new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt, xml, json, or md)', 'txt', fn () => (new DescriptorHelper())->getFormats()), + new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command help'), + ]) + ->setDescription('Display help for a command') + ->setHelp(<<<'EOF' +The %command.name% command displays help for a given command: + + %command.full_name% list + +You can also output the help in other formats by using the --format option: + + %command.full_name% --format=xml list + +To display the list of available commands, please use the list command. +EOF + ) + ; + } + + public function setCommand(Command $command): void + { + $this->command = $command; + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $this->command ??= $this->getApplication()->find($input->getArgument('command_name')); + + $helper = new DescriptorHelper(); + $helper->describe($output, $this->command, [ + 'format' => $input->getOption('format'), + 'raw_text' => $input->getOption('raw'), + ]); + + unset($this->command); + + return 0; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Command/LazyCommand.php b/tools/php-cs-fixer/vendor/symfony/console/Command/LazyCommand.php new file mode 100644 index 00000000..7279724a --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Command/LazyCommand.php @@ -0,0 +1,202 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Completion\Suggestion; +use Symfony\Component\Console\Helper\HelperInterface; +use Symfony\Component\Console\Helper\HelperSet; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Nicolas Grekas + */ +final class LazyCommand extends Command +{ + private \Closure|Command $command; + private ?bool $isEnabled; + + public function __construct(string $name, array $aliases, string $description, bool $isHidden, \Closure $commandFactory, ?bool $isEnabled = true) + { + $this->setName($name) + ->setAliases($aliases) + ->setHidden($isHidden) + ->setDescription($description); + + $this->command = $commandFactory; + $this->isEnabled = $isEnabled; + } + + public function ignoreValidationErrors(): void + { + $this->getCommand()->ignoreValidationErrors(); + } + + public function setApplication(?Application $application): void + { + if ($this->command instanceof parent) { + $this->command->setApplication($application); + } + + parent::setApplication($application); + } + + public function setHelperSet(HelperSet $helperSet): void + { + if ($this->command instanceof parent) { + $this->command->setHelperSet($helperSet); + } + + parent::setHelperSet($helperSet); + } + + public function isEnabled(): bool + { + return $this->isEnabled ?? $this->getCommand()->isEnabled(); + } + + public function run(InputInterface $input, OutputInterface $output): int + { + return $this->getCommand()->run($input, $output); + } + + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + $this->getCommand()->complete($input, $suggestions); + } + + public function setCode(callable $code): static + { + $this->getCommand()->setCode($code); + + return $this; + } + + /** + * @internal + */ + public function mergeApplicationDefinition(bool $mergeArgs = true): void + { + $this->getCommand()->mergeApplicationDefinition($mergeArgs); + } + + public function setDefinition(array|InputDefinition $definition): static + { + $this->getCommand()->setDefinition($definition); + + return $this; + } + + public function getDefinition(): InputDefinition + { + return $this->getCommand()->getDefinition(); + } + + public function getNativeDefinition(): InputDefinition + { + return $this->getCommand()->getNativeDefinition(); + } + + /** + * @param array|\Closure(CompletionInput,CompletionSuggestions):list $suggestedValues The values used for input completion + */ + public function addArgument(string $name, int $mode = null, string $description = '', mixed $default = null, array|\Closure $suggestedValues = []): static + { + $this->getCommand()->addArgument($name, $mode, $description, $default, $suggestedValues); + + return $this; + } + + /** + * @param array|\Closure(CompletionInput,CompletionSuggestions):list $suggestedValues The values used for input completion + */ + public function addOption(string $name, string|array $shortcut = null, int $mode = null, string $description = '', mixed $default = null, array|\Closure $suggestedValues = []): static + { + $this->getCommand()->addOption($name, $shortcut, $mode, $description, $default, $suggestedValues); + + return $this; + } + + public function setProcessTitle(string $title): static + { + $this->getCommand()->setProcessTitle($title); + + return $this; + } + + public function setHelp(string $help): static + { + $this->getCommand()->setHelp($help); + + return $this; + } + + public function getHelp(): string + { + return $this->getCommand()->getHelp(); + } + + public function getProcessedHelp(): string + { + return $this->getCommand()->getProcessedHelp(); + } + + public function getSynopsis(bool $short = false): string + { + return $this->getCommand()->getSynopsis($short); + } + + public function addUsage(string $usage): static + { + $this->getCommand()->addUsage($usage); + + return $this; + } + + public function getUsages(): array + { + return $this->getCommand()->getUsages(); + } + + public function getHelper(string $name): HelperInterface + { + return $this->getCommand()->getHelper($name); + } + + public function getCommand(): parent + { + if (!$this->command instanceof \Closure) { + return $this->command; + } + + $command = $this->command = ($this->command)(); + $command->setApplication($this->getApplication()); + + if (null !== $this->getHelperSet()) { + $command->setHelperSet($this->getHelperSet()); + } + + $command->setName($this->getName()) + ->setAliases($this->getAliases()) + ->setHidden($this->isHidden()) + ->setDescription($this->getDescription()); + + // Will throw if the command is not correctly initialized. + $command->getDefinition(); + + return $command; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Command/ListCommand.php b/tools/php-cs-fixer/vendor/symfony/console/Command/ListCommand.php new file mode 100644 index 00000000..61b4b1b3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Command/ListCommand.php @@ -0,0 +1,72 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +use Symfony\Component\Console\Descriptor\ApplicationDescription; +use Symfony\Component\Console\Helper\DescriptorHelper; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * ListCommand displays the list of all available commands for the application. + * + * @author Fabien Potencier + */ +class ListCommand extends Command +{ + protected function configure(): void + { + $this + ->setName('list') + ->setDefinition([ + new InputArgument('namespace', InputArgument::OPTIONAL, 'The namespace name', null, fn () => array_keys((new ApplicationDescription($this->getApplication()))->getNamespaces())), + new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command list'), + new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt, xml, json, or md)', 'txt', fn () => (new DescriptorHelper())->getFormats()), + new InputOption('short', null, InputOption::VALUE_NONE, 'To skip describing commands\' arguments'), + ]) + ->setDescription('List commands') + ->setHelp(<<<'EOF' +The %command.name% command lists all commands: + + %command.full_name% + +You can also display the commands for a specific namespace: + + %command.full_name% test + +You can also output the information in other formats by using the --format option: + + %command.full_name% --format=xml + +It's also possible to get raw list of commands (useful for embedding command runner): + + %command.full_name% --raw +EOF + ) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $helper = new DescriptorHelper(); + $helper->describe($output, $this->getApplication(), [ + 'format' => $input->getOption('format'), + 'raw_text' => $input->getOption('raw'), + 'namespace' => $input->getArgument('namespace'), + 'short' => $input->getOption('short'), + ]); + + return 0; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Command/LockableTrait.php b/tools/php-cs-fixer/vendor/symfony/console/Command/LockableTrait.php new file mode 100644 index 00000000..c1006a65 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Command/LockableTrait.php @@ -0,0 +1,68 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +use Symfony\Component\Console\Exception\LogicException; +use Symfony\Component\Lock\LockFactory; +use Symfony\Component\Lock\LockInterface; +use Symfony\Component\Lock\Store\FlockStore; +use Symfony\Component\Lock\Store\SemaphoreStore; + +/** + * Basic lock feature for commands. + * + * @author Geoffrey Brier + */ +trait LockableTrait +{ + private ?LockInterface $lock = null; + + /** + * Locks a command. + */ + private function lock(string $name = null, bool $blocking = false): bool + { + if (!class_exists(SemaphoreStore::class)) { + throw new LogicException('To enable the locking feature you must install the symfony/lock component. Try running "composer require symfony/lock".'); + } + + if (null !== $this->lock) { + throw new LogicException('A lock is already in place.'); + } + + if (SemaphoreStore::isSupported()) { + $store = new SemaphoreStore(); + } else { + $store = new FlockStore(); + } + + $this->lock = (new LockFactory($store))->createLock($name ?: $this->getName()); + if (!$this->lock->acquire($blocking)) { + $this->lock = null; + + return false; + } + + return true; + } + + /** + * Releases the command lock if there is one. + */ + private function release(): void + { + if ($this->lock) { + $this->lock->release(); + $this->lock = null; + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Command/SignalableCommandInterface.php b/tools/php-cs-fixer/vendor/symfony/console/Command/SignalableCommandInterface.php new file mode 100644 index 00000000..40b301d1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Command/SignalableCommandInterface.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +/** + * Interface for command reacting to signal. + * + * @author Grégoire Pineau + */ +interface SignalableCommandInterface +{ + /** + * Returns the list of signals to subscribe. + */ + public function getSubscribedSignals(): array; + + /** + * The method will be called when the application is signaled. + * + * @return int|false The exit code to return or false to continue the normal execution + */ + public function handleSignal(int $signal, int|false $previousExitCode = 0): int|false; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Command/TraceableCommand.php b/tools/php-cs-fixer/vendor/symfony/console/Command/TraceableCommand.php new file mode 100644 index 00000000..d8c46b7f --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Command/TraceableCommand.php @@ -0,0 +1,356 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Command; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Helper\HelperInterface; +use Symfony\Component\Console\Helper\HelperSet; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Stopwatch\Stopwatch; + +/** + * @internal + * + * @author Jules Pietri + */ +final class TraceableCommand extends Command implements SignalableCommandInterface +{ + public readonly Command $command; + public int $exitCode; + public ?int $interruptedBySignal = null; + public bool $ignoreValidation; + public bool $isInteractive = false; + public string $duration = 'n/a'; + public string $maxMemoryUsage = 'n/a'; + public InputInterface $input; + public OutputInterface $output; + /** @var array */ + public array $arguments; + /** @var array */ + public array $options; + /** @var array */ + public array $interactiveInputs = []; + public array $handledSignals = []; + + public function __construct( + Command $command, + private readonly Stopwatch $stopwatch, + ) { + if ($command instanceof LazyCommand) { + $command = $command->getCommand(); + } + + $this->command = $command; + + // prevent call to self::getDefaultDescription() + $this->setDescription($command->getDescription()); + + parent::__construct($command->getName()); + + // init below enables calling {@see parent::run()} + [$code, $processTitle, $ignoreValidationErrors] = \Closure::bind(function () { + return [$this->code, $this->processTitle, $this->ignoreValidationErrors]; + }, $command, Command::class)(); + + if (\is_callable($code)) { + $this->setCode($code); + } + + if ($processTitle) { + parent::setProcessTitle($processTitle); + } + + if ($ignoreValidationErrors) { + parent::ignoreValidationErrors(); + } + + $this->ignoreValidation = $ignoreValidationErrors; + } + + public function __call(string $name, array $arguments): mixed + { + return $this->command->{$name}(...$arguments); + } + + public function getSubscribedSignals(): array + { + return $this->command instanceof SignalableCommandInterface ? $this->command->getSubscribedSignals() : []; + } + + public function handleSignal(int $signal, int|false $previousExitCode = 0): int|false + { + if (!$this->command instanceof SignalableCommandInterface) { + return false; + } + + $event = $this->stopwatch->start($this->getName().'.handle_signal'); + + $exit = $this->command->handleSignal($signal, $previousExitCode); + + $event->stop(); + + if (!isset($this->handledSignals[$signal])) { + $this->handledSignals[$signal] = [ + 'handled' => 0, + 'duration' => 0, + 'memory' => 0, + ]; + } + + ++$this->handledSignals[$signal]['handled']; + $this->handledSignals[$signal]['duration'] += $event->getDuration(); + $this->handledSignals[$signal]['memory'] = max( + $this->handledSignals[$signal]['memory'], + $event->getMemory() >> 20 + ); + + return $exit; + } + + /** + * {@inheritdoc} + * + * Calling parent method is required to be used in {@see parent::run()}. + */ + public function ignoreValidationErrors(): void + { + $this->ignoreValidation = true; + $this->command->ignoreValidationErrors(); + + parent::ignoreValidationErrors(); + } + + public function setApplication(Application $application = null): void + { + $this->command->setApplication($application); + } + + public function getApplication(): ?Application + { + return $this->command->getApplication(); + } + + public function setHelperSet(HelperSet $helperSet): void + { + $this->command->setHelperSet($helperSet); + } + + public function getHelperSet(): ?HelperSet + { + return $this->command->getHelperSet(); + } + + public function isEnabled(): bool + { + return $this->command->isEnabled(); + } + + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + $this->command->complete($input, $suggestions); + } + + /** + * {@inheritdoc} + * + * Calling parent method is required to be used in {@see parent::run()}. + */ + public function setCode(callable $code): static + { + $this->command->setCode($code); + + return parent::setCode(function (InputInterface $input, OutputInterface $output) use ($code): int { + $event = $this->stopwatch->start($this->getName().'.code'); + + $this->exitCode = $code($input, $output); + + $event->stop(); + + return $this->exitCode; + }); + } + + /** + * @internal + */ + public function mergeApplicationDefinition(bool $mergeArgs = true): void + { + $this->command->mergeApplicationDefinition($mergeArgs); + } + + public function setDefinition(array|InputDefinition $definition): static + { + $this->command->setDefinition($definition); + + return $this; + } + + public function getDefinition(): InputDefinition + { + return $this->command->getDefinition(); + } + + public function getNativeDefinition(): InputDefinition + { + return $this->command->getNativeDefinition(); + } + + public function addArgument(string $name, int $mode = null, string $description = '', mixed $default = null, array|\Closure $suggestedValues = []): static + { + $this->command->addArgument($name, $mode, $description, $default, $suggestedValues); + + return $this; + } + + public function addOption(string $name, string|array $shortcut = null, int $mode = null, string $description = '', mixed $default = null, array|\Closure $suggestedValues = []): static + { + $this->command->addOption($name, $shortcut, $mode, $description, $default, $suggestedValues); + + return $this; + } + + /** + * {@inheritdoc} + * + * Calling parent method is required to be used in {@see parent::run()}. + */ + public function setProcessTitle(string $title): static + { + $this->command->setProcessTitle($title); + + return parent::setProcessTitle($title); + } + + public function setHelp(string $help): static + { + $this->command->setHelp($help); + + return $this; + } + + public function getHelp(): string + { + return $this->command->getHelp(); + } + + public function getProcessedHelp(): string + { + return $this->command->getProcessedHelp(); + } + + public function getSynopsis(bool $short = false): string + { + return $this->command->getSynopsis($short); + } + + public function addUsage(string $usage): static + { + $this->command->addUsage($usage); + + return $this; + } + + public function getUsages(): array + { + return $this->command->getUsages(); + } + + public function getHelper(string $name): HelperInterface + { + return $this->command->getHelper($name); + } + + public function run(InputInterface $input, OutputInterface $output): int + { + $this->input = $input; + $this->output = $output; + $this->arguments = $input->getArguments(); + $this->options = $input->getOptions(); + $event = $this->stopwatch->start($this->getName(), 'command'); + + try { + $this->exitCode = parent::run($input, $output); + } finally { + $event->stop(); + + if ($output instanceof ConsoleOutputInterface && $output->isDebug()) { + $output->getErrorOutput()->writeln((string) $event); + } + + $this->duration = $event->getDuration().' ms'; + $this->maxMemoryUsage = ($event->getMemory() >> 20).' MiB'; + + if ($this->isInteractive) { + $this->extractInteractiveInputs($input->getArguments(), $input->getOptions()); + } + } + + return $this->exitCode; + } + + protected function initialize(InputInterface $input, OutputInterface $output): void + { + $event = $this->stopwatch->start($this->getName().'.init', 'command'); + + $this->command->initialize($input, $output); + + $event->stop(); + } + + protected function interact(InputInterface $input, OutputInterface $output): void + { + if (!$this->isInteractive = Command::class !== (new \ReflectionMethod($this->command, 'interact'))->getDeclaringClass()->getName()) { + return; + } + + $event = $this->stopwatch->start($this->getName().'.interact', 'command'); + + $this->command->interact($input, $output); + + $event->stop(); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $event = $this->stopwatch->start($this->getName().'.execute', 'command'); + + $exitCode = $this->command->execute($input, $output); + + $event->stop(); + + return $exitCode; + } + + private function extractInteractiveInputs(array $arguments, array $options): void + { + foreach ($arguments as $argName => $argValue) { + if (\array_key_exists($argName, $this->arguments) && $this->arguments[$argName] === $argValue) { + continue; + } + + $this->interactiveInputs[$argName] = $argValue; + } + + foreach ($options as $optName => $optValue) { + if (\array_key_exists($optName, $this->options) && $this->options[$optName] === $optValue) { + continue; + } + + $this->interactiveInputs['--'.$optName] = $optValue; + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/CommandLoader/CommandLoaderInterface.php b/tools/php-cs-fixer/vendor/symfony/console/CommandLoader/CommandLoaderInterface.php new file mode 100644 index 00000000..b6b637ce --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/CommandLoader/CommandLoaderInterface.php @@ -0,0 +1,38 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\CommandLoader; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\CommandNotFoundException; + +/** + * @author Robin Chalas + */ +interface CommandLoaderInterface +{ + /** + * Loads a command. + * + * @throws CommandNotFoundException + */ + public function get(string $name): Command; + + /** + * Checks if a command exists. + */ + public function has(string $name): bool; + + /** + * @return string[] + */ + public function getNames(): array; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/CommandLoader/ContainerCommandLoader.php b/tools/php-cs-fixer/vendor/symfony/console/CommandLoader/ContainerCommandLoader.php new file mode 100644 index 00000000..bfa0ac46 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/CommandLoader/ContainerCommandLoader.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\CommandLoader; + +use Psr\Container\ContainerInterface; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\CommandNotFoundException; + +/** + * Loads commands from a PSR-11 container. + * + * @author Robin Chalas + */ +class ContainerCommandLoader implements CommandLoaderInterface +{ + private ContainerInterface $container; + private array $commandMap; + + /** + * @param array $commandMap An array with command names as keys and service ids as values + */ + public function __construct(ContainerInterface $container, array $commandMap) + { + $this->container = $container; + $this->commandMap = $commandMap; + } + + public function get(string $name): Command + { + if (!$this->has($name)) { + throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name)); + } + + return $this->container->get($this->commandMap[$name]); + } + + public function has(string $name): bool + { + return isset($this->commandMap[$name]) && $this->container->has($this->commandMap[$name]); + } + + public function getNames(): array + { + return array_keys($this->commandMap); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/CommandLoader/FactoryCommandLoader.php b/tools/php-cs-fixer/vendor/symfony/console/CommandLoader/FactoryCommandLoader.php new file mode 100644 index 00000000..9ced75ae --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/CommandLoader/FactoryCommandLoader.php @@ -0,0 +1,54 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\CommandLoader; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\CommandNotFoundException; + +/** + * A simple command loader using factories to instantiate commands lazily. + * + * @author Maxime Steinhausser + */ +class FactoryCommandLoader implements CommandLoaderInterface +{ + private array $factories; + + /** + * @param callable[] $factories Indexed by command names + */ + public function __construct(array $factories) + { + $this->factories = $factories; + } + + public function has(string $name): bool + { + return isset($this->factories[$name]); + } + + public function get(string $name): Command + { + if (!isset($this->factories[$name])) { + throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name)); + } + + $factory = $this->factories[$name]; + + return $factory(); + } + + public function getNames(): array + { + return array_keys($this->factories); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Completion/CompletionInput.php b/tools/php-cs-fixer/vendor/symfony/console/Completion/CompletionInput.php new file mode 100644 index 00000000..7ba41c08 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Completion/CompletionInput.php @@ -0,0 +1,248 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Completion; + +use Symfony\Component\Console\Exception\RuntimeException; +use Symfony\Component\Console\Input\ArgvInput; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputOption; + +/** + * An input specialized for shell completion. + * + * This input allows unfinished option names or values and exposes what kind of + * completion is expected. + * + * @author Wouter de Jong + */ +final class CompletionInput extends ArgvInput +{ + public const TYPE_ARGUMENT_VALUE = 'argument_value'; + public const TYPE_OPTION_VALUE = 'option_value'; + public const TYPE_OPTION_NAME = 'option_name'; + public const TYPE_NONE = 'none'; + + private array $tokens; + private int $currentIndex; + private string $completionType; + private ?string $completionName = null; + private string $completionValue = ''; + + /** + * Converts a terminal string into tokens. + * + * This is required for shell completions without COMP_WORDS support. + */ + public static function fromString(string $inputStr, int $currentIndex): self + { + preg_match_all('/(?<=^|\s)([\'"]?)(.+?)(?tokens = $tokens; + $input->currentIndex = $currentIndex; + + return $input; + } + + public function bind(InputDefinition $definition): void + { + parent::bind($definition); + + $relevantToken = $this->getRelevantToken(); + if ('-' === $relevantToken[0]) { + // the current token is an input option: complete either option name or option value + [$optionToken, $optionValue] = explode('=', $relevantToken, 2) + ['', '']; + + $option = $this->getOptionFromToken($optionToken); + if (null === $option && !$this->isCursorFree()) { + $this->completionType = self::TYPE_OPTION_NAME; + $this->completionValue = $relevantToken; + + return; + } + + if ($option?->acceptValue()) { + $this->completionType = self::TYPE_OPTION_VALUE; + $this->completionName = $option->getName(); + $this->completionValue = $optionValue ?: (!str_starts_with($optionToken, '--') ? substr($optionToken, 2) : ''); + + return; + } + } + + $previousToken = $this->tokens[$this->currentIndex - 1]; + if ('-' === $previousToken[0] && '' !== trim($previousToken, '-')) { + // check if previous option accepted a value + $previousOption = $this->getOptionFromToken($previousToken); + if ($previousOption?->acceptValue()) { + $this->completionType = self::TYPE_OPTION_VALUE; + $this->completionName = $previousOption->getName(); + $this->completionValue = $relevantToken; + + return; + } + } + + // complete argument value + $this->completionType = self::TYPE_ARGUMENT_VALUE; + + foreach ($this->definition->getArguments() as $argumentName => $argument) { + if (!isset($this->arguments[$argumentName])) { + break; + } + + $argumentValue = $this->arguments[$argumentName]; + $this->completionName = $argumentName; + if (\is_array($argumentValue)) { + $this->completionValue = $argumentValue ? $argumentValue[array_key_last($argumentValue)] : null; + } else { + $this->completionValue = $argumentValue; + } + } + + if ($this->currentIndex >= \count($this->tokens)) { + if (!isset($this->arguments[$argumentName]) || $this->definition->getArgument($argumentName)->isArray()) { + $this->completionName = $argumentName; + $this->completionValue = ''; + } else { + // we've reached the end + $this->completionType = self::TYPE_NONE; + $this->completionName = null; + $this->completionValue = ''; + } + } + } + + /** + * Returns the type of completion required. + * + * TYPE_ARGUMENT_VALUE when completing the value of an input argument + * TYPE_OPTION_VALUE when completing the value of an input option + * TYPE_OPTION_NAME when completing the name of an input option + * TYPE_NONE when nothing should be completed + * + * TYPE_OPTION_NAME and TYPE_NONE are already implemented by the Console component. + * + * @return self::TYPE_* + */ + public function getCompletionType(): string + { + return $this->completionType; + } + + /** + * The name of the input option or argument when completing a value. + * + * @return string|null returns null when completing an option name + */ + public function getCompletionName(): ?string + { + return $this->completionName; + } + + /** + * The value already typed by the user (or empty string). + */ + public function getCompletionValue(): string + { + return $this->completionValue; + } + + public function mustSuggestOptionValuesFor(string $optionName): bool + { + return self::TYPE_OPTION_VALUE === $this->getCompletionType() && $optionName === $this->getCompletionName(); + } + + public function mustSuggestArgumentValuesFor(string $argumentName): bool + { + return self::TYPE_ARGUMENT_VALUE === $this->getCompletionType() && $argumentName === $this->getCompletionName(); + } + + protected function parseToken(string $token, bool $parseOptions): bool + { + try { + return parent::parseToken($token, $parseOptions); + } catch (RuntimeException) { + // suppress errors, completed input is almost never valid + } + + return $parseOptions; + } + + private function getOptionFromToken(string $optionToken): ?InputOption + { + $optionName = ltrim($optionToken, '-'); + if (!$optionName) { + return null; + } + + if ('-' === ($optionToken[1] ?? ' ')) { + // long option name + return $this->definition->hasOption($optionName) ? $this->definition->getOption($optionName) : null; + } + + // short option name + return $this->definition->hasShortcut($optionName[0]) ? $this->definition->getOptionForShortcut($optionName[0]) : null; + } + + /** + * The token of the cursor, or the last token if the cursor is at the end of the input. + */ + private function getRelevantToken(): string + { + return $this->tokens[$this->isCursorFree() ? $this->currentIndex - 1 : $this->currentIndex]; + } + + /** + * Whether the cursor is "free" (i.e. at the end of the input preceded by a space). + */ + private function isCursorFree(): bool + { + $nrOfTokens = \count($this->tokens); + if ($this->currentIndex > $nrOfTokens) { + throw new \LogicException('Current index is invalid, it must be the number of input tokens or one more.'); + } + + return $this->currentIndex >= $nrOfTokens; + } + + public function __toString() + { + $str = ''; + foreach ($this->tokens as $i => $token) { + $str .= $token; + + if ($this->currentIndex === $i) { + $str .= '|'; + } + + $str .= ' '; + } + + if ($this->currentIndex > $i) { + $str .= '|'; + } + + return rtrim($str); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Completion/CompletionSuggestions.php b/tools/php-cs-fixer/vendor/symfony/console/Completion/CompletionSuggestions.php new file mode 100644 index 00000000..549bbafb --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Completion/CompletionSuggestions.php @@ -0,0 +1,97 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Completion; + +use Symfony\Component\Console\Input\InputOption; + +/** + * Stores all completion suggestions for the current input. + * + * @author Wouter de Jong + */ +final class CompletionSuggestions +{ + private array $valueSuggestions = []; + private array $optionSuggestions = []; + + /** + * Add a suggested value for an input option or argument. + * + * @return $this + */ + public function suggestValue(string|Suggestion $value): static + { + $this->valueSuggestions[] = !$value instanceof Suggestion ? new Suggestion($value) : $value; + + return $this; + } + + /** + * Add multiple suggested values at once for an input option or argument. + * + * @param list $values + * + * @return $this + */ + public function suggestValues(array $values): static + { + foreach ($values as $value) { + $this->suggestValue($value); + } + + return $this; + } + + /** + * Add a suggestion for an input option name. + * + * @return $this + */ + public function suggestOption(InputOption $option): static + { + $this->optionSuggestions[] = $option; + + return $this; + } + + /** + * Add multiple suggestions for input option names at once. + * + * @param InputOption[] $options + * + * @return $this + */ + public function suggestOptions(array $options): static + { + foreach ($options as $option) { + $this->suggestOption($option); + } + + return $this; + } + + /** + * @return InputOption[] + */ + public function getOptionSuggestions(): array + { + return $this->optionSuggestions; + } + + /** + * @return Suggestion[] + */ + public function getValueSuggestions(): array + { + return $this->valueSuggestions; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Completion/Output/BashCompletionOutput.php b/tools/php-cs-fixer/vendor/symfony/console/Completion/Output/BashCompletionOutput.php new file mode 100644 index 00000000..c6f76eb8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Completion/Output/BashCompletionOutput.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Completion\Output; + +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Wouter de Jong + */ +class BashCompletionOutput implements CompletionOutputInterface +{ + public function write(CompletionSuggestions $suggestions, OutputInterface $output): void + { + $values = $suggestions->getValueSuggestions(); + foreach ($suggestions->getOptionSuggestions() as $option) { + $values[] = '--'.$option->getName(); + if ($option->isNegatable()) { + $values[] = '--no-'.$option->getName(); + } + } + $output->writeln(implode("\n", $values)); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Completion/Output/CompletionOutputInterface.php b/tools/php-cs-fixer/vendor/symfony/console/Completion/Output/CompletionOutputInterface.php new file mode 100644 index 00000000..659e5965 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Completion/Output/CompletionOutputInterface.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Completion\Output; + +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Transforms the {@see CompletionSuggestions} object into output readable by the shell completion. + * + * @author Wouter de Jong + */ +interface CompletionOutputInterface +{ + public function write(CompletionSuggestions $suggestions, OutputInterface $output): void; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Completion/Output/FishCompletionOutput.php b/tools/php-cs-fixer/vendor/symfony/console/Completion/Output/FishCompletionOutput.php new file mode 100644 index 00000000..d2c414e4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Completion/Output/FishCompletionOutput.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Completion\Output; + +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Guillaume Aveline + */ +class FishCompletionOutput implements CompletionOutputInterface +{ + public function write(CompletionSuggestions $suggestions, OutputInterface $output): void + { + $values = $suggestions->getValueSuggestions(); + foreach ($suggestions->getOptionSuggestions() as $option) { + $values[] = '--'.$option->getName(); + if ($option->isNegatable()) { + $values[] = '--no-'.$option->getName(); + } + } + $output->write(implode("\n", $values)); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Completion/Output/ZshCompletionOutput.php b/tools/php-cs-fixer/vendor/symfony/console/Completion/Output/ZshCompletionOutput.php new file mode 100644 index 00000000..bb4ce70b --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Completion/Output/ZshCompletionOutput.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Completion\Output; + +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Jitendra A + */ +class ZshCompletionOutput implements CompletionOutputInterface +{ + public function write(CompletionSuggestions $suggestions, OutputInterface $output): void + { + $values = []; + foreach ($suggestions->getValueSuggestions() as $value) { + $values[] = $value->getValue().($value->getDescription() ? "\t".$value->getDescription() : ''); + } + foreach ($suggestions->getOptionSuggestions() as $option) { + $values[] = '--'.$option->getName().($option->getDescription() ? "\t".$option->getDescription() : ''); + if ($option->isNegatable()) { + $values[] = '--no-'.$option->getName().($option->getDescription() ? "\t".$option->getDescription() : ''); + } + } + $output->write(implode("\n", $values)."\n"); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Completion/Suggestion.php b/tools/php-cs-fixer/vendor/symfony/console/Completion/Suggestion.php new file mode 100644 index 00000000..7392965a --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Completion/Suggestion.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Completion; + +/** + * Represents a single suggested value. + * + * @author Wouter de Jong + */ +class Suggestion implements \Stringable +{ + public function __construct( + private readonly string $value, + private readonly string $description = '' + ) { + } + + public function getValue(): string + { + return $this->value; + } + + public function getDescription(): string + { + return $this->description; + } + + public function __toString(): string + { + return $this->getValue(); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/ConsoleEvents.php b/tools/php-cs-fixer/vendor/symfony/console/ConsoleEvents.php new file mode 100644 index 00000000..6ae8f32b --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/ConsoleEvents.php @@ -0,0 +1,72 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console; + +use Symfony\Component\Console\Event\ConsoleCommandEvent; +use Symfony\Component\Console\Event\ConsoleErrorEvent; +use Symfony\Component\Console\Event\ConsoleSignalEvent; +use Symfony\Component\Console\Event\ConsoleTerminateEvent; + +/** + * Contains all events dispatched by an Application. + * + * @author Francesco Levorato + */ +final class ConsoleEvents +{ + /** + * The COMMAND event allows you to attach listeners before any command is + * executed by the console. It also allows you to modify the command, input and output + * before they are handed to the command. + * + * @Event("Symfony\Component\Console\Event\ConsoleCommandEvent") + */ + public const COMMAND = 'console.command'; + + /** + * The SIGNAL event allows you to perform some actions + * after the command execution was interrupted. + * + * @Event("Symfony\Component\Console\Event\ConsoleSignalEvent") + */ + public const SIGNAL = 'console.signal'; + + /** + * The TERMINATE event allows you to attach listeners after a command is + * executed by the console. + * + * @Event("Symfony\Component\Console\Event\ConsoleTerminateEvent") + */ + public const TERMINATE = 'console.terminate'; + + /** + * The ERROR event occurs when an uncaught exception or error appears. + * + * This event allows you to deal with the exception/error or + * to modify the thrown exception. + * + * @Event("Symfony\Component\Console\Event\ConsoleErrorEvent") + */ + public const ERROR = 'console.error'; + + /** + * Event aliases. + * + * These aliases can be consumed by RegisterListenersPass. + */ + public const ALIASES = [ + ConsoleCommandEvent::class => self::COMMAND, + ConsoleErrorEvent::class => self::ERROR, + ConsoleSignalEvent::class => self::SIGNAL, + ConsoleTerminateEvent::class => self::TERMINATE, + ]; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Cursor.php b/tools/php-cs-fixer/vendor/symfony/console/Cursor.php new file mode 100644 index 00000000..69fd3821 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Cursor.php @@ -0,0 +1,204 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console; + +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Pierre du Plessis + */ +final class Cursor +{ + private OutputInterface $output; + /** @var resource */ + private $input; + + /** + * @param resource|null $input + */ + public function __construct(OutputInterface $output, $input = null) + { + $this->output = $output; + $this->input = $input ?? (\defined('STDIN') ? \STDIN : fopen('php://input', 'r+')); + } + + /** + * @return $this + */ + public function moveUp(int $lines = 1): static + { + $this->output->write(sprintf("\x1b[%dA", $lines)); + + return $this; + } + + /** + * @return $this + */ + public function moveDown(int $lines = 1): static + { + $this->output->write(sprintf("\x1b[%dB", $lines)); + + return $this; + } + + /** + * @return $this + */ + public function moveRight(int $columns = 1): static + { + $this->output->write(sprintf("\x1b[%dC", $columns)); + + return $this; + } + + /** + * @return $this + */ + public function moveLeft(int $columns = 1): static + { + $this->output->write(sprintf("\x1b[%dD", $columns)); + + return $this; + } + + /** + * @return $this + */ + public function moveToColumn(int $column): static + { + $this->output->write(sprintf("\x1b[%dG", $column)); + + return $this; + } + + /** + * @return $this + */ + public function moveToPosition(int $column, int $row): static + { + $this->output->write(sprintf("\x1b[%d;%dH", $row + 1, $column)); + + return $this; + } + + /** + * @return $this + */ + public function savePosition(): static + { + $this->output->write("\x1b7"); + + return $this; + } + + /** + * @return $this + */ + public function restorePosition(): static + { + $this->output->write("\x1b8"); + + return $this; + } + + /** + * @return $this + */ + public function hide(): static + { + $this->output->write("\x1b[?25l"); + + return $this; + } + + /** + * @return $this + */ + public function show(): static + { + $this->output->write("\x1b[?25h\x1b[?0c"); + + return $this; + } + + /** + * Clears all the output from the current line. + * + * @return $this + */ + public function clearLine(): static + { + $this->output->write("\x1b[2K"); + + return $this; + } + + /** + * Clears all the output from the current line after the current position. + */ + public function clearLineAfter(): self + { + $this->output->write("\x1b[K"); + + return $this; + } + + /** + * Clears all the output from the cursors' current position to the end of the screen. + * + * @return $this + */ + public function clearOutput(): static + { + $this->output->write("\x1b[0J"); + + return $this; + } + + /** + * Clears the entire screen. + * + * @return $this + */ + public function clearScreen(): static + { + $this->output->write("\x1b[2J"); + + return $this; + } + + /** + * Returns the current cursor position as x,y coordinates. + */ + public function getCurrentPosition(): array + { + static $isTtySupported; + + if (!$isTtySupported ??= '/' === \DIRECTORY_SEPARATOR && stream_isatty(\STDOUT)) { + return [1, 1]; + } + + $sttyMode = shell_exec('stty -g'); + shell_exec('stty -icanon -echo'); + + @fwrite($this->input, "\033[6n"); + + $code = trim(fread($this->input, 1024)); + + shell_exec(sprintf('stty %s', $sttyMode)); + + sscanf($code, "\033[%d;%dR", $row, $col); + + return [$col, $row]; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/DataCollector/CommandDataCollector.php b/tools/php-cs-fixer/vendor/symfony/console/DataCollector/CommandDataCollector.php new file mode 100644 index 00000000..16a0eadf --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/DataCollector/CommandDataCollector.php @@ -0,0 +1,234 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\DataCollector; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Debug\CliRequest; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\SignalRegistry\SignalMap; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\DataCollector\DataCollector; +use Symfony\Component\VarDumper\Cloner\Data; + +/** + * @internal + * + * @author Jules Pietri + */ +final class CommandDataCollector extends DataCollector +{ + public function collect(Request $request, Response $response, \Throwable $exception = null): void + { + if (!$request instanceof CliRequest) { + return; + } + + $command = $request->command; + $application = $command->getApplication(); + + $this->data = [ + 'command' => $this->cloneVar($command->command), + 'exit_code' => $command->exitCode, + 'interrupted_by_signal' => $command->interruptedBySignal, + 'duration' => $command->duration, + 'max_memory_usage' => $command->maxMemoryUsage, + 'verbosity_level' => match ($command->output->getVerbosity()) { + OutputInterface::VERBOSITY_QUIET => 'quiet', + OutputInterface::VERBOSITY_NORMAL => 'normal', + OutputInterface::VERBOSITY_VERBOSE => 'verbose', + OutputInterface::VERBOSITY_VERY_VERBOSE => 'very verbose', + OutputInterface::VERBOSITY_DEBUG => 'debug', + }, + 'interactive' => $command->isInteractive, + 'validate_input' => !$command->ignoreValidation, + 'enabled' => $command->isEnabled(), + 'visible' => !$command->isHidden(), + 'input' => $this->cloneVar($command->input), + 'output' => $this->cloneVar($command->output), + 'interactive_inputs' => array_map($this->cloneVar(...), $command->interactiveInputs), + 'signalable' => $command->getSubscribedSignals(), + 'handled_signals' => $command->handledSignals, + 'helper_set' => array_map($this->cloneVar(...), iterator_to_array($command->getHelperSet())), + ]; + + $baseDefinition = $application->getDefinition(); + + foreach ($command->arguments as $argName => $argValue) { + if ($baseDefinition->hasArgument($argName)) { + $this->data['application_inputs'][$argName] = $this->cloneVar($argValue); + } else { + $this->data['arguments'][$argName] = $this->cloneVar($argValue); + } + } + + foreach ($command->options as $optName => $optValue) { + if ($baseDefinition->hasOption($optName)) { + $this->data['application_inputs']['--'.$optName] = $this->cloneVar($optValue); + } else { + $this->data['options'][$optName] = $this->cloneVar($optValue); + } + } + } + + public function getName(): string + { + return 'command'; + } + + /** + * @return array{ + * class?: class-string, + * executor?: string, + * file: string, + * line: int, + * } + */ + public function getCommand(): array + { + $class = $this->data['command']->getType(); + $r = new \ReflectionMethod($class, 'execute'); + + if (Command::class !== $r->getDeclaringClass()) { + return [ + 'executor' => $class.'::'.$r->name, + 'file' => $r->getFileName(), + 'line' => $r->getStartLine(), + ]; + } + + $r = new \ReflectionClass($class); + + return [ + 'class' => $class, + 'file' => $r->getFileName(), + 'line' => $r->getStartLine(), + ]; + } + + public function getInterruptedBySignal(): ?string + { + if (isset($this->data['interrupted_by_signal'])) { + return sprintf('%s (%d)', SignalMap::getSignalName($this->data['interrupted_by_signal']), $this->data['interrupted_by_signal']); + } + + return null; + } + + public function getDuration(): string + { + return $this->data['duration']; + } + + public function getMaxMemoryUsage(): string + { + return $this->data['max_memory_usage']; + } + + public function getVerbosityLevel(): string + { + return $this->data['verbosity_level']; + } + + public function getInteractive(): bool + { + return $this->data['interactive']; + } + + public function getValidateInput(): bool + { + return $this->data['validate_input']; + } + + public function getEnabled(): bool + { + return $this->data['enabled']; + } + + public function getVisible(): bool + { + return $this->data['visible']; + } + + public function getInput(): Data + { + return $this->data['input']; + } + + public function getOutput(): Data + { + return $this->data['output']; + } + + /** + * @return Data[] + */ + public function getArguments(): array + { + return $this->data['arguments'] ?? []; + } + + /** + * @return Data[] + */ + public function getOptions(): array + { + return $this->data['options'] ?? []; + } + + /** + * @return Data[] + */ + public function getApplicationInputs(): array + { + return $this->data['application_inputs'] ?? []; + } + + /** + * @return Data[] + */ + public function getInteractiveInputs(): array + { + return $this->data['interactive_inputs'] ?? []; + } + + public function getSignalable(): array + { + return array_map( + static fn (int $signal): string => sprintf('%s (%d)', SignalMap::getSignalName($signal), $signal), + $this->data['signalable'] + ); + } + + public function getHandledSignals(): array + { + $keys = array_map( + static fn (int $signal): string => sprintf('%s (%d)', SignalMap::getSignalName($signal), $signal), + array_keys($this->data['handled_signals']) + ); + + return array_combine($keys, array_values($this->data['handled_signals'])); + } + + /** + * @return Data[] + */ + public function getHelperSet(): array + { + return $this->data['helper_set'] ?? []; + } + + public function reset(): void + { + $this->data = []; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Debug/CliRequest.php b/tools/php-cs-fixer/vendor/symfony/console/Debug/CliRequest.php new file mode 100644 index 00000000..b023db07 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Debug/CliRequest.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Debug; + +use Symfony\Component\Console\Command\TraceableCommand; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; + +/** + * @internal + */ +final class CliRequest extends Request +{ + public function __construct( + public readonly TraceableCommand $command, + ) { + parent::__construct( + attributes: ['_controller' => \get_class($command->command), '_virtual_type' => 'command'], + server: $_SERVER, + ); + } + + // Methods below allow to populate a profile, thus enable search and filtering + public function getUri(): string + { + if ($this->server->has('SYMFONY_CLI_BINARY_NAME')) { + $binary = $this->server->get('SYMFONY_CLI_BINARY_NAME').' console'; + } else { + $binary = $this->server->get('argv')[0]; + } + + return $binary.' '.$this->command->input; + } + + public function getMethod(): string + { + return $this->command->isInteractive ? 'INTERACTIVE' : 'BATCH'; + } + + public function getResponse(): Response + { + return new class($this->command->exitCode) extends Response { + public function __construct(private readonly int $exitCode) + { + parent::__construct(); + } + + public function getStatusCode(): int + { + return $this->exitCode; + } + }; + } + + public function getClientIp(): string + { + $application = $this->command->getApplication(); + + return $application->getName().' '.$application->getVersion(); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/DependencyInjection/AddConsoleCommandPass.php b/tools/php-cs-fixer/vendor/symfony/console/DependencyInjection/AddConsoleCommandPass.php new file mode 100644 index 00000000..f712c614 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/DependencyInjection/AddConsoleCommandPass.php @@ -0,0 +1,131 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\DependencyInjection; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Command\LazyCommand; +use Symfony\Component\Console\CommandLoader\ContainerCommandLoader; +use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\DependencyInjection\TypedReference; + +/** + * Registers console commands. + * + * @author Grégoire Pineau + */ +class AddConsoleCommandPass implements CompilerPassInterface +{ + public function process(ContainerBuilder $container): void + { + $commandServices = $container->findTaggedServiceIds('console.command', true); + $lazyCommandMap = []; + $lazyCommandRefs = []; + $serviceIds = []; + + foreach ($commandServices as $id => $tags) { + $definition = $container->getDefinition($id); + $definition->addTag('container.no_preload'); + $class = $container->getParameterBag()->resolveValue($definition->getClass()); + + if (isset($tags[0]['command'])) { + $aliases = $tags[0]['command']; + } else { + if (!$r = $container->getReflectionClass($class)) { + throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id)); + } + if (!$r->isSubclassOf(Command::class)) { + throw new InvalidArgumentException(sprintf('The service "%s" tagged "%s" must be a subclass of "%s".', $id, 'console.command', Command::class)); + } + $aliases = str_replace('%', '%%', $class::getDefaultName() ?? ''); + } + + $aliases = explode('|', $aliases ?? ''); + $commandName = array_shift($aliases); + + if ($isHidden = '' === $commandName) { + $commandName = array_shift($aliases); + } + + if (null === $commandName) { + if (!$definition->isPublic() || $definition->isPrivate() || $definition->hasTag('container.private')) { + $commandId = 'console.command.public_alias.'.$id; + $container->setAlias($commandId, $id)->setPublic(true); + $id = $commandId; + } + $serviceIds[] = $id; + + continue; + } + + $description = $tags[0]['description'] ?? null; + + unset($tags[0]); + $lazyCommandMap[$commandName] = $id; + $lazyCommandRefs[$id] = new TypedReference($id, $class); + + foreach ($aliases as $alias) { + $lazyCommandMap[$alias] = $id; + } + + foreach ($tags as $tag) { + if (isset($tag['command'])) { + $aliases[] = $tag['command']; + $lazyCommandMap[$tag['command']] = $id; + } + + $description ??= $tag['description'] ?? null; + } + + $definition->addMethodCall('setName', [$commandName]); + + if ($aliases) { + $definition->addMethodCall('setAliases', [$aliases]); + } + + if ($isHidden) { + $definition->addMethodCall('setHidden', [true]); + } + + if (!$description) { + if (!$r = $container->getReflectionClass($class)) { + throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id)); + } + if (!$r->isSubclassOf(Command::class)) { + throw new InvalidArgumentException(sprintf('The service "%s" tagged "%s" must be a subclass of "%s".', $id, 'console.command', Command::class)); + } + $description = str_replace('%', '%%', $class::getDefaultDescription() ?? ''); + } + + if ($description) { + $definition->addMethodCall('setDescription', [$description]); + + $container->register('.'.$id.'.lazy', LazyCommand::class) + ->setArguments([$commandName, $aliases, $description, $isHidden, new ServiceClosureArgument($lazyCommandRefs[$id])]); + + $lazyCommandRefs[$id] = new Reference('.'.$id.'.lazy'); + } + } + + $container + ->register('console.command_loader', ContainerCommandLoader::class) + ->setPublic(true) + ->addTag('container.no_preload') + ->setArguments([ServiceLocatorTagPass::register($container, $lazyCommandRefs), $lazyCommandMap]); + + $container->setParameter('console.command.ids', $serviceIds); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Descriptor/ApplicationDescription.php b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/ApplicationDescription.php new file mode 100644 index 00000000..f8ed1804 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/ApplicationDescription.php @@ -0,0 +1,139 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Descriptor; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\CommandNotFoundException; + +/** + * @author Jean-François Simon + * + * @internal + */ +class ApplicationDescription +{ + public const GLOBAL_NAMESPACE = '_global'; + + private Application $application; + private ?string $namespace; + private bool $showHidden; + private array $namespaces; + + /** + * @var array + */ + private array $commands; + + /** + * @var array + */ + private array $aliases = []; + + public function __construct(Application $application, string $namespace = null, bool $showHidden = false) + { + $this->application = $application; + $this->namespace = $namespace; + $this->showHidden = $showHidden; + } + + public function getNamespaces(): array + { + if (!isset($this->namespaces)) { + $this->inspectApplication(); + } + + return $this->namespaces; + } + + /** + * @return Command[] + */ + public function getCommands(): array + { + if (!isset($this->commands)) { + $this->inspectApplication(); + } + + return $this->commands; + } + + /** + * @throws CommandNotFoundException + */ + public function getCommand(string $name): Command + { + if (!isset($this->commands[$name]) && !isset($this->aliases[$name])) { + throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name)); + } + + return $this->commands[$name] ?? $this->aliases[$name]; + } + + private function inspectApplication(): void + { + $this->commands = []; + $this->namespaces = []; + + $all = $this->application->all($this->namespace ? $this->application->findNamespace($this->namespace) : null); + foreach ($this->sortCommands($all) as $namespace => $commands) { + $names = []; + + /** @var Command $command */ + foreach ($commands as $name => $command) { + if (!$command->getName() || (!$this->showHidden && $command->isHidden())) { + continue; + } + + if ($command->getName() === $name) { + $this->commands[$name] = $command; + } else { + $this->aliases[$name] = $command; + } + + $names[] = $name; + } + + $this->namespaces[$namespace] = ['id' => $namespace, 'commands' => $names]; + } + } + + private function sortCommands(array $commands): array + { + $namespacedCommands = []; + $globalCommands = []; + $sortedCommands = []; + foreach ($commands as $name => $command) { + $key = $this->application->extractNamespace($name, 1); + if (\in_array($key, ['', self::GLOBAL_NAMESPACE], true)) { + $globalCommands[$name] = $command; + } else { + $namespacedCommands[$key][$name] = $command; + } + } + + if ($globalCommands) { + ksort($globalCommands); + $sortedCommands[self::GLOBAL_NAMESPACE] = $globalCommands; + } + + if ($namespacedCommands) { + ksort($namespacedCommands, \SORT_STRING); + foreach ($namespacedCommands as $key => $commandsSet) { + ksort($commandsSet); + $sortedCommands[$key] = $commandsSet; + } + } + + return $sortedCommands; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Descriptor/Descriptor.php b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/Descriptor.php new file mode 100644 index 00000000..7b2509c6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/Descriptor.php @@ -0,0 +1,74 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Descriptor; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Jean-François Simon + * + * @internal + */ +abstract class Descriptor implements DescriptorInterface +{ + protected OutputInterface $output; + + public function describe(OutputInterface $output, object $object, array $options = []): void + { + $this->output = $output; + + match (true) { + $object instanceof InputArgument => $this->describeInputArgument($object, $options), + $object instanceof InputOption => $this->describeInputOption($object, $options), + $object instanceof InputDefinition => $this->describeInputDefinition($object, $options), + $object instanceof Command => $this->describeCommand($object, $options), + $object instanceof Application => $this->describeApplication($object, $options), + default => throw new InvalidArgumentException(sprintf('Object of type "%s" is not describable.', get_debug_type($object))), + }; + } + + protected function write(string $content, bool $decorated = false): void + { + $this->output->write($content, false, $decorated ? OutputInterface::OUTPUT_NORMAL : OutputInterface::OUTPUT_RAW); + } + + /** + * Describes an InputArgument instance. + */ + abstract protected function describeInputArgument(InputArgument $argument, array $options = []): void; + + /** + * Describes an InputOption instance. + */ + abstract protected function describeInputOption(InputOption $option, array $options = []): void; + + /** + * Describes an InputDefinition instance. + */ + abstract protected function describeInputDefinition(InputDefinition $definition, array $options = []): void; + + /** + * Describes a Command instance. + */ + abstract protected function describeCommand(Command $command, array $options = []): void; + + /** + * Describes an Application instance. + */ + abstract protected function describeApplication(Application $application, array $options = []): void; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Descriptor/DescriptorInterface.php b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/DescriptorInterface.php new file mode 100644 index 00000000..04e5a7c8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/DescriptorInterface.php @@ -0,0 +1,24 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Descriptor; + +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Descriptor interface. + * + * @author Jean-François Simon + */ +interface DescriptorInterface +{ + public function describe(OutputInterface $output, object $object, array $options = []): void; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Descriptor/JsonDescriptor.php b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/JsonDescriptor.php new file mode 100644 index 00000000..95630370 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/JsonDescriptor.php @@ -0,0 +1,166 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Descriptor; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputOption; + +/** + * JSON descriptor. + * + * @author Jean-François Simon + * + * @internal + */ +class JsonDescriptor extends Descriptor +{ + protected function describeInputArgument(InputArgument $argument, array $options = []): void + { + $this->writeData($this->getInputArgumentData($argument), $options); + } + + protected function describeInputOption(InputOption $option, array $options = []): void + { + $this->writeData($this->getInputOptionData($option), $options); + if ($option->isNegatable()) { + $this->writeData($this->getInputOptionData($option, true), $options); + } + } + + protected function describeInputDefinition(InputDefinition $definition, array $options = []): void + { + $this->writeData($this->getInputDefinitionData($definition), $options); + } + + protected function describeCommand(Command $command, array $options = []): void + { + $this->writeData($this->getCommandData($command, $options['short'] ?? false), $options); + } + + protected function describeApplication(Application $application, array $options = []): void + { + $describedNamespace = $options['namespace'] ?? null; + $description = new ApplicationDescription($application, $describedNamespace, true); + $commands = []; + + foreach ($description->getCommands() as $command) { + $commands[] = $this->getCommandData($command, $options['short'] ?? false); + } + + $data = []; + if ('UNKNOWN' !== $application->getName()) { + $data['application']['name'] = $application->getName(); + if ('UNKNOWN' !== $application->getVersion()) { + $data['application']['version'] = $application->getVersion(); + } + } + + $data['commands'] = $commands; + + if ($describedNamespace) { + $data['namespace'] = $describedNamespace; + } else { + $data['namespaces'] = array_values($description->getNamespaces()); + } + + $this->writeData($data, $options); + } + + /** + * Writes data as json. + */ + private function writeData(array $data, array $options): void + { + $flags = $options['json_encoding'] ?? 0; + + $this->write(json_encode($data, $flags)); + } + + private function getInputArgumentData(InputArgument $argument): array + { + return [ + 'name' => $argument->getName(), + 'is_required' => $argument->isRequired(), + 'is_array' => $argument->isArray(), + 'description' => preg_replace('/\s*[\r\n]\s*/', ' ', $argument->getDescription()), + 'default' => \INF === $argument->getDefault() ? 'INF' : $argument->getDefault(), + ]; + } + + private function getInputOptionData(InputOption $option, bool $negated = false): array + { + return $negated ? [ + 'name' => '--no-'.$option->getName(), + 'shortcut' => '', + 'accept_value' => false, + 'is_value_required' => false, + 'is_multiple' => false, + 'description' => 'Negate the "--'.$option->getName().'" option', + 'default' => false, + ] : [ + 'name' => '--'.$option->getName(), + 'shortcut' => $option->getShortcut() ? '-'.str_replace('|', '|-', $option->getShortcut()) : '', + 'accept_value' => $option->acceptValue(), + 'is_value_required' => $option->isValueRequired(), + 'is_multiple' => $option->isArray(), + 'description' => preg_replace('/\s*[\r\n]\s*/', ' ', $option->getDescription()), + 'default' => \INF === $option->getDefault() ? 'INF' : $option->getDefault(), + ]; + } + + private function getInputDefinitionData(InputDefinition $definition): array + { + $inputArguments = []; + foreach ($definition->getArguments() as $name => $argument) { + $inputArguments[$name] = $this->getInputArgumentData($argument); + } + + $inputOptions = []; + foreach ($definition->getOptions() as $name => $option) { + $inputOptions[$name] = $this->getInputOptionData($option); + if ($option->isNegatable()) { + $inputOptions['no-'.$name] = $this->getInputOptionData($option, true); + } + } + + return ['arguments' => $inputArguments, 'options' => $inputOptions]; + } + + private function getCommandData(Command $command, bool $short = false): array + { + $data = [ + 'name' => $command->getName(), + 'description' => $command->getDescription(), + ]; + + if ($short) { + $data += [ + 'usage' => $command->getAliases(), + ]; + } else { + $command->mergeApplicationDefinition(false); + + $data += [ + 'usage' => array_merge([$command->getSynopsis()], $command->getUsages(), $command->getAliases()), + 'help' => $command->getProcessedHelp(), + 'definition' => $this->getInputDefinitionData($command->getDefinition()), + ]; + } + + $data['hidden'] = $command->isHidden(); + + return $data; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Descriptor/MarkdownDescriptor.php b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/MarkdownDescriptor.php new file mode 100644 index 00000000..b3f16ee9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/MarkdownDescriptor.php @@ -0,0 +1,173 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Descriptor; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Helper\Helper; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Markdown descriptor. + * + * @author Jean-François Simon + * + * @internal + */ +class MarkdownDescriptor extends Descriptor +{ + public function describe(OutputInterface $output, object $object, array $options = []): void + { + $decorated = $output->isDecorated(); + $output->setDecorated(false); + + parent::describe($output, $object, $options); + + $output->setDecorated($decorated); + } + + protected function write(string $content, bool $decorated = true): void + { + parent::write($content, $decorated); + } + + protected function describeInputArgument(InputArgument $argument, array $options = []): void + { + $this->write( + '#### `'.($argument->getName() ?: '')."`\n\n" + .($argument->getDescription() ? preg_replace('/\s*[\r\n]\s*/', "\n", $argument->getDescription())."\n\n" : '') + .'* Is required: '.($argument->isRequired() ? 'yes' : 'no')."\n" + .'* Is array: '.($argument->isArray() ? 'yes' : 'no')."\n" + .'* Default: `'.str_replace("\n", '', var_export($argument->getDefault(), true)).'`' + ); + } + + protected function describeInputOption(InputOption $option, array $options = []): void + { + $name = '--'.$option->getName(); + if ($option->isNegatable()) { + $name .= '|--no-'.$option->getName(); + } + if ($option->getShortcut()) { + $name .= '|-'.str_replace('|', '|-', $option->getShortcut()).''; + } + + $this->write( + '#### `'.$name.'`'."\n\n" + .($option->getDescription() ? preg_replace('/\s*[\r\n]\s*/', "\n", $option->getDescription())."\n\n" : '') + .'* Accept value: '.($option->acceptValue() ? 'yes' : 'no')."\n" + .'* Is value required: '.($option->isValueRequired() ? 'yes' : 'no')."\n" + .'* Is multiple: '.($option->isArray() ? 'yes' : 'no')."\n" + .'* Is negatable: '.($option->isNegatable() ? 'yes' : 'no')."\n" + .'* Default: `'.str_replace("\n", '', var_export($option->getDefault(), true)).'`' + ); + } + + protected function describeInputDefinition(InputDefinition $definition, array $options = []): void + { + if ($showArguments = \count($definition->getArguments()) > 0) { + $this->write('### Arguments'); + foreach ($definition->getArguments() as $argument) { + $this->write("\n\n"); + $this->describeInputArgument($argument); + } + } + + if (\count($definition->getOptions()) > 0) { + if ($showArguments) { + $this->write("\n\n"); + } + + $this->write('### Options'); + foreach ($definition->getOptions() as $option) { + $this->write("\n\n"); + $this->describeInputOption($option); + } + } + } + + protected function describeCommand(Command $command, array $options = []): void + { + if ($options['short'] ?? false) { + $this->write( + '`'.$command->getName()."`\n" + .str_repeat('-', Helper::width($command->getName()) + 2)."\n\n" + .($command->getDescription() ? $command->getDescription()."\n\n" : '') + .'### Usage'."\n\n" + .array_reduce($command->getAliases(), fn ($carry, $usage) => $carry.'* `'.$usage.'`'."\n") + ); + + return; + } + + $command->mergeApplicationDefinition(false); + + $this->write( + '`'.$command->getName()."`\n" + .str_repeat('-', Helper::width($command->getName()) + 2)."\n\n" + .($command->getDescription() ? $command->getDescription()."\n\n" : '') + .'### Usage'."\n\n" + .array_reduce(array_merge([$command->getSynopsis()], $command->getAliases(), $command->getUsages()), fn ($carry, $usage) => $carry.'* `'.$usage.'`'."\n") + ); + + if ($help = $command->getProcessedHelp()) { + $this->write("\n"); + $this->write($help); + } + + $definition = $command->getDefinition(); + if ($definition->getOptions() || $definition->getArguments()) { + $this->write("\n\n"); + $this->describeInputDefinition($definition); + } + } + + protected function describeApplication(Application $application, array $options = []): void + { + $describedNamespace = $options['namespace'] ?? null; + $description = new ApplicationDescription($application, $describedNamespace); + $title = $this->getApplicationTitle($application); + + $this->write($title."\n".str_repeat('=', Helper::width($title))); + + foreach ($description->getNamespaces() as $namespace) { + if (ApplicationDescription::GLOBAL_NAMESPACE !== $namespace['id']) { + $this->write("\n\n"); + $this->write('**'.$namespace['id'].':**'); + } + + $this->write("\n\n"); + $this->write(implode("\n", array_map(fn ($commandName) => sprintf('* [`%s`](#%s)', $commandName, str_replace(':', '', $description->getCommand($commandName)->getName())), $namespace['commands']))); + } + + foreach ($description->getCommands() as $command) { + $this->write("\n\n"); + $this->describeCommand($command, $options); + } + } + + private function getApplicationTitle(Application $application): string + { + if ('UNKNOWN' !== $application->getName()) { + if ('UNKNOWN' !== $application->getVersion()) { + return sprintf('%s %s', $application->getName(), $application->getVersion()); + } + + return $application->getName(); + } + + return 'Console Tool'; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Descriptor/ReStructuredTextDescriptor.php b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/ReStructuredTextDescriptor.php new file mode 100644 index 00000000..d4423fd3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/ReStructuredTextDescriptor.php @@ -0,0 +1,272 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Descriptor; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Helper\Helper; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\String\UnicodeString; + +class ReStructuredTextDescriptor extends Descriptor +{ + //

+ private string $partChar = '='; + //

+ private string $chapterChar = '-'; + //

+ private string $sectionChar = '~'; + //

+ private string $subsectionChar = '.'; + //

+ private string $subsubsectionChar = '^'; + //
+ private string $paragraphsChar = '"'; + + private array $visibleNamespaces = []; + + public function describe(OutputInterface $output, object $object, array $options = []): void + { + $decorated = $output->isDecorated(); + $output->setDecorated(false); + + parent::describe($output, $object, $options); + + $output->setDecorated($decorated); + } + + /** + * Override parent method to set $decorated = true. + */ + protected function write(string $content, bool $decorated = true): void + { + parent::write($content, $decorated); + } + + protected function describeInputArgument(InputArgument $argument, array $options = []): void + { + $this->write( + $argument->getName() ?: ''."\n".str_repeat($this->paragraphsChar, Helper::width($argument->getName()))."\n\n" + .($argument->getDescription() ? preg_replace('/\s*[\r\n]\s*/', "\n", $argument->getDescription())."\n\n" : '') + .'- **Is required**: '.($argument->isRequired() ? 'yes' : 'no')."\n" + .'- **Is array**: '.($argument->isArray() ? 'yes' : 'no')."\n" + .'- **Default**: ``'.str_replace("\n", '', var_export($argument->getDefault(), true)).'``' + ); + } + + protected function describeInputOption(InputOption $option, array $options = []): void + { + $name = '\-\-'.$option->getName(); + if ($option->isNegatable()) { + $name .= '|\-\-no-'.$option->getName(); + } + if ($option->getShortcut()) { + $name .= '|-'.str_replace('|', '|-', $option->getShortcut()); + } + + $optionDescription = $option->getDescription() ? preg_replace('/\s*[\r\n]\s*/', "\n\n", $option->getDescription())."\n\n" : ''; + $optionDescription = (new UnicodeString($optionDescription))->ascii(); + $this->write( + $name."\n".str_repeat($this->paragraphsChar, Helper::width($name))."\n\n" + .$optionDescription + .'- **Accept value**: '.($option->acceptValue() ? 'yes' : 'no')."\n" + .'- **Is value required**: '.($option->isValueRequired() ? 'yes' : 'no')."\n" + .'- **Is multiple**: '.($option->isArray() ? 'yes' : 'no')."\n" + .'- **Is negatable**: '.($option->isNegatable() ? 'yes' : 'no')."\n" + .'- **Default**: ``'.str_replace("\n", '', var_export($option->getDefault(), true)).'``'."\n" + ); + } + + protected function describeInputDefinition(InputDefinition $definition, array $options = []): void + { + if ($showArguments = ((bool) $definition->getArguments())) { + $this->write("Arguments\n".str_repeat($this->subsubsectionChar, 9))."\n\n"; + foreach ($definition->getArguments() as $argument) { + $this->write("\n\n"); + $this->describeInputArgument($argument); + } + } + + if ($nonDefaultOptions = $this->getNonDefaultOptions($definition)) { + if ($showArguments) { + $this->write("\n\n"); + } + + $this->write("Options\n".str_repeat($this->subsubsectionChar, 7)."\n\n"); + foreach ($nonDefaultOptions as $option) { + $this->describeInputOption($option); + $this->write("\n"); + } + } + } + + protected function describeCommand(Command $command, array $options = []): void + { + if ($options['short'] ?? false) { + $this->write( + '``'.$command->getName()."``\n" + .str_repeat($this->subsectionChar, Helper::width($command->getName()))."\n\n" + .($command->getDescription() ? $command->getDescription()."\n\n" : '') + ."Usage\n".str_repeat($this->paragraphsChar, 5)."\n\n" + .array_reduce($command->getAliases(), static fn ($carry, $usage) => $carry.'- ``'.$usage.'``'."\n") + ); + + return; + } + + $command->mergeApplicationDefinition(false); + + foreach ($command->getAliases() as $alias) { + $this->write('.. _'.$alias.":\n\n"); + } + $this->write( + $command->getName()."\n" + .str_repeat($this->subsectionChar, Helper::width($command->getName()))."\n\n" + .($command->getDescription() ? $command->getDescription()."\n\n" : '') + ."Usage\n".str_repeat($this->subsubsectionChar, 5)."\n\n" + .array_reduce(array_merge([$command->getSynopsis()], $command->getAliases(), $command->getUsages()), static fn ($carry, $usage) => $carry.'- ``'.$usage.'``'."\n") + ); + + if ($help = $command->getProcessedHelp()) { + $this->write("\n"); + $this->write($help); + } + + $definition = $command->getDefinition(); + if ($definition->getOptions() || $definition->getArguments()) { + $this->write("\n\n"); + $this->describeInputDefinition($definition); + } + } + + protected function describeApplication(Application $application, array $options = []): void + { + $description = new ApplicationDescription($application, $options['namespace'] ?? null); + $title = $this->getApplicationTitle($application); + + $this->write($title."\n".str_repeat($this->partChar, Helper::width($title))); + $this->createTableOfContents($description, $application); + $this->describeCommands($application, $options); + } + + private function getApplicationTitle(Application $application): string + { + if ('UNKNOWN' === $application->getName()) { + return 'Console Tool'; + } + if ('UNKNOWN' !== $application->getVersion()) { + return sprintf('%s %s', $application->getName(), $application->getVersion()); + } + + return $application->getName(); + } + + private function describeCommands($application, array $options): void + { + $title = 'Commands'; + $this->write("\n\n$title\n".str_repeat($this->chapterChar, Helper::width($title))."\n\n"); + foreach ($this->visibleNamespaces as $namespace) { + if ('_global' === $namespace) { + $commands = $application->all(''); + $this->write('Global'."\n".str_repeat($this->sectionChar, Helper::width('Global'))."\n\n"); + } else { + $commands = $application->all($namespace); + $this->write($namespace."\n".str_repeat($this->sectionChar, Helper::width($namespace))."\n\n"); + } + + foreach ($this->removeAliasesAndHiddenCommands($commands) as $command) { + $this->describeCommand($command, $options); + $this->write("\n\n"); + } + } + } + + private function createTableOfContents(ApplicationDescription $description, Application $application): void + { + $this->setVisibleNamespaces($description); + $chapterTitle = 'Table of Contents'; + $this->write("\n\n$chapterTitle\n".str_repeat($this->chapterChar, Helper::width($chapterTitle))."\n\n"); + foreach ($this->visibleNamespaces as $namespace) { + if ('_global' === $namespace) { + $commands = $application->all(''); + } else { + $commands = $application->all($namespace); + $this->write("\n\n"); + $this->write($namespace."\n".str_repeat($this->sectionChar, Helper::width($namespace))."\n\n"); + } + $commands = $this->removeAliasesAndHiddenCommands($commands); + + $this->write("\n\n"); + $this->write(implode("\n", array_map(static fn ($commandName) => sprintf('- `%s`_', $commandName), array_keys($commands)))); + } + } + + private function getNonDefaultOptions(InputDefinition $definition): array + { + $globalOptions = [ + 'help', + 'quiet', + 'verbose', + 'version', + 'ansi', + 'no-interaction', + ]; + $nonDefaultOptions = []; + foreach ($definition->getOptions() as $option) { + // Skip global options. + if (!\in_array($option->getName(), $globalOptions)) { + $nonDefaultOptions[] = $option; + } + } + + return $nonDefaultOptions; + } + + private function setVisibleNamespaces(ApplicationDescription $description): void + { + $commands = $description->getCommands(); + foreach ($description->getNamespaces() as $namespace) { + try { + $namespaceCommands = $namespace['commands']; + foreach ($namespaceCommands as $key => $commandName) { + if (!\array_key_exists($commandName, $commands)) { + // If the array key does not exist, then this is an alias. + unset($namespaceCommands[$key]); + } elseif ($commands[$commandName]->isHidden()) { + unset($namespaceCommands[$key]); + } + } + if (!$namespaceCommands) { + // If the namespace contained only aliases or hidden commands, skip the namespace. + continue; + } + } catch (\Exception) { + } + $this->visibleNamespaces[] = $namespace['id']; + } + } + + private function removeAliasesAndHiddenCommands(array $commands): array + { + foreach ($commands as $key => $command) { + if ($command->isHidden() || \in_array($key, $command->getAliases(), true)) { + unset($commands[$key]); + } + } + unset($commands['completion']); + + return $commands; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Descriptor/TextDescriptor.php b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/TextDescriptor.php new file mode 100644 index 00000000..d04d1023 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/TextDescriptor.php @@ -0,0 +1,317 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Descriptor; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Helper\Helper; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputOption; + +/** + * Text descriptor. + * + * @author Jean-François Simon + * + * @internal + */ +class TextDescriptor extends Descriptor +{ + protected function describeInputArgument(InputArgument $argument, array $options = []): void + { + if (null !== $argument->getDefault() && (!\is_array($argument->getDefault()) || \count($argument->getDefault()))) { + $default = sprintf(' [default: %s]', $this->formatDefaultValue($argument->getDefault())); + } else { + $default = ''; + } + + $totalWidth = $options['total_width'] ?? Helper::width($argument->getName()); + $spacingWidth = $totalWidth - \strlen($argument->getName()); + + $this->writeText(sprintf(' %s %s%s%s', + $argument->getName(), + str_repeat(' ', $spacingWidth), + // + 4 = 2 spaces before , 2 spaces after + preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 4), $argument->getDescription()), + $default + ), $options); + } + + protected function describeInputOption(InputOption $option, array $options = []): void + { + if ($option->acceptValue() && null !== $option->getDefault() && (!\is_array($option->getDefault()) || \count($option->getDefault()))) { + $default = sprintf(' [default: %s]', $this->formatDefaultValue($option->getDefault())); + } else { + $default = ''; + } + + $value = ''; + if ($option->acceptValue()) { + $value = '='.strtoupper($option->getName()); + + if ($option->isValueOptional()) { + $value = '['.$value.']'; + } + } + + $totalWidth = $options['total_width'] ?? $this->calculateTotalWidthForOptions([$option]); + $synopsis = sprintf('%s%s', + $option->getShortcut() ? sprintf('-%s, ', $option->getShortcut()) : ' ', + sprintf($option->isNegatable() ? '--%1$s|--no-%1$s' : '--%1$s%2$s', $option->getName(), $value) + ); + + $spacingWidth = $totalWidth - Helper::width($synopsis); + + $this->writeText(sprintf(' %s %s%s%s%s', + $synopsis, + str_repeat(' ', $spacingWidth), + // + 4 = 2 spaces before , 2 spaces after + preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 4), $option->getDescription()), + $default, + $option->isArray() ? ' (multiple values allowed)' : '' + ), $options); + } + + protected function describeInputDefinition(InputDefinition $definition, array $options = []): void + { + $totalWidth = $this->calculateTotalWidthForOptions($definition->getOptions()); + foreach ($definition->getArguments() as $argument) { + $totalWidth = max($totalWidth, Helper::width($argument->getName())); + } + + if ($definition->getArguments()) { + $this->writeText('Arguments:', $options); + $this->writeText("\n"); + foreach ($definition->getArguments() as $argument) { + $this->describeInputArgument($argument, array_merge($options, ['total_width' => $totalWidth])); + $this->writeText("\n"); + } + } + + if ($definition->getArguments() && $definition->getOptions()) { + $this->writeText("\n"); + } + + if ($definition->getOptions()) { + $laterOptions = []; + + $this->writeText('Options:', $options); + foreach ($definition->getOptions() as $option) { + if (\strlen($option->getShortcut() ?? '') > 1) { + $laterOptions[] = $option; + continue; + } + $this->writeText("\n"); + $this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth])); + } + foreach ($laterOptions as $option) { + $this->writeText("\n"); + $this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth])); + } + } + } + + protected function describeCommand(Command $command, array $options = []): void + { + $command->mergeApplicationDefinition(false); + + if ($description = $command->getDescription()) { + $this->writeText('Description:', $options); + $this->writeText("\n"); + $this->writeText(' '.$description); + $this->writeText("\n\n"); + } + + $this->writeText('Usage:', $options); + foreach (array_merge([$command->getSynopsis(true)], $command->getAliases(), $command->getUsages()) as $usage) { + $this->writeText("\n"); + $this->writeText(' '.OutputFormatter::escape($usage), $options); + } + $this->writeText("\n"); + + $definition = $command->getDefinition(); + if ($definition->getOptions() || $definition->getArguments()) { + $this->writeText("\n"); + $this->describeInputDefinition($definition, $options); + $this->writeText("\n"); + } + + $help = $command->getProcessedHelp(); + if ($help && $help !== $description) { + $this->writeText("\n"); + $this->writeText('Help:', $options); + $this->writeText("\n"); + $this->writeText(' '.str_replace("\n", "\n ", $help), $options); + $this->writeText("\n"); + } + } + + protected function describeApplication(Application $application, array $options = []): void + { + $describedNamespace = $options['namespace'] ?? null; + $description = new ApplicationDescription($application, $describedNamespace); + + if (isset($options['raw_text']) && $options['raw_text']) { + $width = $this->getColumnWidth($description->getCommands()); + + foreach ($description->getCommands() as $command) { + $this->writeText(sprintf("%-{$width}s %s", $command->getName(), $command->getDescription()), $options); + $this->writeText("\n"); + } + } else { + if ('' != $help = $application->getHelp()) { + $this->writeText("$help\n\n", $options); + } + + $this->writeText("Usage:\n", $options); + $this->writeText(" command [options] [arguments]\n\n", $options); + + $this->describeInputDefinition(new InputDefinition($application->getDefinition()->getOptions()), $options); + + $this->writeText("\n"); + $this->writeText("\n"); + + $commands = $description->getCommands(); + $namespaces = $description->getNamespaces(); + if ($describedNamespace && $namespaces) { + // make sure all alias commands are included when describing a specific namespace + $describedNamespaceInfo = reset($namespaces); + foreach ($describedNamespaceInfo['commands'] as $name) { + $commands[$name] = $description->getCommand($name); + } + } + + // calculate max. width based on available commands per namespace + $width = $this->getColumnWidth(array_merge(...array_values(array_map(fn ($namespace) => array_intersect($namespace['commands'], array_keys($commands)), array_values($namespaces))))); + + if ($describedNamespace) { + $this->writeText(sprintf('Available commands for the "%s" namespace:', $describedNamespace), $options); + } else { + $this->writeText('Available commands:', $options); + } + + foreach ($namespaces as $namespace) { + $namespace['commands'] = array_filter($namespace['commands'], fn ($name) => isset($commands[$name])); + + if (!$namespace['commands']) { + continue; + } + + if (!$describedNamespace && ApplicationDescription::GLOBAL_NAMESPACE !== $namespace['id']) { + $this->writeText("\n"); + $this->writeText(' '.$namespace['id'].'', $options); + } + + foreach ($namespace['commands'] as $name) { + $this->writeText("\n"); + $spacingWidth = $width - Helper::width($name); + $command = $commands[$name]; + $commandAliases = $name === $command->getName() ? $this->getCommandAliasesText($command) : ''; + $this->writeText(sprintf(' %s%s%s', $name, str_repeat(' ', $spacingWidth), $commandAliases.$command->getDescription()), $options); + } + } + + $this->writeText("\n"); + } + } + + private function writeText(string $content, array $options = []): void + { + $this->write( + isset($options['raw_text']) && $options['raw_text'] ? strip_tags($content) : $content, + isset($options['raw_output']) ? !$options['raw_output'] : true + ); + } + + /** + * Formats command aliases to show them in the command description. + */ + private function getCommandAliasesText(Command $command): string + { + $text = ''; + $aliases = $command->getAliases(); + + if ($aliases) { + $text = '['.implode('|', $aliases).'] '; + } + + return $text; + } + + /** + * Formats input option/argument default value. + */ + private function formatDefaultValue(mixed $default): string + { + if (\INF === $default) { + return 'INF'; + } + + if (\is_string($default)) { + $default = OutputFormatter::escape($default); + } elseif (\is_array($default)) { + foreach ($default as $key => $value) { + if (\is_string($value)) { + $default[$key] = OutputFormatter::escape($value); + } + } + } + + return str_replace('\\\\', '\\', json_encode($default, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE)); + } + + /** + * @param array $commands + */ + private function getColumnWidth(array $commands): int + { + $widths = []; + + foreach ($commands as $command) { + if ($command instanceof Command) { + $widths[] = Helper::width($command->getName()); + foreach ($command->getAliases() as $alias) { + $widths[] = Helper::width($alias); + } + } else { + $widths[] = Helper::width($command); + } + } + + return $widths ? max($widths) + 2 : 0; + } + + /** + * @param InputOption[] $options + */ + private function calculateTotalWidthForOptions(array $options): int + { + $totalWidth = 0; + foreach ($options as $option) { + // "-" + shortcut + ", --" + name + $nameLength = 1 + max(Helper::width($option->getShortcut()), 1) + 4 + Helper::width($option->getName()); + if ($option->isNegatable()) { + $nameLength += 6 + Helper::width($option->getName()); // |--no- + name + } elseif ($option->acceptValue()) { + $valueLength = 1 + Helper::width($option->getName()); // = + value + $valueLength += $option->isValueOptional() ? 2 : 0; // [ + ] + + $nameLength += $valueLength; + } + $totalWidth = max($totalWidth, $nameLength); + } + + return $totalWidth; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Descriptor/XmlDescriptor.php b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/XmlDescriptor.php new file mode 100644 index 00000000..72580fd9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Descriptor/XmlDescriptor.php @@ -0,0 +1,232 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Descriptor; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputOption; + +/** + * XML descriptor. + * + * @author Jean-François Simon + * + * @internal + */ +class XmlDescriptor extends Descriptor +{ + public function getInputDefinitionDocument(InputDefinition $definition): \DOMDocument + { + $dom = new \DOMDocument('1.0', 'UTF-8'); + $dom->appendChild($definitionXML = $dom->createElement('definition')); + + $definitionXML->appendChild($argumentsXML = $dom->createElement('arguments')); + foreach ($definition->getArguments() as $argument) { + $this->appendDocument($argumentsXML, $this->getInputArgumentDocument($argument)); + } + + $definitionXML->appendChild($optionsXML = $dom->createElement('options')); + foreach ($definition->getOptions() as $option) { + $this->appendDocument($optionsXML, $this->getInputOptionDocument($option)); + } + + return $dom; + } + + public function getCommandDocument(Command $command, bool $short = false): \DOMDocument + { + $dom = new \DOMDocument('1.0', 'UTF-8'); + $dom->appendChild($commandXML = $dom->createElement('command')); + + $commandXML->setAttribute('id', $command->getName()); + $commandXML->setAttribute('name', $command->getName()); + $commandXML->setAttribute('hidden', $command->isHidden() ? 1 : 0); + + $commandXML->appendChild($usagesXML = $dom->createElement('usages')); + + $commandXML->appendChild($descriptionXML = $dom->createElement('description')); + $descriptionXML->appendChild($dom->createTextNode(str_replace("\n", "\n ", $command->getDescription()))); + + if ($short) { + foreach ($command->getAliases() as $usage) { + $usagesXML->appendChild($dom->createElement('usage', $usage)); + } + } else { + $command->mergeApplicationDefinition(false); + + foreach (array_merge([$command->getSynopsis()], $command->getAliases(), $command->getUsages()) as $usage) { + $usagesXML->appendChild($dom->createElement('usage', $usage)); + } + + $commandXML->appendChild($helpXML = $dom->createElement('help')); + $helpXML->appendChild($dom->createTextNode(str_replace("\n", "\n ", $command->getProcessedHelp()))); + + $definitionXML = $this->getInputDefinitionDocument($command->getDefinition()); + $this->appendDocument($commandXML, $definitionXML->getElementsByTagName('definition')->item(0)); + } + + return $dom; + } + + public function getApplicationDocument(Application $application, string $namespace = null, bool $short = false): \DOMDocument + { + $dom = new \DOMDocument('1.0', 'UTF-8'); + $dom->appendChild($rootXml = $dom->createElement('symfony')); + + if ('UNKNOWN' !== $application->getName()) { + $rootXml->setAttribute('name', $application->getName()); + if ('UNKNOWN' !== $application->getVersion()) { + $rootXml->setAttribute('version', $application->getVersion()); + } + } + + $rootXml->appendChild($commandsXML = $dom->createElement('commands')); + + $description = new ApplicationDescription($application, $namespace, true); + + if ($namespace) { + $commandsXML->setAttribute('namespace', $namespace); + } + + foreach ($description->getCommands() as $command) { + $this->appendDocument($commandsXML, $this->getCommandDocument($command, $short)); + } + + if (!$namespace) { + $rootXml->appendChild($namespacesXML = $dom->createElement('namespaces')); + + foreach ($description->getNamespaces() as $namespaceDescription) { + $namespacesXML->appendChild($namespaceArrayXML = $dom->createElement('namespace')); + $namespaceArrayXML->setAttribute('id', $namespaceDescription['id']); + + foreach ($namespaceDescription['commands'] as $name) { + $namespaceArrayXML->appendChild($commandXML = $dom->createElement('command')); + $commandXML->appendChild($dom->createTextNode($name)); + } + } + } + + return $dom; + } + + protected function describeInputArgument(InputArgument $argument, array $options = []): void + { + $this->writeDocument($this->getInputArgumentDocument($argument)); + } + + protected function describeInputOption(InputOption $option, array $options = []): void + { + $this->writeDocument($this->getInputOptionDocument($option)); + } + + protected function describeInputDefinition(InputDefinition $definition, array $options = []): void + { + $this->writeDocument($this->getInputDefinitionDocument($definition)); + } + + protected function describeCommand(Command $command, array $options = []): void + { + $this->writeDocument($this->getCommandDocument($command, $options['short'] ?? false)); + } + + protected function describeApplication(Application $application, array $options = []): void + { + $this->writeDocument($this->getApplicationDocument($application, $options['namespace'] ?? null, $options['short'] ?? false)); + } + + /** + * Appends document children to parent node. + */ + private function appendDocument(\DOMNode $parentNode, \DOMNode $importedParent): void + { + foreach ($importedParent->childNodes as $childNode) { + $parentNode->appendChild($parentNode->ownerDocument->importNode($childNode, true)); + } + } + + /** + * Writes DOM document. + */ + private function writeDocument(\DOMDocument $dom): void + { + $dom->formatOutput = true; + $this->write($dom->saveXML()); + } + + private function getInputArgumentDocument(InputArgument $argument): \DOMDocument + { + $dom = new \DOMDocument('1.0', 'UTF-8'); + + $dom->appendChild($objectXML = $dom->createElement('argument')); + $objectXML->setAttribute('name', $argument->getName()); + $objectXML->setAttribute('is_required', $argument->isRequired() ? 1 : 0); + $objectXML->setAttribute('is_array', $argument->isArray() ? 1 : 0); + $objectXML->appendChild($descriptionXML = $dom->createElement('description')); + $descriptionXML->appendChild($dom->createTextNode($argument->getDescription())); + + $objectXML->appendChild($defaultsXML = $dom->createElement('defaults')); + $defaults = \is_array($argument->getDefault()) ? $argument->getDefault() : (\is_bool($argument->getDefault()) ? [var_export($argument->getDefault(), true)] : ($argument->getDefault() ? [$argument->getDefault()] : [])); + foreach ($defaults as $default) { + $defaultsXML->appendChild($defaultXML = $dom->createElement('default')); + $defaultXML->appendChild($dom->createTextNode($default)); + } + + return $dom; + } + + private function getInputOptionDocument(InputOption $option): \DOMDocument + { + $dom = new \DOMDocument('1.0', 'UTF-8'); + + $dom->appendChild($objectXML = $dom->createElement('option')); + $objectXML->setAttribute('name', '--'.$option->getName()); + $pos = strpos($option->getShortcut() ?? '', '|'); + if (false !== $pos) { + $objectXML->setAttribute('shortcut', '-'.substr($option->getShortcut(), 0, $pos)); + $objectXML->setAttribute('shortcuts', '-'.str_replace('|', '|-', $option->getShortcut())); + } else { + $objectXML->setAttribute('shortcut', $option->getShortcut() ? '-'.$option->getShortcut() : ''); + } + $objectXML->setAttribute('accept_value', $option->acceptValue() ? 1 : 0); + $objectXML->setAttribute('is_value_required', $option->isValueRequired() ? 1 : 0); + $objectXML->setAttribute('is_multiple', $option->isArray() ? 1 : 0); + $objectXML->appendChild($descriptionXML = $dom->createElement('description')); + $descriptionXML->appendChild($dom->createTextNode($option->getDescription())); + + if ($option->acceptValue()) { + $defaults = \is_array($option->getDefault()) ? $option->getDefault() : (\is_bool($option->getDefault()) ? [var_export($option->getDefault(), true)] : ($option->getDefault() ? [$option->getDefault()] : [])); + $objectXML->appendChild($defaultsXML = $dom->createElement('defaults')); + + if (!empty($defaults)) { + foreach ($defaults as $default) { + $defaultsXML->appendChild($defaultXML = $dom->createElement('default')); + $defaultXML->appendChild($dom->createTextNode($default)); + } + } + } + + if ($option->isNegatable()) { + $dom->appendChild($objectXML = $dom->createElement('option')); + $objectXML->setAttribute('name', '--no-'.$option->getName()); + $objectXML->setAttribute('shortcut', ''); + $objectXML->setAttribute('accept_value', 0); + $objectXML->setAttribute('is_value_required', 0); + $objectXML->setAttribute('is_multiple', 0); + $objectXML->appendChild($descriptionXML = $dom->createElement('description')); + $descriptionXML->appendChild($dom->createTextNode('Negate the "--'.$option->getName().'" option')); + } + + return $dom; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Event/ConsoleCommandEvent.php b/tools/php-cs-fixer/vendor/symfony/console/Event/ConsoleCommandEvent.php new file mode 100644 index 00000000..0757a23f --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Event/ConsoleCommandEvent.php @@ -0,0 +1,54 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Event; + +/** + * Allows to do things before the command is executed, like skipping the command or executing code before the command is + * going to be executed. + * + * Changing the input arguments will have no effect. + * + * @author Fabien Potencier + */ +final class ConsoleCommandEvent extends ConsoleEvent +{ + /** + * The return code for skipped commands, this will also be passed into the terminate event. + */ + public const RETURN_CODE_DISABLED = 113; + + /** + * Indicates if the command should be run or skipped. + */ + private bool $commandShouldRun = true; + + /** + * Disables the command, so it won't be run. + */ + public function disableCommand(): bool + { + return $this->commandShouldRun = false; + } + + public function enableCommand(): bool + { + return $this->commandShouldRun = true; + } + + /** + * Returns true if the command is runnable, false otherwise. + */ + public function commandShouldRun(): bool + { + return $this->commandShouldRun; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Event/ConsoleErrorEvent.php b/tools/php-cs-fixer/vendor/symfony/console/Event/ConsoleErrorEvent.php new file mode 100644 index 00000000..d4a69121 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Event/ConsoleErrorEvent.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Event; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Allows to handle throwables thrown while running a command. + * + * @author Wouter de Jong + */ +final class ConsoleErrorEvent extends ConsoleEvent +{ + private \Throwable $error; + private int $exitCode; + + public function __construct(InputInterface $input, OutputInterface $output, \Throwable $error, Command $command = null) + { + parent::__construct($command, $input, $output); + + $this->error = $error; + } + + public function getError(): \Throwable + { + return $this->error; + } + + public function setError(\Throwable $error): void + { + $this->error = $error; + } + + public function setExitCode(int $exitCode): void + { + $this->exitCode = $exitCode; + + $r = new \ReflectionProperty($this->error, 'code'); + $r->setValue($this->error, $this->exitCode); + } + + public function getExitCode(): int + { + return $this->exitCode ?? (\is_int($this->error->getCode()) && 0 !== $this->error->getCode() ? $this->error->getCode() : 1); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Event/ConsoleEvent.php b/tools/php-cs-fixer/vendor/symfony/console/Event/ConsoleEvent.php new file mode 100644 index 00000000..437a58e1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Event/ConsoleEvent.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Event; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Contracts\EventDispatcher\Event; + +/** + * Allows to inspect input and output of a command. + * + * @author Francesco Levorato + */ +class ConsoleEvent extends Event +{ + protected ?Command $command; + + private InputInterface $input; + private OutputInterface $output; + + public function __construct(?Command $command, InputInterface $input, OutputInterface $output) + { + $this->command = $command; + $this->input = $input; + $this->output = $output; + } + + /** + * Gets the command that is executed. + */ + public function getCommand(): ?Command + { + return $this->command; + } + + /** + * Gets the input instance. + */ + public function getInput(): InputInterface + { + return $this->input; + } + + /** + * Gets the output instance. + */ + public function getOutput(): OutputInterface + { + return $this->output; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Event/ConsoleSignalEvent.php b/tools/php-cs-fixer/vendor/symfony/console/Event/ConsoleSignalEvent.php new file mode 100644 index 00000000..95af1f91 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Event/ConsoleSignalEvent.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Event; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author marie + */ +final class ConsoleSignalEvent extends ConsoleEvent +{ + private int $handlingSignal; + private int|false $exitCode; + + public function __construct(Command $command, InputInterface $input, OutputInterface $output, int $handlingSignal, int|false $exitCode = 0) + { + parent::__construct($command, $input, $output); + $this->handlingSignal = $handlingSignal; + $this->exitCode = $exitCode; + } + + public function getHandlingSignal(): int + { + return $this->handlingSignal; + } + + public function setExitCode(int $exitCode): void + { + if ($exitCode < 0 || $exitCode > 255) { + throw new \InvalidArgumentException('Exit code must be between 0 and 255.'); + } + + $this->exitCode = $exitCode; + } + + public function abortExit(): void + { + $this->exitCode = false; + } + + public function getExitCode(): int|false + { + return $this->exitCode; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Event/ConsoleTerminateEvent.php b/tools/php-cs-fixer/vendor/symfony/console/Event/ConsoleTerminateEvent.php new file mode 100644 index 00000000..38f7253a --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Event/ConsoleTerminateEvent.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Event; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Allows to manipulate the exit code of a command after its execution. + * + * @author Francesco Levorato + * @author Jules Pietri + */ +final class ConsoleTerminateEvent extends ConsoleEvent +{ + public function __construct( + Command $command, + InputInterface $input, + OutputInterface $output, + private int $exitCode, + private readonly ?int $interruptingSignal = null, + ) { + parent::__construct($command, $input, $output); + } + + public function setExitCode(int $exitCode): void + { + $this->exitCode = $exitCode; + } + + public function getExitCode(): int + { + return $this->exitCode; + } + + public function getInterruptingSignal(): ?int + { + return $this->interruptingSignal; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/EventListener/ErrorListener.php b/tools/php-cs-fixer/vendor/symfony/console/EventListener/ErrorListener.php new file mode 100644 index 00000000..5c38e8ef --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/EventListener/ErrorListener.php @@ -0,0 +1,95 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\EventListener; + +use Psr\Log\LoggerInterface; +use Symfony\Component\Console\ConsoleEvents; +use Symfony\Component\Console\Event\ConsoleErrorEvent; +use Symfony\Component\Console\Event\ConsoleEvent; +use Symfony\Component\Console\Event\ConsoleTerminateEvent; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; + +/** + * @author James Halsall + * @author Robin Chalas + */ +class ErrorListener implements EventSubscriberInterface +{ + private ?LoggerInterface $logger; + + public function __construct(LoggerInterface $logger = null) + { + $this->logger = $logger; + } + + public function onConsoleError(ConsoleErrorEvent $event): void + { + if (null === $this->logger) { + return; + } + + $error = $event->getError(); + + if (!$inputString = $this->getInputString($event)) { + $this->logger->critical('An error occurred while using the console. Message: "{message}"', ['exception' => $error, 'message' => $error->getMessage()]); + + return; + } + + $this->logger->critical('Error thrown while running command "{command}". Message: "{message}"', ['exception' => $error, 'command' => $inputString, 'message' => $error->getMessage()]); + } + + public function onConsoleTerminate(ConsoleTerminateEvent $event): void + { + if (null === $this->logger) { + return; + } + + $exitCode = $event->getExitCode(); + + if (0 === $exitCode) { + return; + } + + if (!$inputString = $this->getInputString($event)) { + $this->logger->debug('The console exited with code "{code}"', ['code' => $exitCode]); + + return; + } + + $this->logger->debug('Command "{command}" exited with code "{code}"', ['command' => $inputString, 'code' => $exitCode]); + } + + public static function getSubscribedEvents(): array + { + return [ + ConsoleEvents::ERROR => ['onConsoleError', -128], + ConsoleEvents::TERMINATE => ['onConsoleTerminate', -128], + ]; + } + + private static function getInputString(ConsoleEvent $event): ?string + { + $commandName = $event->getCommand()?->getName(); + $input = $event->getInput(); + + if ($input instanceof \Stringable) { + if ($commandName) { + return str_replace(["'$commandName'", "\"$commandName\""], $commandName, (string) $input); + } + + return (string) $input; + } + + return $commandName; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Exception/CommandNotFoundException.php b/tools/php-cs-fixer/vendor/symfony/console/Exception/CommandNotFoundException.php new file mode 100644 index 00000000..1e9f1c79 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Exception/CommandNotFoundException.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * Represents an incorrect command name typed in the console. + * + * @author Jérôme Tamarelle + */ +class CommandNotFoundException extends \InvalidArgumentException implements ExceptionInterface +{ + private array $alternatives; + + /** + * @param string $message Exception message to throw + * @param string[] $alternatives List of similar defined names + * @param int $code Exception code + * @param \Throwable|null $previous Previous exception used for the exception chaining + */ + public function __construct(string $message, array $alternatives = [], int $code = 0, \Throwable $previous = null) + { + parent::__construct($message, $code, $previous); + + $this->alternatives = $alternatives; + } + + /** + * @return string[] + */ + public function getAlternatives(): array + { + return $this->alternatives; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Exception/ExceptionInterface.php b/tools/php-cs-fixer/vendor/symfony/console/Exception/ExceptionInterface.php new file mode 100644 index 00000000..1624e13d --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Exception/ExceptionInterface.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * ExceptionInterface. + * + * @author Jérôme Tamarelle + */ +interface ExceptionInterface extends \Throwable +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Exception/InvalidArgumentException.php b/tools/php-cs-fixer/vendor/symfony/console/Exception/InvalidArgumentException.php new file mode 100644 index 00000000..07cc0b61 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Exception/InvalidArgumentException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * @author Jérôme Tamarelle + */ +class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Exception/InvalidOptionException.php b/tools/php-cs-fixer/vendor/symfony/console/Exception/InvalidOptionException.php new file mode 100644 index 00000000..5cf62792 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Exception/InvalidOptionException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * Represents an incorrect option name or value typed in the console. + * + * @author Jérôme Tamarelle + */ +class InvalidOptionException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Exception/LogicException.php b/tools/php-cs-fixer/vendor/symfony/console/Exception/LogicException.php new file mode 100644 index 00000000..fc37b8d8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Exception/LogicException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * @author Jérôme Tamarelle + */ +class LogicException extends \LogicException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Exception/MissingInputException.php b/tools/php-cs-fixer/vendor/symfony/console/Exception/MissingInputException.php new file mode 100644 index 00000000..04f02ade --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Exception/MissingInputException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * Represents failure to read input from stdin. + * + * @author Gabriel Ostrolucký + */ +class MissingInputException extends RuntimeException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Exception/NamespaceNotFoundException.php b/tools/php-cs-fixer/vendor/symfony/console/Exception/NamespaceNotFoundException.php new file mode 100644 index 00000000..dd16e450 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Exception/NamespaceNotFoundException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * Represents an incorrect namespace typed in the console. + * + * @author Pierre du Plessis + */ +class NamespaceNotFoundException extends CommandNotFoundException +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Exception/RunCommandFailedException.php b/tools/php-cs-fixer/vendor/symfony/console/Exception/RunCommandFailedException.php new file mode 100644 index 00000000..5d87ec94 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Exception/RunCommandFailedException.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +use Symfony\Component\Console\Messenger\RunCommandContext; + +/** + * @author Kevin Bond + */ +final class RunCommandFailedException extends RuntimeException +{ + public function __construct(\Throwable|string $exception, public readonly RunCommandContext $context) + { + parent::__construct( + $exception instanceof \Throwable ? $exception->getMessage() : $exception, + $exception instanceof \Throwable ? $exception->getCode() : 0, + $exception instanceof \Throwable ? $exception : null, + ); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Exception/RuntimeException.php b/tools/php-cs-fixer/vendor/symfony/console/Exception/RuntimeException.php new file mode 100644 index 00000000..51d7d80a --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Exception/RuntimeException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Exception; + +/** + * @author Jérôme Tamarelle + */ +class RuntimeException extends \RuntimeException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Formatter/NullOutputFormatter.php b/tools/php-cs-fixer/vendor/symfony/console/Formatter/NullOutputFormatter.php new file mode 100644 index 00000000..5c11c764 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Formatter/NullOutputFormatter.php @@ -0,0 +1,51 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +/** + * @author Tien Xuan Vo + */ +final class NullOutputFormatter implements OutputFormatterInterface +{ + private NullOutputFormatterStyle $style; + + public function format(?string $message): ?string + { + return null; + } + + public function getStyle(string $name): OutputFormatterStyleInterface + { + // to comply with the interface we must return a OutputFormatterStyleInterface + return $this->style ??= new NullOutputFormatterStyle(); + } + + public function hasStyle(string $name): bool + { + return false; + } + + public function isDecorated(): bool + { + return false; + } + + public function setDecorated(bool $decorated): void + { + // do nothing + } + + public function setStyle(string $name, OutputFormatterStyleInterface $style): void + { + // do nothing + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Formatter/NullOutputFormatterStyle.php b/tools/php-cs-fixer/vendor/symfony/console/Formatter/NullOutputFormatterStyle.php new file mode 100644 index 00000000..06fa6e40 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Formatter/NullOutputFormatterStyle.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +/** + * @author Tien Xuan Vo + */ +final class NullOutputFormatterStyle implements OutputFormatterStyleInterface +{ + public function apply(string $text): string + { + return $text; + } + + public function setBackground(?string $color): void + { + // do nothing + } + + public function setForeground(?string $color): void + { + // do nothing + } + + public function setOption(string $option): void + { + // do nothing + } + + public function setOptions(array $options): void + { + // do nothing + } + + public function unsetOption(string $option): void + { + // do nothing + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Formatter/OutputFormatter.php b/tools/php-cs-fixer/vendor/symfony/console/Formatter/OutputFormatter.php new file mode 100644 index 00000000..8e81e590 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Formatter/OutputFormatter.php @@ -0,0 +1,268 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +use Symfony\Component\Console\Exception\InvalidArgumentException; + +use function Symfony\Component\String\b; + +/** + * Formatter class for console output. + * + * @author Konstantin Kudryashov + * @author Roland Franssen + */ +class OutputFormatter implements WrappableOutputFormatterInterface +{ + private bool $decorated; + private array $styles = []; + private OutputFormatterStyleStack $styleStack; + + public function __clone() + { + $this->styleStack = clone $this->styleStack; + foreach ($this->styles as $key => $value) { + $this->styles[$key] = clone $value; + } + } + + /** + * Escapes "<" and ">" special chars in given text. + */ + public static function escape(string $text): string + { + $text = preg_replace('/([^\\\\]|^)([<>])/', '$1\\\\$2', $text); + + return self::escapeTrailingBackslash($text); + } + + /** + * Escapes trailing "\" in given text. + * + * @internal + */ + public static function escapeTrailingBackslash(string $text): string + { + if (str_ends_with($text, '\\')) { + $len = \strlen($text); + $text = rtrim($text, '\\'); + $text = str_replace("\0", '', $text); + $text .= str_repeat("\0", $len - \strlen($text)); + } + + return $text; + } + + /** + * Initializes console output formatter. + * + * @param OutputFormatterStyleInterface[] $styles Array of "name => FormatterStyle" instances + */ + public function __construct(bool $decorated = false, array $styles = []) + { + $this->decorated = $decorated; + + $this->setStyle('error', new OutputFormatterStyle('white', 'red')); + $this->setStyle('info', new OutputFormatterStyle('green')); + $this->setStyle('comment', new OutputFormatterStyle('yellow')); + $this->setStyle('question', new OutputFormatterStyle('black', 'cyan')); + + foreach ($styles as $name => $style) { + $this->setStyle($name, $style); + } + + $this->styleStack = new OutputFormatterStyleStack(); + } + + public function setDecorated(bool $decorated): void + { + $this->decorated = $decorated; + } + + public function isDecorated(): bool + { + return $this->decorated; + } + + public function setStyle(string $name, OutputFormatterStyleInterface $style): void + { + $this->styles[strtolower($name)] = $style; + } + + public function hasStyle(string $name): bool + { + return isset($this->styles[strtolower($name)]); + } + + public function getStyle(string $name): OutputFormatterStyleInterface + { + if (!$this->hasStyle($name)) { + throw new InvalidArgumentException(sprintf('Undefined style: "%s".', $name)); + } + + return $this->styles[strtolower($name)]; + } + + public function format(?string $message): ?string + { + return $this->formatAndWrap($message, 0); + } + + public function formatAndWrap(?string $message, int $width): string + { + if (null === $message) { + return ''; + } + + $offset = 0; + $output = ''; + $openTagRegex = '[a-z](?:[^\\\\<>]*+ | \\\\.)*'; + $closeTagRegex = '[a-z][^<>]*+'; + $currentLineLength = 0; + preg_match_all("#<(($openTagRegex) | /($closeTagRegex)?)>#ix", $message, $matches, \PREG_OFFSET_CAPTURE); + foreach ($matches[0] as $i => $match) { + $pos = $match[1]; + $text = $match[0]; + + if (0 != $pos && '\\' == $message[$pos - 1]) { + continue; + } + + // add the text up to the next tag + $output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset), $output, $width, $currentLineLength); + $offset = $pos + \strlen($text); + + // opening tag? + if ($open = '/' !== $text[1]) { + $tag = $matches[1][$i][0]; + } else { + $tag = $matches[3][$i][0] ?? ''; + } + + if (!$open && !$tag) { + // + $this->styleStack->pop(); + } elseif (null === $style = $this->createStyleFromString($tag)) { + $output .= $this->applyCurrentStyle($text, $output, $width, $currentLineLength); + } elseif ($open) { + $this->styleStack->push($style); + } else { + $this->styleStack->pop($style); + } + } + + $output .= $this->applyCurrentStyle(substr($message, $offset), $output, $width, $currentLineLength); + + return strtr($output, ["\0" => '\\', '\\<' => '<', '\\>' => '>']); + } + + public function getStyleStack(): OutputFormatterStyleStack + { + return $this->styleStack; + } + + /** + * Tries to create new style instance from string. + */ + private function createStyleFromString(string $string): ?OutputFormatterStyleInterface + { + if (isset($this->styles[$string])) { + return $this->styles[$string]; + } + + if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', $string, $matches, \PREG_SET_ORDER)) { + return null; + } + + $style = new OutputFormatterStyle(); + foreach ($matches as $match) { + array_shift($match); + $match[0] = strtolower($match[0]); + + if ('fg' == $match[0]) { + $style->setForeground(strtolower($match[1])); + } elseif ('bg' == $match[0]) { + $style->setBackground(strtolower($match[1])); + } elseif ('href' === $match[0]) { + $url = preg_replace('{\\\\([<>])}', '$1', $match[1]); + $style->setHref($url); + } elseif ('options' === $match[0]) { + preg_match_all('([^,;]+)', strtolower($match[1]), $options); + $options = array_shift($options); + foreach ($options as $option) { + $style->setOption($option); + } + } else { + return null; + } + } + + return $style; + } + + /** + * Applies current style from stack to text, if must be applied. + */ + private function applyCurrentStyle(string $text, string $current, int $width, int &$currentLineLength): string + { + if ('' === $text) { + return ''; + } + + if (!$width) { + return $this->isDecorated() ? $this->styleStack->getCurrent()->apply($text) : $text; + } + + if (!$currentLineLength && '' !== $current) { + $text = ltrim($text); + } + + if ($currentLineLength) { + $prefix = substr($text, 0, $i = $width - $currentLineLength)."\n"; + $text = substr($text, $i); + } else { + $prefix = ''; + } + + preg_match('~(\\n)$~', $text, $matches); + $text = $prefix.$this->addLineBreaks($text, $width); + $text = rtrim($text, "\n").($matches[1] ?? ''); + + if (!$currentLineLength && '' !== $current && !str_ends_with($current, "\n")) { + $text = "\n".$text; + } + + $lines = explode("\n", $text); + + foreach ($lines as $line) { + $currentLineLength += \strlen($line); + if ($width <= $currentLineLength) { + $currentLineLength = 0; + } + } + + if ($this->isDecorated()) { + foreach ($lines as $i => $line) { + $lines[$i] = $this->styleStack->getCurrent()->apply($line); + } + } + + return implode("\n", $lines); + } + + private function addLineBreaks(string $text, int $width): string + { + $encoding = mb_detect_encoding($text, null, true) ?: 'UTF-8'; + + return b($text)->toCodePointString($encoding)->wordwrap($width, "\n", true)->toByteString($encoding); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Formatter/OutputFormatterInterface.php b/tools/php-cs-fixer/vendor/symfony/console/Formatter/OutputFormatterInterface.php new file mode 100644 index 00000000..947347fa --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Formatter/OutputFormatterInterface.php @@ -0,0 +1,52 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +/** + * Formatter interface for console output. + * + * @author Konstantin Kudryashov + */ +interface OutputFormatterInterface +{ + /** + * Sets the decorated flag. + */ + public function setDecorated(bool $decorated): void; + + /** + * Whether the output will decorate messages. + */ + public function isDecorated(): bool; + + /** + * Sets a new style. + */ + public function setStyle(string $name, OutputFormatterStyleInterface $style): void; + + /** + * Checks if output formatter has style with specified name. + */ + public function hasStyle(string $name): bool; + + /** + * Gets style options from style with specified name. + * + * @throws \InvalidArgumentException When style isn't defined + */ + public function getStyle(string $name): OutputFormatterStyleInterface; + + /** + * Formats a message according to the given styles. + */ + public function format(?string $message): ?string; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Formatter/OutputFormatterStyle.php b/tools/php-cs-fixer/vendor/symfony/console/Formatter/OutputFormatterStyle.php new file mode 100644 index 00000000..4582ccd0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Formatter/OutputFormatterStyle.php @@ -0,0 +1,89 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +use Symfony\Component\Console\Color; + +/** + * Formatter style class for defining styles. + * + * @author Konstantin Kudryashov + */ +class OutputFormatterStyle implements OutputFormatterStyleInterface +{ + private Color $color; + private string $foreground; + private string $background; + private array $options; + private ?string $href = null; + private bool $handlesHrefGracefully; + + /** + * Initializes output formatter style. + * + * @param string|null $foreground The style foreground color name + * @param string|null $background The style background color name + */ + public function __construct(string $foreground = null, string $background = null, array $options = []) + { + $this->color = new Color($this->foreground = $foreground ?: '', $this->background = $background ?: '', $this->options = $options); + } + + public function setForeground(?string $color): void + { + $this->color = new Color($this->foreground = $color ?: '', $this->background, $this->options); + } + + public function setBackground(?string $color): void + { + $this->color = new Color($this->foreground, $this->background = $color ?: '', $this->options); + } + + public function setHref(string $url): void + { + $this->href = $url; + } + + public function setOption(string $option): void + { + $this->options[] = $option; + $this->color = new Color($this->foreground, $this->background, $this->options); + } + + public function unsetOption(string $option): void + { + $pos = array_search($option, $this->options); + if (false !== $pos) { + unset($this->options[$pos]); + } + + $this->color = new Color($this->foreground, $this->background, $this->options); + } + + public function setOptions(array $options): void + { + $this->color = new Color($this->foreground, $this->background, $this->options = $options); + } + + public function apply(string $text): string + { + $this->handlesHrefGracefully ??= 'JetBrains-JediTerm' !== getenv('TERMINAL_EMULATOR') + && (!getenv('KONSOLE_VERSION') || (int) getenv('KONSOLE_VERSION') > 201100) + && !isset($_SERVER['IDEA_INITIAL_DIRECTORY']); + + if (null !== $this->href && $this->handlesHrefGracefully) { + $text = "\033]8;;$this->href\033\\$text\033]8;;\033\\"; + } + + return $this->color->apply($text); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Formatter/OutputFormatterStyleInterface.php b/tools/php-cs-fixer/vendor/symfony/console/Formatter/OutputFormatterStyleInterface.php new file mode 100644 index 00000000..03741927 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Formatter/OutputFormatterStyleInterface.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +/** + * Formatter style interface for defining styles. + * + * @author Konstantin Kudryashov + */ +interface OutputFormatterStyleInterface +{ + /** + * Sets style foreground color. + */ + public function setForeground(?string $color): void; + + /** + * Sets style background color. + */ + public function setBackground(?string $color): void; + + /** + * Sets some specific style option. + */ + public function setOption(string $option): void; + + /** + * Unsets some specific style option. + */ + public function unsetOption(string $option): void; + + /** + * Sets multiple style options at once. + */ + public function setOptions(array $options): void; + + /** + * Applies the style to a given text. + */ + public function apply(string $text): string; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Formatter/OutputFormatterStyleStack.php b/tools/php-cs-fixer/vendor/symfony/console/Formatter/OutputFormatterStyleStack.php new file mode 100644 index 00000000..c3726a35 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Formatter/OutputFormatterStyleStack.php @@ -0,0 +1,103 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Contracts\Service\ResetInterface; + +/** + * @author Jean-François Simon + */ +class OutputFormatterStyleStack implements ResetInterface +{ + /** + * @var OutputFormatterStyleInterface[] + */ + private array $styles = []; + + private OutputFormatterStyleInterface $emptyStyle; + + public function __construct(OutputFormatterStyleInterface $emptyStyle = null) + { + $this->emptyStyle = $emptyStyle ?? new OutputFormatterStyle(); + $this->reset(); + } + + /** + * Resets stack (ie. empty internal arrays). + */ + public function reset(): void + { + $this->styles = []; + } + + /** + * Pushes a style in the stack. + */ + public function push(OutputFormatterStyleInterface $style): void + { + $this->styles[] = $style; + } + + /** + * Pops a style from the stack. + * + * @throws InvalidArgumentException When style tags incorrectly nested + */ + public function pop(OutputFormatterStyleInterface $style = null): OutputFormatterStyleInterface + { + if (!$this->styles) { + return $this->emptyStyle; + } + + if (null === $style) { + return array_pop($this->styles); + } + + foreach (array_reverse($this->styles, true) as $index => $stackedStyle) { + if ($style->apply('') === $stackedStyle->apply('')) { + $this->styles = \array_slice($this->styles, 0, $index); + + return $stackedStyle; + } + } + + throw new InvalidArgumentException('Incorrectly nested style tag found.'); + } + + /** + * Computes current style with stacks top codes. + */ + public function getCurrent(): OutputFormatterStyleInterface + { + if (!$this->styles) { + return $this->emptyStyle; + } + + return $this->styles[\count($this->styles) - 1]; + } + + /** + * @return $this + */ + public function setEmptyStyle(OutputFormatterStyleInterface $emptyStyle): static + { + $this->emptyStyle = $emptyStyle; + + return $this; + } + + public function getEmptyStyle(): OutputFormatterStyleInterface + { + return $this->emptyStyle; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Formatter/WrappableOutputFormatterInterface.php b/tools/php-cs-fixer/vendor/symfony/console/Formatter/WrappableOutputFormatterInterface.php new file mode 100644 index 00000000..412d9976 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Formatter/WrappableOutputFormatterInterface.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Formatter; + +/** + * Formatter interface for console output that supports word wrapping. + * + * @author Roland Franssen + */ +interface WrappableOutputFormatterInterface extends OutputFormatterInterface +{ + /** + * Formats a message according to the given styles, wrapping at `$width` (0 means no wrapping). + */ + public function formatAndWrap(?string $message, int $width): string; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/DebugFormatterHelper.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/DebugFormatterHelper.php new file mode 100644 index 00000000..9ea7fb91 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/DebugFormatterHelper.php @@ -0,0 +1,98 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +/** + * Helps outputting debug information when running an external program from a command. + * + * An external program can be a Process, an HTTP request, or anything else. + * + * @author Fabien Potencier + */ +class DebugFormatterHelper extends Helper +{ + private const COLORS = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'default']; + private array $started = []; + private int $count = -1; + + /** + * Starts a debug formatting session. + */ + public function start(string $id, string $message, string $prefix = 'RUN'): string + { + $this->started[$id] = ['border' => ++$this->count % \count(self::COLORS)]; + + return sprintf("%s %s %s\n", $this->getBorder($id), $prefix, $message); + } + + /** + * Adds progress to a formatting session. + */ + public function progress(string $id, string $buffer, bool $error = false, string $prefix = 'OUT', string $errorPrefix = 'ERR'): string + { + $message = ''; + + if ($error) { + if (isset($this->started[$id]['out'])) { + $message .= "\n"; + unset($this->started[$id]['out']); + } + if (!isset($this->started[$id]['err'])) { + $message .= sprintf('%s %s ', $this->getBorder($id), $errorPrefix); + $this->started[$id]['err'] = true; + } + + $message .= str_replace("\n", sprintf("\n%s %s ", $this->getBorder($id), $errorPrefix), $buffer); + } else { + if (isset($this->started[$id]['err'])) { + $message .= "\n"; + unset($this->started[$id]['err']); + } + if (!isset($this->started[$id]['out'])) { + $message .= sprintf('%s %s ', $this->getBorder($id), $prefix); + $this->started[$id]['out'] = true; + } + + $message .= str_replace("\n", sprintf("\n%s %s ", $this->getBorder($id), $prefix), $buffer); + } + + return $message; + } + + /** + * Stops a formatting session. + */ + public function stop(string $id, string $message, bool $successful, string $prefix = 'RES'): string + { + $trailingEOL = isset($this->started[$id]['out']) || isset($this->started[$id]['err']) ? "\n" : ''; + + if ($successful) { + return sprintf("%s%s %s %s\n", $trailingEOL, $this->getBorder($id), $prefix, $message); + } + + $message = sprintf("%s%s %s %s\n", $trailingEOL, $this->getBorder($id), $prefix, $message); + + unset($this->started[$id]['out'], $this->started[$id]['err']); + + return $message; + } + + private function getBorder(string $id): string + { + return sprintf(' ', self::COLORS[$this->started[$id]['border']]); + } + + public function getName(): string + { + return 'debug_formatter'; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/DescriptorHelper.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/DescriptorHelper.php new file mode 100644 index 00000000..300c7b10 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/DescriptorHelper.php @@ -0,0 +1,91 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Descriptor\DescriptorInterface; +use Symfony\Component\Console\Descriptor\JsonDescriptor; +use Symfony\Component\Console\Descriptor\MarkdownDescriptor; +use Symfony\Component\Console\Descriptor\ReStructuredTextDescriptor; +use Symfony\Component\Console\Descriptor\TextDescriptor; +use Symfony\Component\Console\Descriptor\XmlDescriptor; +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * This class adds helper method to describe objects in various formats. + * + * @author Jean-François Simon + */ +class DescriptorHelper extends Helper +{ + /** + * @var DescriptorInterface[] + */ + private array $descriptors = []; + + public function __construct() + { + $this + ->register('txt', new TextDescriptor()) + ->register('xml', new XmlDescriptor()) + ->register('json', new JsonDescriptor()) + ->register('md', new MarkdownDescriptor()) + ->register('rst', new ReStructuredTextDescriptor()) + ; + } + + /** + * Describes an object if supported. + * + * Available options are: + * * format: string, the output format name + * * raw_text: boolean, sets output type as raw + * + * @throws InvalidArgumentException when the given format is not supported + */ + public function describe(OutputInterface $output, ?object $object, array $options = []): void + { + $options = array_merge([ + 'raw_text' => false, + 'format' => 'txt', + ], $options); + + if (!isset($this->descriptors[$options['format']])) { + throw new InvalidArgumentException(sprintf('Unsupported format "%s".', $options['format'])); + } + + $descriptor = $this->descriptors[$options['format']]; + $descriptor->describe($output, $object, $options); + } + + /** + * Registers a descriptor. + * + * @return $this + */ + public function register(string $format, DescriptorInterface $descriptor): static + { + $this->descriptors[$format] = $descriptor; + + return $this; + } + + public function getName(): string + { + return 'descriptor'; + } + + public function getFormats(): array + { + return array_keys($this->descriptors); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/Dumper.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/Dumper.php new file mode 100644 index 00000000..8c6a94d5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/Dumper.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\VarDumper\Cloner\ClonerInterface; +use Symfony\Component\VarDumper\Cloner\VarCloner; +use Symfony\Component\VarDumper\Dumper\CliDumper; + +/** + * @author Roland Franssen + */ +final class Dumper +{ + private OutputInterface $output; + private ?CliDumper $dumper; + private ?ClonerInterface $cloner; + private \Closure $handler; + + public function __construct(OutputInterface $output, CliDumper $dumper = null, ClonerInterface $cloner = null) + { + $this->output = $output; + $this->dumper = $dumper; + $this->cloner = $cloner; + + if (class_exists(CliDumper::class)) { + $this->handler = function ($var): string { + $dumper = $this->dumper ??= new CliDumper(null, null, CliDumper::DUMP_LIGHT_ARRAY | CliDumper::DUMP_COMMA_SEPARATOR); + $dumper->setColors($this->output->isDecorated()); + + return rtrim($dumper->dump(($this->cloner ??= new VarCloner())->cloneVar($var)->withRefHandles(false), true)); + }; + } else { + $this->handler = fn ($var): string => match (true) { + null === $var => 'null', + true === $var => 'true', + false === $var => 'false', + \is_string($var) => '"'.$var.'"', + default => rtrim(print_r($var, true)), + }; + } + } + + public function __invoke(mixed $var): string + { + return ($this->handler)($var); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/FormatterHelper.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/FormatterHelper.php new file mode 100644 index 00000000..279e4c79 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/FormatterHelper.php @@ -0,0 +1,81 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * The Formatter class provides helpers to format messages. + * + * @author Fabien Potencier + */ +class FormatterHelper extends Helper +{ + /** + * Formats a message within a section. + */ + public function formatSection(string $section, string $message, string $style = 'info'): string + { + return sprintf('<%s>[%s] %s', $style, $section, $style, $message); + } + + /** + * Formats a message as a block of text. + */ + public function formatBlock(string|array $messages, string $style, bool $large = false): string + { + if (!\is_array($messages)) { + $messages = [$messages]; + } + + $len = 0; + $lines = []; + foreach ($messages as $message) { + $message = OutputFormatter::escape($message); + $lines[] = sprintf($large ? ' %s ' : ' %s ', $message); + $len = max(self::width($message) + ($large ? 4 : 2), $len); + } + + $messages = $large ? [str_repeat(' ', $len)] : []; + for ($i = 0; isset($lines[$i]); ++$i) { + $messages[] = $lines[$i].str_repeat(' ', $len - self::width($lines[$i])); + } + if ($large) { + $messages[] = str_repeat(' ', $len); + } + + for ($i = 0; isset($messages[$i]); ++$i) { + $messages[$i] = sprintf('<%s>%s', $style, $messages[$i], $style); + } + + return implode("\n", $messages); + } + + /** + * Truncates a message to the given length. + */ + public function truncate(string $message, int $length, string $suffix = '...'): string + { + $computedLength = $length - self::width($suffix); + + if ($computedLength > self::width($message)) { + return $message; + } + + return self::substr($message, 0, $length).$suffix; + } + + public function getName(): string + { + return 'formatter'; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/Helper.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/Helper.php new file mode 100644 index 00000000..afb20ad5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/Helper.php @@ -0,0 +1,159 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Formatter\OutputFormatterInterface; +use Symfony\Component\String\UnicodeString; + +/** + * Helper is the base class for all helper classes. + * + * @author Fabien Potencier + */ +abstract class Helper implements HelperInterface +{ + protected ?HelperSet $helperSet = null; + + public function setHelperSet(?HelperSet $helperSet): void + { + $this->helperSet = $helperSet; + } + + public function getHelperSet(): ?HelperSet + { + return $this->helperSet; + } + + /** + * Returns the width of a string, using mb_strwidth if it is available. + * The width is how many characters positions the string will use. + */ + public static function width(?string $string): int + { + $string ??= ''; + + if (preg_match('//u', $string)) { + return (new UnicodeString($string))->width(false); + } + + if (false === $encoding = mb_detect_encoding($string, null, true)) { + return \strlen($string); + } + + return mb_strwidth($string, $encoding); + } + + /** + * Returns the length of a string, using mb_strlen if it is available. + * The length is related to how many bytes the string will use. + */ + public static function length(?string $string): int + { + $string ??= ''; + + if (preg_match('//u', $string)) { + return (new UnicodeString($string))->length(); + } + + if (false === $encoding = mb_detect_encoding($string, null, true)) { + return \strlen($string); + } + + return mb_strlen($string, $encoding); + } + + /** + * Returns the subset of a string, using mb_substr if it is available. + */ + public static function substr(?string $string, int $from, int $length = null): string + { + $string ??= ''; + + if (false === $encoding = mb_detect_encoding($string, null, true)) { + return substr($string, $from, $length); + } + + return mb_substr($string, $from, $length, $encoding); + } + + public static function formatTime(int|float $secs, int $precision = 1): string + { + $secs = (int) floor($secs); + + if (0 === $secs) { + return '< 1 sec'; + } + + static $timeFormats = [ + [1, '1 sec', 'secs'], + [60, '1 min', 'mins'], + [3600, '1 hr', 'hrs'], + [86400, '1 day', 'days'], + ]; + + $times = []; + foreach ($timeFormats as $index => $format) { + $seconds = isset($timeFormats[$index + 1]) ? $secs % $timeFormats[$index + 1][0] : $secs; + + if (isset($times[$index - $precision])) { + unset($times[$index - $precision]); + } + + if (0 === $seconds) { + continue; + } + + $unitCount = ($seconds / $format[0]); + $times[$index] = 1 === $unitCount ? $format[1] : $unitCount.' '.$format[2]; + + if ($secs === $seconds) { + break; + } + + $secs -= $seconds; + } + + return implode(', ', array_reverse($times)); + } + + public static function formatMemory(int $memory): string + { + if ($memory >= 1024 * 1024 * 1024) { + return sprintf('%.1f GiB', $memory / 1024 / 1024 / 1024); + } + + if ($memory >= 1024 * 1024) { + return sprintf('%.1f MiB', $memory / 1024 / 1024); + } + + if ($memory >= 1024) { + return sprintf('%d KiB', $memory / 1024); + } + + return sprintf('%d B', $memory); + } + + public static function removeDecoration(OutputFormatterInterface $formatter, ?string $string): string + { + $isDecorated = $formatter->isDecorated(); + $formatter->setDecorated(false); + // remove <...> formatting + $string = $formatter->format($string ?? ''); + // remove already formatted characters + $string = preg_replace("/\033\[[^m]*m/", '', $string ?? ''); + // remove terminal hyperlinks + $string = preg_replace('/\\033]8;[^;]*;[^\\033]*\\033\\\\/', '', $string ?? ''); + $formatter->setDecorated($isDecorated); + + return $string; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/HelperInterface.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/HelperInterface.php new file mode 100644 index 00000000..8c4da3c9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/HelperInterface.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +/** + * HelperInterface is the interface all helpers must implement. + * + * @author Fabien Potencier + */ +interface HelperInterface +{ + /** + * Sets the helper set associated with this helper. + */ + public function setHelperSet(?HelperSet $helperSet): void; + + /** + * Gets the helper set associated with this helper. + */ + public function getHelperSet(): ?HelperSet; + + /** + * Returns the canonical name of this helper. + */ + public function getName(): string; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/HelperSet.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/HelperSet.php new file mode 100644 index 00000000..42153b68 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/HelperSet.php @@ -0,0 +1,74 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Exception\InvalidArgumentException; + +/** + * HelperSet represents a set of helpers to be used with a command. + * + * @author Fabien Potencier + * + * @implements \IteratorAggregate + */ +class HelperSet implements \IteratorAggregate +{ + /** @var array */ + private array $helpers = []; + + /** + * @param HelperInterface[] $helpers + */ + public function __construct(array $helpers = []) + { + foreach ($helpers as $alias => $helper) { + $this->set($helper, \is_int($alias) ? null : $alias); + } + } + + public function set(HelperInterface $helper, string $alias = null): void + { + $this->helpers[$helper->getName()] = $helper; + if (null !== $alias) { + $this->helpers[$alias] = $helper; + } + + $helper->setHelperSet($this); + } + + /** + * Returns true if the helper if defined. + */ + public function has(string $name): bool + { + return isset($this->helpers[$name]); + } + + /** + * Gets a helper value. + * + * @throws InvalidArgumentException if the helper is not defined + */ + public function get(string $name): HelperInterface + { + if (!$this->has($name)) { + throw new InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name)); + } + + return $this->helpers[$name]; + } + + public function getIterator(): \Traversable + { + return new \ArrayIterator($this->helpers); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/InputAwareHelper.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/InputAwareHelper.php new file mode 100644 index 00000000..47126bda --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/InputAwareHelper.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Input\InputAwareInterface; +use Symfony\Component\Console\Input\InputInterface; + +/** + * An implementation of InputAwareInterface for Helpers. + * + * @author Wouter J + */ +abstract class InputAwareHelper extends Helper implements InputAwareInterface +{ + protected InputInterface $input; + + public function setInput(InputInterface $input): void + { + $this->input = $input; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/OutputWrapper.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/OutputWrapper.php new file mode 100644 index 00000000..2ec819c7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/OutputWrapper.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +/** + * Simple output wrapper for "tagged outputs" instead of wordwrap(). This solution is based on a StackOverflow + * answer: https://stackoverflow.com/a/20434776/1476819 from user557597 (alias SLN). + * + * (?: + * # -- Words/Characters + * ( # (1 start) + * (?> # Atomic Group - Match words with valid breaks + * .{1,16} # 1-N characters + * # Followed by one of 4 prioritized, non-linebreak whitespace + * (?: # break types: + * (?<= [^\S\r\n] ) # 1. - Behind a non-linebreak whitespace + * [^\S\r\n]? # ( optionally accept an extra non-linebreak whitespace ) + * | (?= \r? \n ) # 2. - Ahead a linebreak + * | $ # 3. - EOS + * | [^\S\r\n] # 4. - Accept an extra non-linebreak whitespace + * ) + * ) # End atomic group + * | + * .{1,16} # No valid word breaks, just break on the N'th character + * ) # (1 end) + * (?: \r? \n )? # Optional linebreak after Words/Characters + * | + * # -- Or, Linebreak + * (?: \r? \n | $ ) # Stand alone linebreak or at EOS + * ) + * + * @author Krisztián Ferenczi + * + * @see https://stackoverflow.com/a/20434776/1476819 + */ +final class OutputWrapper +{ + private const TAG_OPEN_REGEX_SEGMENT = '[a-z](?:[^\\\\<>]*+ | \\\\.)*'; + private const TAG_CLOSE_REGEX_SEGMENT = '[a-z][^<>]*+'; + private const URL_PATTERN = 'https?://\S+'; + + public function __construct( + private bool $allowCutUrls = false + ) { + } + + public function wrap(string $text, int $width, string $break = "\n"): string + { + if (!$width) { + return $text; + } + + $tagPattern = sprintf('<(?:(?:%s)|/(?:%s)?)>', self::TAG_OPEN_REGEX_SEGMENT, self::TAG_CLOSE_REGEX_SEGMENT); + $limitPattern = "{1,$width}"; + $patternBlocks = [$tagPattern]; + if (!$this->allowCutUrls) { + $patternBlocks[] = self::URL_PATTERN; + } + $patternBlocks[] = '.'; + $blocks = implode('|', $patternBlocks); + $rowPattern = "(?:$blocks)$limitPattern"; + $pattern = sprintf('#(?:((?>(%1$s)((?<=[^\S\r\n])[^\S\r\n]?|(?=\r?\n)|$|[^\S\r\n]))|(%1$s))(?:\r?\n)?|(?:\r?\n|$))#imux', $rowPattern); + $output = rtrim(preg_replace($pattern, '\\1'.$break, $text), $break); + + return str_replace(' '.$break, $break, $output); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/ProcessHelper.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/ProcessHelper.php new file mode 100644 index 00000000..26d35a1a --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/ProcessHelper.php @@ -0,0 +1,137 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Process\Exception\ProcessFailedException; +use Symfony\Component\Process\Process; + +/** + * The ProcessHelper class provides helpers to run external processes. + * + * @author Fabien Potencier + * + * @final + */ +class ProcessHelper extends Helper +{ + /** + * Runs an external process. + * + * @param array|Process $cmd An instance of Process or an array of the command and arguments + * @param callable|null $callback A PHP callback to run whenever there is some + * output available on STDOUT or STDERR + */ + public function run(OutputInterface $output, array|Process $cmd, string $error = null, callable $callback = null, int $verbosity = OutputInterface::VERBOSITY_VERY_VERBOSE): Process + { + if (!class_exists(Process::class)) { + throw new \LogicException('The ProcessHelper cannot be run as the Process component is not installed. Try running "compose require symfony/process".'); + } + + if ($output instanceof ConsoleOutputInterface) { + $output = $output->getErrorOutput(); + } + + $formatter = $this->getHelperSet()->get('debug_formatter'); + + if ($cmd instanceof Process) { + $cmd = [$cmd]; + } + + if (\is_string($cmd[0] ?? null)) { + $process = new Process($cmd); + $cmd = []; + } elseif (($cmd[0] ?? null) instanceof Process) { + $process = $cmd[0]; + unset($cmd[0]); + } else { + throw new \InvalidArgumentException(sprintf('Invalid command provided to "%s()": the command should be an array whose first element is either the path to the binary to run or a "Process" object.', __METHOD__)); + } + + if ($verbosity <= $output->getVerbosity()) { + $output->write($formatter->start(spl_object_hash($process), $this->escapeString($process->getCommandLine()))); + } + + if ($output->isDebug()) { + $callback = $this->wrapCallback($output, $process, $callback); + } + + $process->run($callback, $cmd); + + if ($verbosity <= $output->getVerbosity()) { + $message = $process->isSuccessful() ? 'Command ran successfully' : sprintf('%s Command did not run successfully', $process->getExitCode()); + $output->write($formatter->stop(spl_object_hash($process), $message, $process->isSuccessful())); + } + + if (!$process->isSuccessful() && null !== $error) { + $output->writeln(sprintf('%s', $this->escapeString($error))); + } + + return $process; + } + + /** + * Runs the process. + * + * This is identical to run() except that an exception is thrown if the process + * exits with a non-zero exit code. + * + * @param array|Process $cmd An instance of Process or a command to run + * @param callable|null $callback A PHP callback to run whenever there is some + * output available on STDOUT or STDERR + * + * @throws ProcessFailedException + * + * @see run() + */ + public function mustRun(OutputInterface $output, array|Process $cmd, string $error = null, callable $callback = null): Process + { + $process = $this->run($output, $cmd, $error, $callback); + + if (!$process->isSuccessful()) { + throw new ProcessFailedException($process); + } + + return $process; + } + + /** + * Wraps a Process callback to add debugging output. + */ + public function wrapCallback(OutputInterface $output, Process $process, callable $callback = null): callable + { + if ($output instanceof ConsoleOutputInterface) { + $output = $output->getErrorOutput(); + } + + $formatter = $this->getHelperSet()->get('debug_formatter'); + + return function ($type, $buffer) use ($output, $process, $callback, $formatter) { + $output->write($formatter->progress(spl_object_hash($process), $this->escapeString($buffer), Process::ERR === $type)); + + if (null !== $callback) { + $callback($type, $buffer); + } + }; + } + + private function escapeString(string $str): string + { + return str_replace('<', '\\<', $str); + } + + public function getName(): string + { + return 'process'; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/ProgressBar.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/ProgressBar.php new file mode 100644 index 00000000..64389c4a --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/ProgressBar.php @@ -0,0 +1,618 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Cursor; +use Symfony\Component\Console\Exception\LogicException; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\ConsoleSectionOutput; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Terminal; + +/** + * The ProgressBar provides helpers to display progress output. + * + * @author Fabien Potencier + * @author Chris Jones + */ +final class ProgressBar +{ + public const FORMAT_VERBOSE = 'verbose'; + public const FORMAT_VERY_VERBOSE = 'very_verbose'; + public const FORMAT_DEBUG = 'debug'; + public const FORMAT_NORMAL = 'normal'; + + private const FORMAT_VERBOSE_NOMAX = 'verbose_nomax'; + private const FORMAT_VERY_VERBOSE_NOMAX = 'very_verbose_nomax'; + private const FORMAT_DEBUG_NOMAX = 'debug_nomax'; + private const FORMAT_NORMAL_NOMAX = 'normal_nomax'; + + private int $barWidth = 28; + private string $barChar; + private string $emptyBarChar = '-'; + private string $progressChar = '>'; + private ?string $format = null; + private ?string $internalFormat = null; + private ?int $redrawFreq = 1; + private int $writeCount = 0; + private float $lastWriteTime = 0; + private float $minSecondsBetweenRedraws = 0; + private float $maxSecondsBetweenRedraws = 1; + private OutputInterface $output; + private int $step = 0; + private int $startingStep = 0; + private ?int $max = null; + private int $startTime; + private int $stepWidth; + private float $percent = 0.0; + private array $messages = []; + private bool $overwrite = true; + private Terminal $terminal; + private ?string $previousMessage = null; + private Cursor $cursor; + private array $placeholders = []; + + private static array $formatters; + private static array $formats; + + /** + * @param int $max Maximum steps (0 if unknown) + */ + public function __construct(OutputInterface $output, int $max = 0, float $minSecondsBetweenRedraws = 1 / 25) + { + if ($output instanceof ConsoleOutputInterface) { + $output = $output->getErrorOutput(); + } + + $this->output = $output; + $this->setMaxSteps($max); + $this->terminal = new Terminal(); + + if (0 < $minSecondsBetweenRedraws) { + $this->redrawFreq = null; + $this->minSecondsBetweenRedraws = $minSecondsBetweenRedraws; + } + + if (!$this->output->isDecorated()) { + // disable overwrite when output does not support ANSI codes. + $this->overwrite = false; + + // set a reasonable redraw frequency so output isn't flooded + $this->redrawFreq = null; + } + + $this->startTime = time(); + $this->cursor = new Cursor($output); + } + + /** + * Sets a placeholder formatter for a given name, globally for all instances of ProgressBar. + * + * This method also allow you to override an existing placeholder. + * + * @param string $name The placeholder name (including the delimiter char like %) + * @param callable(ProgressBar):string $callable A PHP callable + */ + public static function setPlaceholderFormatterDefinition(string $name, callable $callable): void + { + self::$formatters ??= self::initPlaceholderFormatters(); + + self::$formatters[$name] = $callable; + } + + /** + * Gets the placeholder formatter for a given name. + * + * @param string $name The placeholder name (including the delimiter char like %) + */ + public static function getPlaceholderFormatterDefinition(string $name): ?callable + { + self::$formatters ??= self::initPlaceholderFormatters(); + + return self::$formatters[$name] ?? null; + } + + /** + * Sets a placeholder formatter for a given name, for this instance only. + * + * @param callable(ProgressBar):string $callable A PHP callable + */ + public function setPlaceholderFormatter(string $name, callable $callable): void + { + $this->placeholders[$name] = $callable; + } + + /** + * Gets the placeholder formatter for a given name. + * + * @param string $name The placeholder name (including the delimiter char like %) + */ + public function getPlaceholderFormatter(string $name): ?callable + { + return $this->placeholders[$name] ?? $this::getPlaceholderFormatterDefinition($name); + } + + /** + * Sets a format for a given name. + * + * This method also allow you to override an existing format. + * + * @param string $name The format name + * @param string $format A format string + */ + public static function setFormatDefinition(string $name, string $format): void + { + self::$formats ??= self::initFormats(); + + self::$formats[$name] = $format; + } + + /** + * Gets the format for a given name. + * + * @param string $name The format name + */ + public static function getFormatDefinition(string $name): ?string + { + self::$formats ??= self::initFormats(); + + return self::$formats[$name] ?? null; + } + + /** + * Associates a text with a named placeholder. + * + * The text is displayed when the progress bar is rendered but only + * when the corresponding placeholder is part of the custom format line + * (by wrapping the name with %). + * + * @param string $message The text to associate with the placeholder + * @param string $name The name of the placeholder + */ + public function setMessage(string $message, string $name = 'message'): void + { + $this->messages[$name] = $message; + } + + public function getMessage(string $name = 'message'): string + { + return $this->messages[$name]; + } + + public function getStartTime(): int + { + return $this->startTime; + } + + public function getMaxSteps(): int + { + return $this->max; + } + + public function getProgress(): int + { + return $this->step; + } + + private function getStepWidth(): int + { + return $this->stepWidth; + } + + public function getProgressPercent(): float + { + return $this->percent; + } + + public function getBarOffset(): float + { + return floor($this->max ? $this->percent * $this->barWidth : (null === $this->redrawFreq ? (int) (min(5, $this->barWidth / 15) * $this->writeCount) : $this->step) % $this->barWidth); + } + + public function getEstimated(): float + { + if (0 === $this->step || $this->step === $this->startingStep) { + return 0; + } + + return round((time() - $this->startTime) / ($this->step - $this->startingStep) * $this->max); + } + + public function getRemaining(): float + { + if (!$this->step) { + return 0; + } + + return round((time() - $this->startTime) / ($this->step - $this->startingStep) * ($this->max - $this->step)); + } + + public function setBarWidth(int $size): void + { + $this->barWidth = max(1, $size); + } + + public function getBarWidth(): int + { + return $this->barWidth; + } + + public function setBarCharacter(string $char): void + { + $this->barChar = $char; + } + + public function getBarCharacter(): string + { + return $this->barChar ?? ($this->max ? '=' : $this->emptyBarChar); + } + + public function setEmptyBarCharacter(string $char): void + { + $this->emptyBarChar = $char; + } + + public function getEmptyBarCharacter(): string + { + return $this->emptyBarChar; + } + + public function setProgressCharacter(string $char): void + { + $this->progressChar = $char; + } + + public function getProgressCharacter(): string + { + return $this->progressChar; + } + + public function setFormat(string $format): void + { + $this->format = null; + $this->internalFormat = $format; + } + + /** + * Sets the redraw frequency. + * + * @param int|null $freq The frequency in steps + */ + public function setRedrawFrequency(?int $freq): void + { + $this->redrawFreq = null !== $freq ? max(1, $freq) : null; + } + + public function minSecondsBetweenRedraws(float $seconds): void + { + $this->minSecondsBetweenRedraws = $seconds; + } + + public function maxSecondsBetweenRedraws(float $seconds): void + { + $this->maxSecondsBetweenRedraws = $seconds; + } + + /** + * Returns an iterator that will automatically update the progress bar when iterated. + * + * @template TKey + * @template TValue + * + * @param iterable $iterable + * @param int|null $max Number of steps to complete the bar (0 if indeterminate), if null it will be inferred from $iterable + * + * @return iterable + */ + public function iterate(iterable $iterable, int $max = null): iterable + { + $this->start($max ?? (is_countable($iterable) ? \count($iterable) : 0)); + + foreach ($iterable as $key => $value) { + yield $key => $value; + + $this->advance(); + } + + $this->finish(); + } + + /** + * Starts the progress output. + * + * @param int|null $max Number of steps to complete the bar (0 if indeterminate), null to leave unchanged + * @param int $startAt The starting point of the bar (useful e.g. when resuming a previously started bar) + */ + public function start(int $max = null, int $startAt = 0): void + { + $this->startTime = time(); + $this->step = $startAt; + $this->startingStep = $startAt; + + $startAt > 0 ? $this->setProgress($startAt) : $this->percent = 0.0; + + if (null !== $max) { + $this->setMaxSteps($max); + } + + $this->display(); + } + + /** + * Advances the progress output X steps. + * + * @param int $step Number of steps to advance + */ + public function advance(int $step = 1): void + { + $this->setProgress($this->step + $step); + } + + /** + * Sets whether to overwrite the progressbar, false for new line. + */ + public function setOverwrite(bool $overwrite): void + { + $this->overwrite = $overwrite; + } + + public function setProgress(int $step): void + { + if ($this->max && $step > $this->max) { + $this->max = $step; + } elseif ($step < 0) { + $step = 0; + } + + $redrawFreq = $this->redrawFreq ?? (($this->max ?: 10) / 10); + $prevPeriod = (int) ($this->step / $redrawFreq); + $currPeriod = (int) ($step / $redrawFreq); + $this->step = $step; + $this->percent = $this->max ? (float) $this->step / $this->max : 0; + $timeInterval = microtime(true) - $this->lastWriteTime; + + // Draw regardless of other limits + if ($this->max === $step) { + $this->display(); + + return; + } + + // Throttling + if ($timeInterval < $this->minSecondsBetweenRedraws) { + return; + } + + // Draw each step period, but not too late + if ($prevPeriod !== $currPeriod || $timeInterval >= $this->maxSecondsBetweenRedraws) { + $this->display(); + } + } + + public function setMaxSteps(int $max): void + { + $this->format = null; + $this->max = max(0, $max); + $this->stepWidth = $this->max ? Helper::width((string) $this->max) : 4; + } + + /** + * Finishes the progress output. + */ + public function finish(): void + { + if (!$this->max) { + $this->max = $this->step; + } + + if ($this->step === $this->max && !$this->overwrite) { + // prevent double 100% output + return; + } + + $this->setProgress($this->max); + } + + /** + * Outputs the current progress string. + */ + public function display(): void + { + if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) { + return; + } + + if (null === $this->format) { + $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat()); + } + + $this->overwrite($this->buildLine()); + } + + /** + * Removes the progress bar from the current line. + * + * This is useful if you wish to write some output + * while a progress bar is running. + * Call display() to show the progress bar again. + */ + public function clear(): void + { + if (!$this->overwrite) { + return; + } + + if (null === $this->format) { + $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat()); + } + + $this->overwrite(''); + } + + private function setRealFormat(string $format): void + { + // try to use the _nomax variant if available + if (!$this->max && null !== self::getFormatDefinition($format.'_nomax')) { + $this->format = self::getFormatDefinition($format.'_nomax'); + } elseif (null !== self::getFormatDefinition($format)) { + $this->format = self::getFormatDefinition($format); + } else { + $this->format = $format; + } + } + + /** + * Overwrites a previous message to the output. + */ + private function overwrite(string $message): void + { + if ($this->previousMessage === $message) { + return; + } + + $originalMessage = $message; + + if ($this->overwrite) { + if (null !== $this->previousMessage) { + if ($this->output instanceof ConsoleSectionOutput) { + $messageLines = explode("\n", $this->previousMessage); + $lineCount = \count($messageLines); + foreach ($messageLines as $messageLine) { + $messageLineLength = Helper::width(Helper::removeDecoration($this->output->getFormatter(), $messageLine)); + if ($messageLineLength > $this->terminal->getWidth()) { + $lineCount += floor($messageLineLength / $this->terminal->getWidth()); + } + } + $this->output->clear($lineCount); + } else { + $lineCount = substr_count($this->previousMessage, "\n"); + for ($i = 0; $i < $lineCount; ++$i) { + $this->cursor->moveToColumn(1); + $this->cursor->clearLine(); + $this->cursor->moveUp(); + } + + $this->cursor->moveToColumn(1); + $this->cursor->clearLine(); + } + } + } elseif ($this->step > 0) { + $message = \PHP_EOL.$message; + } + + $this->previousMessage = $originalMessage; + $this->lastWriteTime = microtime(true); + + $this->output->write($message); + ++$this->writeCount; + } + + private function determineBestFormat(): string + { + return match ($this->output->getVerbosity()) { + // OutputInterface::VERBOSITY_QUIET: display is disabled anyway + OutputInterface::VERBOSITY_VERBOSE => $this->max ? self::FORMAT_VERBOSE : self::FORMAT_VERBOSE_NOMAX, + OutputInterface::VERBOSITY_VERY_VERBOSE => $this->max ? self::FORMAT_VERY_VERBOSE : self::FORMAT_VERY_VERBOSE_NOMAX, + OutputInterface::VERBOSITY_DEBUG => $this->max ? self::FORMAT_DEBUG : self::FORMAT_DEBUG_NOMAX, + default => $this->max ? self::FORMAT_NORMAL : self::FORMAT_NORMAL_NOMAX, + }; + } + + private static function initPlaceholderFormatters(): array + { + return [ + 'bar' => function (self $bar, OutputInterface $output) { + $completeBars = $bar->getBarOffset(); + $display = str_repeat($bar->getBarCharacter(), $completeBars); + if ($completeBars < $bar->getBarWidth()) { + $emptyBars = $bar->getBarWidth() - $completeBars - Helper::length(Helper::removeDecoration($output->getFormatter(), $bar->getProgressCharacter())); + $display .= $bar->getProgressCharacter().str_repeat($bar->getEmptyBarCharacter(), $emptyBars); + } + + return $display; + }, + 'elapsed' => fn (self $bar) => Helper::formatTime(time() - $bar->getStartTime(), 2), + 'remaining' => function (self $bar) { + if (!$bar->getMaxSteps()) { + throw new LogicException('Unable to display the remaining time if the maximum number of steps is not set.'); + } + + return Helper::formatTime($bar->getRemaining(), 2); + }, + 'estimated' => function (self $bar) { + if (!$bar->getMaxSteps()) { + throw new LogicException('Unable to display the estimated time if the maximum number of steps is not set.'); + } + + return Helper::formatTime($bar->getEstimated(), 2); + }, + 'memory' => fn (self $bar) => Helper::formatMemory(memory_get_usage(true)), + 'current' => fn (self $bar) => str_pad($bar->getProgress(), $bar->getStepWidth(), ' ', \STR_PAD_LEFT), + 'max' => fn (self $bar) => $bar->getMaxSteps(), + 'percent' => fn (self $bar) => floor($bar->getProgressPercent() * 100), + ]; + } + + private static function initFormats(): array + { + return [ + self::FORMAT_NORMAL => ' %current%/%max% [%bar%] %percent:3s%%', + self::FORMAT_NORMAL_NOMAX => ' %current% [%bar%]', + + self::FORMAT_VERBOSE => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%', + self::FORMAT_VERBOSE_NOMAX => ' %current% [%bar%] %elapsed:6s%', + + self::FORMAT_VERY_VERBOSE => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%', + self::FORMAT_VERY_VERBOSE_NOMAX => ' %current% [%bar%] %elapsed:6s%', + + self::FORMAT_DEBUG => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%', + self::FORMAT_DEBUG_NOMAX => ' %current% [%bar%] %elapsed:6s% %memory:6s%', + ]; + } + + private function buildLine(): string + { + \assert(null !== $this->format); + + $regex = "{%([a-z\-_]+)(?:\:([^%]+))?%}i"; + $callback = function ($matches) { + if ($formatter = $this->getPlaceholderFormatter($matches[1])) { + $text = $formatter($this, $this->output); + } elseif (isset($this->messages[$matches[1]])) { + $text = $this->messages[$matches[1]]; + } else { + return $matches[0]; + } + + if (isset($matches[2])) { + $text = sprintf('%'.$matches[2], $text); + } + + return $text; + }; + $line = preg_replace_callback($regex, $callback, $this->format); + + // gets string length for each sub line with multiline format + $linesLength = array_map(fn ($subLine) => Helper::width(Helper::removeDecoration($this->output->getFormatter(), rtrim($subLine, "\r"))), explode("\n", $line)); + + $linesWidth = max($linesLength); + + $terminalWidth = $this->terminal->getWidth(); + if ($linesWidth <= $terminalWidth) { + return $line; + } + + $this->setBarWidth($this->barWidth - $linesWidth + $terminalWidth); + + return preg_replace_callback($regex, $callback, $this->format); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/ProgressIndicator.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/ProgressIndicator.php new file mode 100644 index 00000000..8865ecc3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/ProgressIndicator.php @@ -0,0 +1,225 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\LogicException; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Kevin Bond + */ +class ProgressIndicator +{ + private const FORMATS = [ + 'normal' => ' %indicator% %message%', + 'normal_no_ansi' => ' %message%', + + 'verbose' => ' %indicator% %message% (%elapsed:6s%)', + 'verbose_no_ansi' => ' %message% (%elapsed:6s%)', + + 'very_verbose' => ' %indicator% %message% (%elapsed:6s%, %memory:6s%)', + 'very_verbose_no_ansi' => ' %message% (%elapsed:6s%, %memory:6s%)', + ]; + + private OutputInterface $output; + private int $startTime; + private ?string $format = null; + private ?string $message = null; + private array $indicatorValues; + private int $indicatorCurrent; + private int $indicatorChangeInterval; + private float $indicatorUpdateTime; + private bool $started = false; + + /** + * @var array + */ + private static array $formatters; + + /** + * @param int $indicatorChangeInterval Change interval in milliseconds + * @param array|null $indicatorValues Animated indicator characters + */ + public function __construct(OutputInterface $output, string $format = null, int $indicatorChangeInterval = 100, array $indicatorValues = null) + { + $this->output = $output; + + $format ??= $this->determineBestFormat(); + $indicatorValues ??= ['-', '\\', '|', '/']; + $indicatorValues = array_values($indicatorValues); + + if (2 > \count($indicatorValues)) { + throw new InvalidArgumentException('Must have at least 2 indicator value characters.'); + } + + $this->format = self::getFormatDefinition($format); + $this->indicatorChangeInterval = $indicatorChangeInterval; + $this->indicatorValues = $indicatorValues; + $this->startTime = time(); + } + + /** + * Sets the current indicator message. + */ + public function setMessage(?string $message): void + { + $this->message = $message; + + $this->display(); + } + + /** + * Starts the indicator output. + */ + public function start(string $message): void + { + if ($this->started) { + throw new LogicException('Progress indicator already started.'); + } + + $this->message = $message; + $this->started = true; + $this->startTime = time(); + $this->indicatorUpdateTime = $this->getCurrentTimeInMilliseconds() + $this->indicatorChangeInterval; + $this->indicatorCurrent = 0; + + $this->display(); + } + + /** + * Advances the indicator. + */ + public function advance(): void + { + if (!$this->started) { + throw new LogicException('Progress indicator has not yet been started.'); + } + + if (!$this->output->isDecorated()) { + return; + } + + $currentTime = $this->getCurrentTimeInMilliseconds(); + + if ($currentTime < $this->indicatorUpdateTime) { + return; + } + + $this->indicatorUpdateTime = $currentTime + $this->indicatorChangeInterval; + ++$this->indicatorCurrent; + + $this->display(); + } + + /** + * Finish the indicator with message. + */ + public function finish(string $message): void + { + if (!$this->started) { + throw new LogicException('Progress indicator has not yet been started.'); + } + + $this->message = $message; + $this->display(); + $this->output->writeln(''); + $this->started = false; + } + + /** + * Gets the format for a given name. + */ + public static function getFormatDefinition(string $name): ?string + { + return self::FORMATS[$name] ?? null; + } + + /** + * Sets a placeholder formatter for a given name. + * + * This method also allow you to override an existing placeholder. + */ + public static function setPlaceholderFormatterDefinition(string $name, callable $callable): void + { + self::$formatters ??= self::initPlaceholderFormatters(); + + self::$formatters[$name] = $callable; + } + + /** + * Gets the placeholder formatter for a given name (including the delimiter char like %). + */ + public static function getPlaceholderFormatterDefinition(string $name): ?callable + { + self::$formatters ??= self::initPlaceholderFormatters(); + + return self::$formatters[$name] ?? null; + } + + private function display(): void + { + if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) { + return; + } + + $this->overwrite(preg_replace_callback("{%([a-z\-_]+)(?:\:([^%]+))?%}i", function ($matches) { + if ($formatter = self::getPlaceholderFormatterDefinition($matches[1])) { + return $formatter($this); + } + + return $matches[0]; + }, $this->format ?? '')); + } + + private function determineBestFormat(): string + { + return match ($this->output->getVerbosity()) { + // OutputInterface::VERBOSITY_QUIET: display is disabled anyway + OutputInterface::VERBOSITY_VERBOSE => $this->output->isDecorated() ? 'verbose' : 'verbose_no_ansi', + OutputInterface::VERBOSITY_VERY_VERBOSE, + OutputInterface::VERBOSITY_DEBUG => $this->output->isDecorated() ? 'very_verbose' : 'very_verbose_no_ansi', + default => $this->output->isDecorated() ? 'normal' : 'normal_no_ansi', + }; + } + + /** + * Overwrites a previous message to the output. + */ + private function overwrite(string $message): void + { + if ($this->output->isDecorated()) { + $this->output->write("\x0D\x1B[2K"); + $this->output->write($message); + } else { + $this->output->writeln($message); + } + } + + private function getCurrentTimeInMilliseconds(): float + { + return round(microtime(true) * 1000); + } + + /** + * @return array + */ + private static function initPlaceholderFormatters(): array + { + return [ + 'indicator' => fn (self $indicator) => $indicator->indicatorValues[$indicator->indicatorCurrent % \count($indicator->indicatorValues)], + 'message' => fn (self $indicator) => $indicator->message, + 'elapsed' => fn (self $indicator) => Helper::formatTime(time() - $indicator->startTime, 2), + 'memory' => fn () => Helper::formatMemory(memory_get_usage(true)), + ]; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/QuestionHelper.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/QuestionHelper.php new file mode 100644 index 00000000..cb75ac91 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/QuestionHelper.php @@ -0,0 +1,606 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Cursor; +use Symfony\Component\Console\Exception\MissingInputException; +use Symfony\Component\Console\Exception\RuntimeException; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Formatter\OutputFormatterStyle; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\StreamableInputInterface; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\ConsoleSectionOutput; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Question\ChoiceQuestion; +use Symfony\Component\Console\Question\Question; +use Symfony\Component\Console\Terminal; + +use function Symfony\Component\String\s; + +/** + * The QuestionHelper class provides helpers to interact with the user. + * + * @author Fabien Potencier + */ +class QuestionHelper extends Helper +{ + /** + * @var resource|null + */ + private $inputStream; + + private static bool $stty = true; + private static bool $stdinIsInteractive; + + /** + * Asks a question to the user. + * + * @return mixed The user answer + * + * @throws RuntimeException If there is no data to read in the input stream + */ + public function ask(InputInterface $input, OutputInterface $output, Question $question): mixed + { + if ($output instanceof ConsoleOutputInterface) { + $output = $output->getErrorOutput(); + } + + if (!$input->isInteractive()) { + return $this->getDefaultAnswer($question); + } + + if ($input instanceof StreamableInputInterface && $stream = $input->getStream()) { + $this->inputStream = $stream; + } + + try { + if (!$question->getValidator()) { + return $this->doAsk($output, $question); + } + + $interviewer = fn () => $this->doAsk($output, $question); + + return $this->validateAttempts($interviewer, $output, $question); + } catch (MissingInputException $exception) { + $input->setInteractive(false); + + if (null === $fallbackOutput = $this->getDefaultAnswer($question)) { + throw $exception; + } + + return $fallbackOutput; + } + } + + public function getName(): string + { + return 'question'; + } + + /** + * Prevents usage of stty. + */ + public static function disableStty(): void + { + self::$stty = false; + } + + /** + * Asks the question to the user. + * + * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden + */ + private function doAsk(OutputInterface $output, Question $question): mixed + { + $this->writePrompt($output, $question); + + $inputStream = $this->inputStream ?: \STDIN; + $autocomplete = $question->getAutocompleterCallback(); + + if (null === $autocomplete || !self::$stty || !Terminal::hasSttyAvailable()) { + $ret = false; + if ($question->isHidden()) { + try { + $hiddenResponse = $this->getHiddenResponse($output, $inputStream, $question->isTrimmable()); + $ret = $question->isTrimmable() ? trim($hiddenResponse) : $hiddenResponse; + } catch (RuntimeException $e) { + if (!$question->isHiddenFallback()) { + throw $e; + } + } + } + + if (false === $ret) { + $isBlocked = stream_get_meta_data($inputStream)['blocked'] ?? true; + + if (!$isBlocked) { + stream_set_blocking($inputStream, true); + } + + $ret = $this->readInput($inputStream, $question); + + if (!$isBlocked) { + stream_set_blocking($inputStream, false); + } + + if (false === $ret) { + throw new MissingInputException('Aborted.'); + } + if ($question->isTrimmable()) { + $ret = trim($ret); + } + } + } else { + $autocomplete = $this->autocomplete($output, $question, $inputStream, $autocomplete); + $ret = $question->isTrimmable() ? trim($autocomplete) : $autocomplete; + } + + if ($output instanceof ConsoleSectionOutput) { + $output->addContent(''); // add EOL to the question + $output->addContent($ret); + } + + $ret = \strlen($ret) > 0 ? $ret : $question->getDefault(); + + if ($normalizer = $question->getNormalizer()) { + return $normalizer($ret); + } + + return $ret; + } + + private function getDefaultAnswer(Question $question): mixed + { + $default = $question->getDefault(); + + if (null === $default) { + return $default; + } + + if ($validator = $question->getValidator()) { + return \call_user_func($validator, $default); + } elseif ($question instanceof ChoiceQuestion) { + $choices = $question->getChoices(); + + if (!$question->isMultiselect()) { + return $choices[$default] ?? $default; + } + + $default = explode(',', $default); + foreach ($default as $k => $v) { + $v = $question->isTrimmable() ? trim($v) : $v; + $default[$k] = $choices[$v] ?? $v; + } + } + + return $default; + } + + /** + * Outputs the question prompt. + */ + protected function writePrompt(OutputInterface $output, Question $question): void + { + $message = $question->getQuestion(); + + if ($question instanceof ChoiceQuestion) { + $output->writeln(array_merge([ + $question->getQuestion(), + ], $this->formatChoiceQuestionChoices($question, 'info'))); + + $message = $question->getPrompt(); + } + + $output->write($message); + } + + /** + * @return string[] + */ + protected function formatChoiceQuestionChoices(ChoiceQuestion $question, string $tag): array + { + $messages = []; + + $maxWidth = max(array_map([__CLASS__, 'width'], array_keys($choices = $question->getChoices()))); + + foreach ($choices as $key => $value) { + $padding = str_repeat(' ', $maxWidth - self::width($key)); + + $messages[] = sprintf(" [<$tag>%s$padding] %s", $key, $value); + } + + return $messages; + } + + /** + * Outputs an error message. + */ + protected function writeError(OutputInterface $output, \Exception $error): void + { + if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) { + $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error'); + } else { + $message = ''.$error->getMessage().''; + } + + $output->writeln($message); + } + + /** + * Autocompletes a question. + * + * @param resource $inputStream + */ + private function autocomplete(OutputInterface $output, Question $question, $inputStream, callable $autocomplete): string + { + $cursor = new Cursor($output, $inputStream); + + $fullChoice = ''; + $ret = ''; + + $i = 0; + $ofs = -1; + $matches = $autocomplete($ret); + $numMatches = \count($matches); + + $sttyMode = shell_exec('stty -g'); + $isStdin = 'php://stdin' === (stream_get_meta_data($inputStream)['uri'] ?? null); + $r = [$inputStream]; + $w = []; + + // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead) + shell_exec('stty -icanon -echo'); + + // Add highlighted text style + $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white')); + + // Read a keypress + while (!feof($inputStream)) { + while ($isStdin && 0 === @stream_select($r, $w, $w, 0, 100)) { + // Give signal handlers a chance to run + $r = [$inputStream]; + } + $c = fread($inputStream, 1); + + // as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false. + if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) { + shell_exec('stty '.$sttyMode); + throw new MissingInputException('Aborted.'); + } elseif ("\177" === $c) { // Backspace Character + if (0 === $numMatches && 0 !== $i) { + --$i; + $cursor->moveLeft(s($fullChoice)->slice(-1)->width(false)); + + $fullChoice = self::substr($fullChoice, 0, $i); + } + + if (0 === $i) { + $ofs = -1; + $matches = $autocomplete($ret); + $numMatches = \count($matches); + } else { + $numMatches = 0; + } + + // Pop the last character off the end of our string + $ret = self::substr($ret, 0, $i); + } elseif ("\033" === $c) { + // Did we read an escape sequence? + $c .= fread($inputStream, 2); + + // A = Up Arrow. B = Down Arrow + if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) { + if ('A' === $c[2] && -1 === $ofs) { + $ofs = 0; + } + + if (0 === $numMatches) { + continue; + } + + $ofs += ('A' === $c[2]) ? -1 : 1; + $ofs = ($numMatches + $ofs) % $numMatches; + } + } elseif (\ord($c) < 32) { + if ("\t" === $c || "\n" === $c) { + if ($numMatches > 0 && -1 !== $ofs) { + $ret = (string) $matches[$ofs]; + // Echo out remaining chars for current match + $remainingCharacters = substr($ret, \strlen(trim($this->mostRecentlyEnteredValue($fullChoice)))); + $output->write($remainingCharacters); + $fullChoice .= $remainingCharacters; + $i = (false === $encoding = mb_detect_encoding($fullChoice, null, true)) ? \strlen($fullChoice) : mb_strlen($fullChoice, $encoding); + + $matches = array_filter( + $autocomplete($ret), + fn ($match) => '' === $ret || str_starts_with($match, $ret) + ); + $numMatches = \count($matches); + $ofs = -1; + } + + if ("\n" === $c) { + $output->write($c); + break; + } + + $numMatches = 0; + } + + continue; + } else { + if ("\x80" <= $c) { + $c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]); + } + + $output->write($c); + $ret .= $c; + $fullChoice .= $c; + ++$i; + + $tempRet = $ret; + + if ($question instanceof ChoiceQuestion && $question->isMultiselect()) { + $tempRet = $this->mostRecentlyEnteredValue($fullChoice); + } + + $numMatches = 0; + $ofs = 0; + + foreach ($autocomplete($ret) as $value) { + // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle) + if (str_starts_with($value, $tempRet)) { + $matches[$numMatches++] = $value; + } + } + } + + $cursor->clearLineAfter(); + + if ($numMatches > 0 && -1 !== $ofs) { + $cursor->savePosition(); + // Write highlighted text, complete the partially entered response + $charactersEntered = \strlen(trim($this->mostRecentlyEnteredValue($fullChoice))); + $output->write(''.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $charactersEntered)).''); + $cursor->restorePosition(); + } + } + + // Reset stty so it behaves normally again + shell_exec('stty '.$sttyMode); + + return $fullChoice; + } + + private function mostRecentlyEnteredValue(string $entered): string + { + // Determine the most recent value that the user entered + if (!str_contains($entered, ',')) { + return $entered; + } + + $choices = explode(',', $entered); + if ('' !== $lastChoice = trim($choices[\count($choices) - 1])) { + return $lastChoice; + } + + return $entered; + } + + /** + * Gets a hidden response from user. + * + * @param resource $inputStream The handler resource + * @param bool $trimmable Is the answer trimmable + * + * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden + */ + private function getHiddenResponse(OutputInterface $output, $inputStream, bool $trimmable = true): string + { + if ('\\' === \DIRECTORY_SEPARATOR) { + $exe = __DIR__.'/../Resources/bin/hiddeninput.exe'; + + // handle code running from a phar + if (str_starts_with(__FILE__, 'phar:')) { + $tmpExe = sys_get_temp_dir().'/hiddeninput.exe'; + copy($exe, $tmpExe); + $exe = $tmpExe; + } + + $sExec = shell_exec('"'.$exe.'"'); + $value = $trimmable ? rtrim($sExec) : $sExec; + $output->writeln(''); + + if (isset($tmpExe)) { + unlink($tmpExe); + } + + return $value; + } + + if (self::$stty && Terminal::hasSttyAvailable()) { + $sttyMode = shell_exec('stty -g'); + shell_exec('stty -echo'); + } elseif ($this->isInteractiveInput($inputStream)) { + throw new RuntimeException('Unable to hide the response.'); + } + + $value = fgets($inputStream, 4096); + + if (4095 === \strlen($value)) { + $errOutput = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output; + $errOutput->warning('The value was possibly truncated by your shell or terminal emulator'); + } + + if (self::$stty && Terminal::hasSttyAvailable()) { + shell_exec('stty '.$sttyMode); + } + + if (false === $value) { + throw new MissingInputException('Aborted.'); + } + if ($trimmable) { + $value = trim($value); + } + $output->writeln(''); + + return $value; + } + + /** + * Validates an attempt. + * + * @param callable $interviewer A callable that will ask for a question and return the result + * + * @throws \Exception In case the max number of attempts has been reached and no valid response has been given + */ + private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question): mixed + { + $error = null; + $attempts = $question->getMaxAttempts(); + + while (null === $attempts || $attempts--) { + if (null !== $error) { + $this->writeError($output, $error); + } + + try { + return $question->getValidator()($interviewer()); + } catch (RuntimeException $e) { + throw $e; + } catch (\Exception $error) { + } + } + + throw $error; + } + + private function isInteractiveInput($inputStream): bool + { + if ('php://stdin' !== (stream_get_meta_data($inputStream)['uri'] ?? null)) { + return false; + } + + if (isset(self::$stdinIsInteractive)) { + return self::$stdinIsInteractive; + } + + if (\function_exists('stream_isatty')) { + return self::$stdinIsInteractive = @stream_isatty(fopen('php://stdin', 'r')); + } + + if (\function_exists('posix_isatty')) { + return self::$stdinIsInteractive = @posix_isatty(fopen('php://stdin', 'r')); + } + + if (!\function_exists('shell_exec')) { + return self::$stdinIsInteractive = true; + } + + return self::$stdinIsInteractive = (bool) shell_exec('stty 2> '.('\\' === \DIRECTORY_SEPARATOR ? 'NUL' : '/dev/null')); + } + + /** + * Reads one or more lines of input and returns what is read. + * + * @param resource $inputStream The handler resource + * @param Question $question The question being asked + */ + private function readInput($inputStream, Question $question): string|false + { + if (!$question->isMultiline()) { + $cp = $this->setIOCodepage(); + $ret = fgets($inputStream, 4096); + + return $this->resetIOCodepage($cp, $ret); + } + + $multiLineStreamReader = $this->cloneInputStream($inputStream); + if (null === $multiLineStreamReader) { + return false; + } + + $ret = ''; + $cp = $this->setIOCodepage(); + while (false !== ($char = fgetc($multiLineStreamReader))) { + if (\PHP_EOL === "{$ret}{$char}") { + break; + } + $ret .= $char; + } + + return $this->resetIOCodepage($cp, $ret); + } + + private function setIOCodepage(): int + { + if (\function_exists('sapi_windows_cp_set')) { + $cp = sapi_windows_cp_get(); + sapi_windows_cp_set(sapi_windows_cp_get('oem')); + + return $cp; + } + + return 0; + } + + /** + * Sets console I/O to the specified code page and converts the user input. + */ + private function resetIOCodepage(int $cp, string|false $input): string|false + { + if (0 !== $cp) { + sapi_windows_cp_set($cp); + + if (false !== $input && '' !== $input) { + $input = sapi_windows_cp_conv(sapi_windows_cp_get('oem'), $cp, $input); + } + } + + return $input; + } + + /** + * Clones an input stream in order to act on one instance of the same + * stream without affecting the other instance. + * + * @param resource $inputStream The handler resource + * + * @return resource|null The cloned resource, null in case it could not be cloned + */ + private function cloneInputStream($inputStream) + { + $streamMetaData = stream_get_meta_data($inputStream); + $seekable = $streamMetaData['seekable'] ?? false; + $mode = $streamMetaData['mode'] ?? 'rb'; + $uri = $streamMetaData['uri'] ?? null; + + if (null === $uri) { + return null; + } + + $cloneStream = fopen($uri, $mode); + + // For seekable and writable streams, add all the same data to the + // cloned stream and then seek to the same offset. + if (true === $seekable && !\in_array($mode, ['r', 'rb', 'rt'])) { + $offset = ftell($inputStream); + rewind($inputStream); + stream_copy_to_stream($inputStream, $cloneStream); + fseek($inputStream, $offset); + fseek($cloneStream, $offset); + } + + return $cloneStream; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/SymfonyQuestionHelper.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/SymfonyQuestionHelper.php new file mode 100644 index 00000000..48d947b7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/SymfonyQuestionHelper.php @@ -0,0 +1,103 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Question\ChoiceQuestion; +use Symfony\Component\Console\Question\ConfirmationQuestion; +use Symfony\Component\Console\Question\Question; +use Symfony\Component\Console\Style\SymfonyStyle; + +/** + * Symfony Style Guide compliant question helper. + * + * @author Kevin Bond + */ +class SymfonyQuestionHelper extends QuestionHelper +{ + protected function writePrompt(OutputInterface $output, Question $question): void + { + $text = OutputFormatter::escapeTrailingBackslash($question->getQuestion()); + $default = $question->getDefault(); + + if ($question->isMultiline()) { + $text .= sprintf(' (press %s to continue)', $this->getEofShortcut()); + } + + switch (true) { + case null === $default: + $text = sprintf(' %s:', $text); + + break; + + case $question instanceof ConfirmationQuestion: + $text = sprintf(' %s (yes/no) [%s]:', $text, $default ? 'yes' : 'no'); + + break; + + case $question instanceof ChoiceQuestion && $question->isMultiselect(): + $choices = $question->getChoices(); + $default = explode(',', $default); + + foreach ($default as $key => $value) { + $default[$key] = $choices[trim($value)]; + } + + $text = sprintf(' %s [%s]:', $text, OutputFormatter::escape(implode(', ', $default))); + + break; + + case $question instanceof ChoiceQuestion: + $choices = $question->getChoices(); + $text = sprintf(' %s [%s]:', $text, OutputFormatter::escape($choices[$default] ?? $default)); + + break; + + default: + $text = sprintf(' %s [%s]:', $text, OutputFormatter::escape($default)); + } + + $output->writeln($text); + + $prompt = ' > '; + + if ($question instanceof ChoiceQuestion) { + $output->writeln($this->formatChoiceQuestionChoices($question, 'comment')); + + $prompt = $question->getPrompt(); + } + + $output->write($prompt); + } + + protected function writeError(OutputInterface $output, \Exception $error): void + { + if ($output instanceof SymfonyStyle) { + $output->newLine(); + $output->error($error->getMessage()); + + return; + } + + parent::writeError($output, $error); + } + + private function getEofShortcut(): string + { + if ('Windows' === \PHP_OS_FAMILY) { + return 'Ctrl+Z then Enter'; + } + + return 'Ctrl+D'; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/Table.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/Table.php new file mode 100644 index 00000000..fe2ac87c --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/Table.php @@ -0,0 +1,922 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\RuntimeException; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Formatter\WrappableOutputFormatterInterface; +use Symfony\Component\Console\Output\ConsoleSectionOutput; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Provides helpers to display a table. + * + * @author Fabien Potencier + * @author Саша Стаменковић + * @author Abdellatif Ait boudad + * @author Max Grigorian + * @author Dany Maillard + */ +class Table +{ + private const SEPARATOR_TOP = 0; + private const SEPARATOR_TOP_BOTTOM = 1; + private const SEPARATOR_MID = 2; + private const SEPARATOR_BOTTOM = 3; + private const BORDER_OUTSIDE = 0; + private const BORDER_INSIDE = 1; + private const DISPLAY_ORIENTATION_DEFAULT = 'default'; + private const DISPLAY_ORIENTATION_HORIZONTAL = 'horizontal'; + private const DISPLAY_ORIENTATION_VERTICAL = 'vertical'; + + private ?string $headerTitle = null; + private ?string $footerTitle = null; + private array $headers = []; + private array $rows = []; + private array $effectiveColumnWidths = []; + private int $numberOfColumns; + private OutputInterface $output; + private TableStyle $style; + private array $columnStyles = []; + private array $columnWidths = []; + private array $columnMaxWidths = []; + private bool $rendered = false; + private string $displayOrientation = self::DISPLAY_ORIENTATION_DEFAULT; + + private static array $styles; + + public function __construct(OutputInterface $output) + { + $this->output = $output; + + self::$styles ??= self::initStyles(); + + $this->setStyle('default'); + } + + /** + * Sets a style definition. + */ + public static function setStyleDefinition(string $name, TableStyle $style): void + { + self::$styles ??= self::initStyles(); + + self::$styles[$name] = $style; + } + + /** + * Gets a style definition by name. + */ + public static function getStyleDefinition(string $name): TableStyle + { + self::$styles ??= self::initStyles(); + + return self::$styles[$name] ?? throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name)); + } + + /** + * Sets table style. + * + * @return $this + */ + public function setStyle(TableStyle|string $name): static + { + $this->style = $this->resolveStyle($name); + + return $this; + } + + /** + * Gets the current table style. + */ + public function getStyle(): TableStyle + { + return $this->style; + } + + /** + * Sets table column style. + * + * @param TableStyle|string $name The style name or a TableStyle instance + * + * @return $this + */ + public function setColumnStyle(int $columnIndex, TableStyle|string $name): static + { + $this->columnStyles[$columnIndex] = $this->resolveStyle($name); + + return $this; + } + + /** + * Gets the current style for a column. + * + * If style was not set, it returns the global table style. + */ + public function getColumnStyle(int $columnIndex): TableStyle + { + return $this->columnStyles[$columnIndex] ?? $this->getStyle(); + } + + /** + * Sets the minimum width of a column. + * + * @return $this + */ + public function setColumnWidth(int $columnIndex, int $width): static + { + $this->columnWidths[$columnIndex] = $width; + + return $this; + } + + /** + * Sets the minimum width of all columns. + * + * @return $this + */ + public function setColumnWidths(array $widths): static + { + $this->columnWidths = []; + foreach ($widths as $index => $width) { + $this->setColumnWidth($index, $width); + } + + return $this; + } + + /** + * Sets the maximum width of a column. + * + * Any cell within this column which contents exceeds the specified width will be wrapped into multiple lines, while + * formatted strings are preserved. + * + * @return $this + */ + public function setColumnMaxWidth(int $columnIndex, int $width): static + { + if (!$this->output->getFormatter() instanceof WrappableOutputFormatterInterface) { + throw new \LogicException(sprintf('Setting a maximum column width is only supported when using a "%s" formatter, got "%s".', WrappableOutputFormatterInterface::class, get_debug_type($this->output->getFormatter()))); + } + + $this->columnMaxWidths[$columnIndex] = $width; + + return $this; + } + + /** + * @return $this + */ + public function setHeaders(array $headers): static + { + $headers = array_values($headers); + if ($headers && !\is_array($headers[0])) { + $headers = [$headers]; + } + + $this->headers = $headers; + + return $this; + } + + /** + * @return $this + */ + public function setRows(array $rows): static + { + $this->rows = []; + + return $this->addRows($rows); + } + + /** + * @return $this + */ + public function addRows(array $rows): static + { + foreach ($rows as $row) { + $this->addRow($row); + } + + return $this; + } + + /** + * @return $this + */ + public function addRow(TableSeparator|array $row): static + { + if ($row instanceof TableSeparator) { + $this->rows[] = $row; + + return $this; + } + + $this->rows[] = array_values($row); + + return $this; + } + + /** + * Adds a row to the table, and re-renders the table. + * + * @return $this + */ + public function appendRow(TableSeparator|array $row): static + { + if (!$this->output instanceof ConsoleSectionOutput) { + throw new RuntimeException(sprintf('Output should be an instance of "%s" when calling "%s".', ConsoleSectionOutput::class, __METHOD__)); + } + + if ($this->rendered) { + $this->output->clear($this->calculateRowCount()); + } + + $this->addRow($row); + $this->render(); + + return $this; + } + + /** + * @return $this + */ + public function setRow(int|string $column, array $row): static + { + $this->rows[$column] = $row; + + return $this; + } + + /** + * @return $this + */ + public function setHeaderTitle(?string $title): static + { + $this->headerTitle = $title; + + return $this; + } + + /** + * @return $this + */ + public function setFooterTitle(?string $title): static + { + $this->footerTitle = $title; + + return $this; + } + + /** + * @return $this + */ + public function setHorizontal(bool $horizontal = true): static + { + $this->displayOrientation = $horizontal ? self::DISPLAY_ORIENTATION_HORIZONTAL : self::DISPLAY_ORIENTATION_DEFAULT; + + return $this; + } + + /** + * @return $this + */ + public function setVertical(bool $vertical = true): static + { + $this->displayOrientation = $vertical ? self::DISPLAY_ORIENTATION_VERTICAL : self::DISPLAY_ORIENTATION_DEFAULT; + + return $this; + } + + /** + * Renders table to output. + * + * Example: + * + * +---------------+-----------------------+------------------+ + * | ISBN | Title | Author | + * +---------------+-----------------------+------------------+ + * | 99921-58-10-7 | Divine Comedy | Dante Alighieri | + * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens | + * | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien | + * +---------------+-----------------------+------------------+ + */ + public function render(): void + { + $divider = new TableSeparator(); + $isCellWithColspan = static fn ($cell) => $cell instanceof TableCell && $cell->getColspan() >= 2; + + $horizontal = self::DISPLAY_ORIENTATION_HORIZONTAL === $this->displayOrientation; + $vertical = self::DISPLAY_ORIENTATION_VERTICAL === $this->displayOrientation; + + $rows = []; + if ($horizontal) { + foreach ($this->headers[0] ?? [] as $i => $header) { + $rows[$i] = [$header]; + foreach ($this->rows as $row) { + if ($row instanceof TableSeparator) { + continue; + } + if (isset($row[$i])) { + $rows[$i][] = $row[$i]; + } elseif ($isCellWithColspan($rows[$i][0])) { + // Noop, there is a "title" + } else { + $rows[$i][] = null; + } + } + } + } elseif ($vertical) { + $formatter = $this->output->getFormatter(); + $maxHeaderLength = array_reduce($this->headers[0] ?? [], static fn ($max, $header) => max($max, Helper::width(Helper::removeDecoration($formatter, $header))), 0); + + foreach ($this->rows as $row) { + if ($row instanceof TableSeparator) { + continue; + } + + if ($rows) { + $rows[] = [$divider]; + } + + $containsColspan = false; + foreach ($row as $cell) { + if ($containsColspan = $isCellWithColspan($cell)) { + break; + } + } + + $headers = $this->headers[0] ?? []; + $maxRows = max(\count($headers), \count($row)); + for ($i = 0; $i < $maxRows; ++$i) { + $cell = (string) ($row[$i] ?? ''); + + $parts = explode("\n", $cell); + foreach ($parts as $idx => $part) { + if ($headers && !$containsColspan) { + if (0 === $idx) { + $rows[] = [sprintf( + '%s: %s', + str_pad($headers[$i] ?? '', $maxHeaderLength, ' ', \STR_PAD_LEFT), + $part + )]; + } else { + $rows[] = [sprintf( + '%s %s', + str_pad('', $maxHeaderLength, ' ', \STR_PAD_LEFT), + $part + )]; + } + } elseif ('' !== $cell) { + $rows[] = [$part]; + } + } + } + } + } else { + $rows = array_merge($this->headers, [$divider], $this->rows); + } + + $this->calculateNumberOfColumns($rows); + + $rowGroups = $this->buildTableRows($rows); + $this->calculateColumnsWidth($rowGroups); + + $isHeader = !$horizontal; + $isFirstRow = $horizontal; + $hasTitle = (bool) $this->headerTitle; + + foreach ($rowGroups as $rowGroup) { + $isHeaderSeparatorRendered = false; + + foreach ($rowGroup as $row) { + if ($divider === $row) { + $isHeader = false; + $isFirstRow = true; + + continue; + } + + if ($row instanceof TableSeparator) { + $this->renderRowSeparator(); + + continue; + } + + if (!$row) { + continue; + } + + if ($isHeader && !$isHeaderSeparatorRendered) { + $this->renderRowSeparator( + self::SEPARATOR_TOP, + $hasTitle ? $this->headerTitle : null, + $hasTitle ? $this->style->getHeaderTitleFormat() : null + ); + $hasTitle = false; + $isHeaderSeparatorRendered = true; + } + + if ($isFirstRow) { + $this->renderRowSeparator( + $horizontal ? self::SEPARATOR_TOP : self::SEPARATOR_TOP_BOTTOM, + $hasTitle ? $this->headerTitle : null, + $hasTitle ? $this->style->getHeaderTitleFormat() : null + ); + $isFirstRow = false; + $hasTitle = false; + } + + if ($vertical) { + $isHeader = false; + $isFirstRow = false; + } + + if ($horizontal) { + $this->renderRow($row, $this->style->getCellRowFormat(), $this->style->getCellHeaderFormat()); + } else { + $this->renderRow($row, $isHeader ? $this->style->getCellHeaderFormat() : $this->style->getCellRowFormat()); + } + } + } + $this->renderRowSeparator(self::SEPARATOR_BOTTOM, $this->footerTitle, $this->style->getFooterTitleFormat()); + + $this->cleanup(); + $this->rendered = true; + } + + /** + * Renders horizontal header separator. + * + * Example: + * + * +-----+-----------+-------+ + */ + private function renderRowSeparator(int $type = self::SEPARATOR_MID, string $title = null, string $titleFormat = null): void + { + if (!$count = $this->numberOfColumns) { + return; + } + + $borders = $this->style->getBorderChars(); + if (!$borders[0] && !$borders[2] && !$this->style->getCrossingChar()) { + return; + } + + $crossings = $this->style->getCrossingChars(); + if (self::SEPARATOR_MID === $type) { + [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[2], $crossings[8], $crossings[0], $crossings[4]]; + } elseif (self::SEPARATOR_TOP === $type) { + [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[0], $crossings[1], $crossings[2], $crossings[3]]; + } elseif (self::SEPARATOR_TOP_BOTTOM === $type) { + [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[0], $crossings[9], $crossings[10], $crossings[11]]; + } else { + [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[0], $crossings[7], $crossings[6], $crossings[5]]; + } + + $markup = $leftChar; + for ($column = 0; $column < $count; ++$column) { + $markup .= str_repeat($horizontal, $this->effectiveColumnWidths[$column]); + $markup .= $column === $count - 1 ? $rightChar : $midChar; + } + + if (null !== $title) { + $titleLength = Helper::width(Helper::removeDecoration($formatter = $this->output->getFormatter(), $formattedTitle = sprintf($titleFormat, $title))); + $markupLength = Helper::width($markup); + if ($titleLength > $limit = $markupLength - 4) { + $titleLength = $limit; + $formatLength = Helper::width(Helper::removeDecoration($formatter, sprintf($titleFormat, ''))); + $formattedTitle = sprintf($titleFormat, Helper::substr($title, 0, $limit - $formatLength - 3).'...'); + } + + $titleStart = intdiv($markupLength - $titleLength, 2); + if (false === mb_detect_encoding($markup, null, true)) { + $markup = substr_replace($markup, $formattedTitle, $titleStart, $titleLength); + } else { + $markup = mb_substr($markup, 0, $titleStart).$formattedTitle.mb_substr($markup, $titleStart + $titleLength); + } + } + + $this->output->writeln(sprintf($this->style->getBorderFormat(), $markup)); + } + + /** + * Renders vertical column separator. + */ + private function renderColumnSeparator(int $type = self::BORDER_OUTSIDE): string + { + $borders = $this->style->getBorderChars(); + + return sprintf($this->style->getBorderFormat(), self::BORDER_OUTSIDE === $type ? $borders[1] : $borders[3]); + } + + /** + * Renders table row. + * + * Example: + * + * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens | + */ + private function renderRow(array $row, string $cellFormat, string $firstCellFormat = null): void + { + $rowContent = $this->renderColumnSeparator(self::BORDER_OUTSIDE); + $columns = $this->getRowColumns($row); + $last = \count($columns) - 1; + foreach ($columns as $i => $column) { + if ($firstCellFormat && 0 === $i) { + $rowContent .= $this->renderCell($row, $column, $firstCellFormat); + } else { + $rowContent .= $this->renderCell($row, $column, $cellFormat); + } + $rowContent .= $this->renderColumnSeparator($last === $i ? self::BORDER_OUTSIDE : self::BORDER_INSIDE); + } + $this->output->writeln($rowContent); + } + + /** + * Renders table cell with padding. + */ + private function renderCell(array $row, int $column, string $cellFormat): string + { + $cell = $row[$column] ?? ''; + $width = $this->effectiveColumnWidths[$column]; + if ($cell instanceof TableCell && $cell->getColspan() > 1) { + // add the width of the following columns(numbers of colspan). + foreach (range($column + 1, $column + $cell->getColspan() - 1) as $nextColumn) { + $width += $this->getColumnSeparatorWidth() + $this->effectiveColumnWidths[$nextColumn]; + } + } + + // str_pad won't work properly with multi-byte strings, we need to fix the padding + if (false !== $encoding = mb_detect_encoding($cell, null, true)) { + $width += \strlen($cell) - mb_strwidth($cell, $encoding); + } + + $style = $this->getColumnStyle($column); + + if ($cell instanceof TableSeparator) { + return sprintf($style->getBorderFormat(), str_repeat($style->getBorderChars()[2], $width)); + } + + $width += Helper::length($cell) - Helper::length(Helper::removeDecoration($this->output->getFormatter(), $cell)); + $content = sprintf($style->getCellRowContentFormat(), $cell); + + $padType = $style->getPadType(); + if ($cell instanceof TableCell && $cell->getStyle() instanceof TableCellStyle) { + $isNotStyledByTag = !preg_match('/^<(\w+|(\w+=[\w,]+;?)*)>.+<\/(\w+|(\w+=\w+;?)*)?>$/', $cell); + if ($isNotStyledByTag) { + $cellFormat = $cell->getStyle()->getCellFormat(); + if (!\is_string($cellFormat)) { + $tag = http_build_query($cell->getStyle()->getTagOptions(), '', ';'); + $cellFormat = '<'.$tag.'>%s'; + } + + if (str_contains($content, '')) { + $content = str_replace('', '', $content); + $width -= 3; + } + if (str_contains($content, '')) { + $content = str_replace('', '', $content); + $width -= \strlen(''); + } + } + + $padType = $cell->getStyle()->getPadByAlign(); + } + + return sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $padType)); + } + + /** + * Calculate number of columns for this table. + */ + private function calculateNumberOfColumns(array $rows): void + { + $columns = [0]; + foreach ($rows as $row) { + if ($row instanceof TableSeparator) { + continue; + } + + $columns[] = $this->getNumberOfColumns($row); + } + + $this->numberOfColumns = max($columns); + } + + private function buildTableRows(array $rows): TableRows + { + /** @var WrappableOutputFormatterInterface $formatter */ + $formatter = $this->output->getFormatter(); + $unmergedRows = []; + for ($rowKey = 0; $rowKey < \count($rows); ++$rowKey) { + $rows = $this->fillNextRows($rows, $rowKey); + + // Remove any new line breaks and replace it with a new line + foreach ($rows[$rowKey] as $column => $cell) { + $colspan = $cell instanceof TableCell ? $cell->getColspan() : 1; + + if (isset($this->columnMaxWidths[$column]) && Helper::width(Helper::removeDecoration($formatter, $cell)) > $this->columnMaxWidths[$column]) { + $cell = $formatter->formatAndWrap($cell, $this->columnMaxWidths[$column] * $colspan); + } + if (!str_contains($cell ?? '', "\n")) { + continue; + } + $escaped = implode("\n", array_map(OutputFormatter::escapeTrailingBackslash(...), explode("\n", $cell))); + $cell = $cell instanceof TableCell ? new TableCell($escaped, ['colspan' => $cell->getColspan()]) : $escaped; + $lines = explode("\n", str_replace("\n", "\n", $cell)); + foreach ($lines as $lineKey => $line) { + if ($colspan > 1) { + $line = new TableCell($line, ['colspan' => $colspan]); + } + if (0 === $lineKey) { + $rows[$rowKey][$column] = $line; + } else { + if (!\array_key_exists($rowKey, $unmergedRows) || !\array_key_exists($lineKey, $unmergedRows[$rowKey])) { + $unmergedRows[$rowKey][$lineKey] = $this->copyRow($rows, $rowKey); + } + $unmergedRows[$rowKey][$lineKey][$column] = $line; + } + } + } + } + + return new TableRows(function () use ($rows, $unmergedRows): \Traversable { + foreach ($rows as $rowKey => $row) { + $rowGroup = [$row instanceof TableSeparator ? $row : $this->fillCells($row)]; + + if (isset($unmergedRows[$rowKey])) { + foreach ($unmergedRows[$rowKey] as $row) { + $rowGroup[] = $row instanceof TableSeparator ? $row : $this->fillCells($row); + } + } + yield $rowGroup; + } + }); + } + + private function calculateRowCount(): int + { + $numberOfRows = \count(iterator_to_array($this->buildTableRows(array_merge($this->headers, [new TableSeparator()], $this->rows)))); + + if ($this->headers) { + ++$numberOfRows; // Add row for header separator + } + + if ($this->rows) { + ++$numberOfRows; // Add row for footer separator + } + + return $numberOfRows; + } + + /** + * fill rows that contains rowspan > 1. + * + * @throws InvalidArgumentException + */ + private function fillNextRows(array $rows, int $line): array + { + $unmergedRows = []; + foreach ($rows[$line] as $column => $cell) { + if (null !== $cell && !$cell instanceof TableCell && !\is_scalar($cell) && !$cell instanceof \Stringable) { + throw new InvalidArgumentException(sprintf('A cell must be a TableCell, a scalar or an object implementing "__toString()", "%s" given.', get_debug_type($cell))); + } + if ($cell instanceof TableCell && $cell->getRowspan() > 1) { + $nbLines = $cell->getRowspan() - 1; + $lines = [$cell]; + if (str_contains($cell, "\n")) { + $lines = explode("\n", str_replace("\n", "\n", $cell)); + $nbLines = \count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines; + + $rows[$line][$column] = new TableCell($lines[0], ['colspan' => $cell->getColspan(), 'style' => $cell->getStyle()]); + unset($lines[0]); + } + + // create a two dimensional array (rowspan x colspan) + $unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, []), $unmergedRows); + foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) { + $value = $lines[$unmergedRowKey - $line] ?? ''; + $unmergedRows[$unmergedRowKey][$column] = new TableCell($value, ['colspan' => $cell->getColspan(), 'style' => $cell->getStyle()]); + if ($nbLines === $unmergedRowKey - $line) { + break; + } + } + } + } + + foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) { + // we need to know if $unmergedRow will be merged or inserted into $rows + if (isset($rows[$unmergedRowKey]) && \is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) { + foreach ($unmergedRow as $cellKey => $cell) { + // insert cell into row at cellKey position + array_splice($rows[$unmergedRowKey], $cellKey, 0, [$cell]); + } + } else { + $row = $this->copyRow($rows, $unmergedRowKey - 1); + foreach ($unmergedRow as $column => $cell) { + if (!empty($cell)) { + $row[$column] = $unmergedRow[$column]; + } + } + array_splice($rows, $unmergedRowKey, 0, [$row]); + } + } + + return $rows; + } + + /** + * fill cells for a row that contains colspan > 1. + */ + private function fillCells(iterable $row): iterable + { + $newRow = []; + + foreach ($row as $column => $cell) { + $newRow[] = $cell; + if ($cell instanceof TableCell && $cell->getColspan() > 1) { + foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) { + // insert empty value at column position + $newRow[] = ''; + } + } + } + + return $newRow ?: $row; + } + + private function copyRow(array $rows, int $line): array + { + $row = $rows[$line]; + foreach ($row as $cellKey => $cellValue) { + $row[$cellKey] = ''; + if ($cellValue instanceof TableCell) { + $row[$cellKey] = new TableCell('', ['colspan' => $cellValue->getColspan()]); + } + } + + return $row; + } + + /** + * Gets number of columns by row. + */ + private function getNumberOfColumns(array $row): int + { + $columns = \count($row); + foreach ($row as $column) { + $columns += $column instanceof TableCell ? ($column->getColspan() - 1) : 0; + } + + return $columns; + } + + /** + * Gets list of columns for the given row. + */ + private function getRowColumns(array $row): array + { + $columns = range(0, $this->numberOfColumns - 1); + foreach ($row as $cellKey => $cell) { + if ($cell instanceof TableCell && $cell->getColspan() > 1) { + // exclude grouped columns. + $columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1)); + } + } + + return $columns; + } + + /** + * Calculates columns widths. + */ + private function calculateColumnsWidth(iterable $groups): void + { + for ($column = 0; $column < $this->numberOfColumns; ++$column) { + $lengths = []; + foreach ($groups as $group) { + foreach ($group as $row) { + if ($row instanceof TableSeparator) { + continue; + } + + foreach ($row as $i => $cell) { + if ($cell instanceof TableCell) { + $textContent = Helper::removeDecoration($this->output->getFormatter(), $cell); + $textLength = Helper::width($textContent); + if ($textLength > 0) { + $contentColumns = mb_str_split($textContent, ceil($textLength / $cell->getColspan())); + foreach ($contentColumns as $position => $content) { + $row[$i + $position] = $content; + } + } + } + } + + $lengths[] = $this->getCellWidth($row, $column); + } + } + + $this->effectiveColumnWidths[$column] = max($lengths) + Helper::width($this->style->getCellRowContentFormat()) - 2; + } + } + + private function getColumnSeparatorWidth(): int + { + return Helper::width(sprintf($this->style->getBorderFormat(), $this->style->getBorderChars()[3])); + } + + private function getCellWidth(array $row, int $column): int + { + $cellWidth = 0; + + if (isset($row[$column])) { + $cell = $row[$column]; + $cellWidth = Helper::width(Helper::removeDecoration($this->output->getFormatter(), $cell)); + } + + $columnWidth = $this->columnWidths[$column] ?? 0; + $cellWidth = max($cellWidth, $columnWidth); + + return isset($this->columnMaxWidths[$column]) ? min($this->columnMaxWidths[$column], $cellWidth) : $cellWidth; + } + + /** + * Called after rendering to cleanup cache data. + */ + private function cleanup(): void + { + $this->effectiveColumnWidths = []; + unset($this->numberOfColumns); + } + + /** + * @return array + */ + private static function initStyles(): array + { + $borderless = new TableStyle(); + $borderless + ->setHorizontalBorderChars('=') + ->setVerticalBorderChars(' ') + ->setDefaultCrossingChar(' ') + ; + + $compact = new TableStyle(); + $compact + ->setHorizontalBorderChars('') + ->setVerticalBorderChars('') + ->setDefaultCrossingChar('') + ->setCellRowContentFormat('%s ') + ; + + $styleGuide = new TableStyle(); + $styleGuide + ->setHorizontalBorderChars('-') + ->setVerticalBorderChars(' ') + ->setDefaultCrossingChar(' ') + ->setCellHeaderFormat('%s') + ; + + $box = (new TableStyle()) + ->setHorizontalBorderChars('─') + ->setVerticalBorderChars('│') + ->setCrossingChars('┼', '┌', '┬', '┐', '┤', '┘', '┴', '└', '├') + ; + + $boxDouble = (new TableStyle()) + ->setHorizontalBorderChars('═', '─') + ->setVerticalBorderChars('║', '│') + ->setCrossingChars('┼', '╔', '╤', '╗', '╢', '╝', '╧', '╚', '╟', '╠', '╪', '╣') + ; + + return [ + 'default' => new TableStyle(), + 'borderless' => $borderless, + 'compact' => $compact, + 'symfony-style-guide' => $styleGuide, + 'box' => $box, + 'box-double' => $boxDouble, + ]; + } + + private function resolveStyle(TableStyle|string $name): TableStyle + { + if ($name instanceof TableStyle) { + return $name; + } + + return self::$styles[$name] ?? throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name)); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/TableCell.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/TableCell.php new file mode 100644 index 00000000..394b2bc9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/TableCell.php @@ -0,0 +1,72 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Exception\InvalidArgumentException; + +/** + * @author Abdellatif Ait boudad + */ +class TableCell +{ + private string $value; + private array $options = [ + 'rowspan' => 1, + 'colspan' => 1, + 'style' => null, + ]; + + public function __construct(string $value = '', array $options = []) + { + $this->value = $value; + + // check option names + if ($diff = array_diff(array_keys($options), array_keys($this->options))) { + throw new InvalidArgumentException(sprintf('The TableCell does not support the following options: \'%s\'.', implode('\', \'', $diff))); + } + + if (isset($options['style']) && !$options['style'] instanceof TableCellStyle) { + throw new InvalidArgumentException('The style option must be an instance of "TableCellStyle".'); + } + + $this->options = array_merge($this->options, $options); + } + + /** + * Returns the cell value. + */ + public function __toString(): string + { + return $this->value; + } + + /** + * Gets number of colspan. + */ + public function getColspan(): int + { + return (int) $this->options['colspan']; + } + + /** + * Gets number of rowspan. + */ + public function getRowspan(): int + { + return (int) $this->options['rowspan']; + } + + public function getStyle(): ?TableCellStyle + { + return $this->options['style']; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/TableCellStyle.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/TableCellStyle.php new file mode 100644 index 00000000..9419dcb4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/TableCellStyle.php @@ -0,0 +1,84 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Exception\InvalidArgumentException; + +/** + * @author Yewhen Khoptynskyi + */ +class TableCellStyle +{ + public const DEFAULT_ALIGN = 'left'; + + private const TAG_OPTIONS = [ + 'fg', + 'bg', + 'options', + ]; + + private const ALIGN_MAP = [ + 'left' => \STR_PAD_RIGHT, + 'center' => \STR_PAD_BOTH, + 'right' => \STR_PAD_LEFT, + ]; + + private array $options = [ + 'fg' => 'default', + 'bg' => 'default', + 'options' => null, + 'align' => self::DEFAULT_ALIGN, + 'cellFormat' => null, + ]; + + public function __construct(array $options = []) + { + if ($diff = array_diff(array_keys($options), array_keys($this->options))) { + throw new InvalidArgumentException(sprintf('The TableCellStyle does not support the following options: \'%s\'.', implode('\', \'', $diff))); + } + + if (isset($options['align']) && !\array_key_exists($options['align'], self::ALIGN_MAP)) { + throw new InvalidArgumentException(sprintf('Wrong align value. Value must be following: \'%s\'.', implode('\', \'', array_keys(self::ALIGN_MAP)))); + } + + $this->options = array_merge($this->options, $options); + } + + public function getOptions(): array + { + return $this->options; + } + + /** + * Gets options we need for tag for example fg, bg. + * + * @return string[] + */ + public function getTagOptions(): array + { + return array_filter( + $this->getOptions(), + fn ($key) => \in_array($key, self::TAG_OPTIONS) && isset($this->options[$key]), + \ARRAY_FILTER_USE_KEY + ); + } + + public function getPadByAlign(): int + { + return self::ALIGN_MAP[$this->getOptions()['align']]; + } + + public function getCellFormat(): ?string + { + return $this->getOptions()['cellFormat']; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/TableRows.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/TableRows.php new file mode 100644 index 00000000..97d07726 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/TableRows.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +/** + * @internal + */ +class TableRows implements \IteratorAggregate +{ + private \Closure $generator; + + public function __construct(\Closure $generator) + { + $this->generator = $generator; + } + + public function getIterator(): \Traversable + { + return ($this->generator)(); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/TableSeparator.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/TableSeparator.php new file mode 100644 index 00000000..e541c531 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/TableSeparator.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +/** + * Marks a row as being a separator. + * + * @author Fabien Potencier + */ +class TableSeparator extends TableCell +{ + public function __construct(array $options = []) + { + parent::__construct('', $options); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Helper/TableStyle.php b/tools/php-cs-fixer/vendor/symfony/console/Helper/TableStyle.php new file mode 100644 index 00000000..bbad98e7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Helper/TableStyle.php @@ -0,0 +1,362 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Helper; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\LogicException; + +/** + * Defines the styles for a Table. + * + * @author Fabien Potencier + * @author Саша Стаменковић + * @author Dany Maillard + */ +class TableStyle +{ + private string $paddingChar = ' '; + private string $horizontalOutsideBorderChar = '-'; + private string $horizontalInsideBorderChar = '-'; + private string $verticalOutsideBorderChar = '|'; + private string $verticalInsideBorderChar = '|'; + private string $crossingChar = '+'; + private string $crossingTopRightChar = '+'; + private string $crossingTopMidChar = '+'; + private string $crossingTopLeftChar = '+'; + private string $crossingMidRightChar = '+'; + private string $crossingBottomRightChar = '+'; + private string $crossingBottomMidChar = '+'; + private string $crossingBottomLeftChar = '+'; + private string $crossingMidLeftChar = '+'; + private string $crossingTopLeftBottomChar = '+'; + private string $crossingTopMidBottomChar = '+'; + private string $crossingTopRightBottomChar = '+'; + private string $headerTitleFormat = ' %s '; + private string $footerTitleFormat = ' %s '; + private string $cellHeaderFormat = '%s'; + private string $cellRowFormat = '%s'; + private string $cellRowContentFormat = ' %s '; + private string $borderFormat = '%s'; + private int $padType = \STR_PAD_RIGHT; + + /** + * Sets padding character, used for cell padding. + * + * @return $this + */ + public function setPaddingChar(string $paddingChar): static + { + if (!$paddingChar) { + throw new LogicException('The padding char must not be empty.'); + } + + $this->paddingChar = $paddingChar; + + return $this; + } + + /** + * Gets padding character, used for cell padding. + */ + public function getPaddingChar(): string + { + return $this->paddingChar; + } + + /** + * Sets horizontal border characters. + * + * + * ╔═══════════════╤══════════════════════════╤══════════════════╗ + * 1 ISBN 2 Title │ Author ║ + * ╠═══════════════╪══════════════════════════╪══════════════════╣ + * ║ 99921-58-10-7 │ Divine Comedy │ Dante Alighieri ║ + * ║ 9971-5-0210-0 │ A Tale of Two Cities │ Charles Dickens ║ + * ║ 960-425-059-0 │ The Lord of the Rings │ J. R. R. Tolkien ║ + * ║ 80-902734-1-6 │ And Then There Were None │ Agatha Christie ║ + * ╚═══════════════╧══════════════════════════╧══════════════════╝ + * + * + * @return $this + */ + public function setHorizontalBorderChars(string $outside, string $inside = null): static + { + $this->horizontalOutsideBorderChar = $outside; + $this->horizontalInsideBorderChar = $inside ?? $outside; + + return $this; + } + + /** + * Sets vertical border characters. + * + * + * ╔═══════════════╤══════════════════════════╤══════════════════╗ + * ║ ISBN │ Title │ Author ║ + * ╠═══════1═══════╪══════════════════════════╪══════════════════╣ + * ║ 99921-58-10-7 │ Divine Comedy │ Dante Alighieri ║ + * ║ 9971-5-0210-0 │ A Tale of Two Cities │ Charles Dickens ║ + * ╟───────2───────┼──────────────────────────┼──────────────────╢ + * ║ 960-425-059-0 │ The Lord of the Rings │ J. R. R. Tolkien ║ + * ║ 80-902734-1-6 │ And Then There Were None │ Agatha Christie ║ + * ╚═══════════════╧══════════════════════════╧══════════════════╝ + * + * + * @return $this + */ + public function setVerticalBorderChars(string $outside, string $inside = null): static + { + $this->verticalOutsideBorderChar = $outside; + $this->verticalInsideBorderChar = $inside ?? $outside; + + return $this; + } + + /** + * Gets border characters. + * + * @internal + */ + public function getBorderChars(): array + { + return [ + $this->horizontalOutsideBorderChar, + $this->verticalOutsideBorderChar, + $this->horizontalInsideBorderChar, + $this->verticalInsideBorderChar, + ]; + } + + /** + * Sets crossing characters. + * + * Example: + * + * 1═══════════════2══════════════════════════2══════════════════3 + * ║ ISBN │ Title │ Author ║ + * 8'══════════════0'═════════════════════════0'═════════════════4' + * ║ 99921-58-10-7 │ Divine Comedy │ Dante Alighieri ║ + * ║ 9971-5-0210-0 │ A Tale of Two Cities │ Charles Dickens ║ + * 8───────────────0──────────────────────────0──────────────────4 + * ║ 960-425-059-0 │ The Lord of the Rings │ J. R. R. Tolkien ║ + * ║ 80-902734-1-6 │ And Then There Were None │ Agatha Christie ║ + * 7═══════════════6══════════════════════════6══════════════════5 + * + * + * @param string $cross Crossing char (see #0 of example) + * @param string $topLeft Top left char (see #1 of example) + * @param string $topMid Top mid char (see #2 of example) + * @param string $topRight Top right char (see #3 of example) + * @param string $midRight Mid right char (see #4 of example) + * @param string $bottomRight Bottom right char (see #5 of example) + * @param string $bottomMid Bottom mid char (see #6 of example) + * @param string $bottomLeft Bottom left char (see #7 of example) + * @param string $midLeft Mid left char (see #8 of example) + * @param string|null $topLeftBottom Top left bottom char (see #8' of example), equals to $midLeft if null + * @param string|null $topMidBottom Top mid bottom char (see #0' of example), equals to $cross if null + * @param string|null $topRightBottom Top right bottom char (see #4' of example), equals to $midRight if null + * + * @return $this + */ + public function setCrossingChars(string $cross, string $topLeft, string $topMid, string $topRight, string $midRight, string $bottomRight, string $bottomMid, string $bottomLeft, string $midLeft, string $topLeftBottom = null, string $topMidBottom = null, string $topRightBottom = null): static + { + $this->crossingChar = $cross; + $this->crossingTopLeftChar = $topLeft; + $this->crossingTopMidChar = $topMid; + $this->crossingTopRightChar = $topRight; + $this->crossingMidRightChar = $midRight; + $this->crossingBottomRightChar = $bottomRight; + $this->crossingBottomMidChar = $bottomMid; + $this->crossingBottomLeftChar = $bottomLeft; + $this->crossingMidLeftChar = $midLeft; + $this->crossingTopLeftBottomChar = $topLeftBottom ?? $midLeft; + $this->crossingTopMidBottomChar = $topMidBottom ?? $cross; + $this->crossingTopRightBottomChar = $topRightBottom ?? $midRight; + + return $this; + } + + /** + * Sets default crossing character used for each cross. + * + * @see {@link setCrossingChars()} for setting each crossing individually. + */ + public function setDefaultCrossingChar(string $char): self + { + return $this->setCrossingChars($char, $char, $char, $char, $char, $char, $char, $char, $char); + } + + /** + * Gets crossing character. + */ + public function getCrossingChar(): string + { + return $this->crossingChar; + } + + /** + * Gets crossing characters. + * + * @internal + */ + public function getCrossingChars(): array + { + return [ + $this->crossingChar, + $this->crossingTopLeftChar, + $this->crossingTopMidChar, + $this->crossingTopRightChar, + $this->crossingMidRightChar, + $this->crossingBottomRightChar, + $this->crossingBottomMidChar, + $this->crossingBottomLeftChar, + $this->crossingMidLeftChar, + $this->crossingTopLeftBottomChar, + $this->crossingTopMidBottomChar, + $this->crossingTopRightBottomChar, + ]; + } + + /** + * Sets header cell format. + * + * @return $this + */ + public function setCellHeaderFormat(string $cellHeaderFormat): static + { + $this->cellHeaderFormat = $cellHeaderFormat; + + return $this; + } + + /** + * Gets header cell format. + */ + public function getCellHeaderFormat(): string + { + return $this->cellHeaderFormat; + } + + /** + * Sets row cell format. + * + * @return $this + */ + public function setCellRowFormat(string $cellRowFormat): static + { + $this->cellRowFormat = $cellRowFormat; + + return $this; + } + + /** + * Gets row cell format. + */ + public function getCellRowFormat(): string + { + return $this->cellRowFormat; + } + + /** + * Sets row cell content format. + * + * @return $this + */ + public function setCellRowContentFormat(string $cellRowContentFormat): static + { + $this->cellRowContentFormat = $cellRowContentFormat; + + return $this; + } + + /** + * Gets row cell content format. + */ + public function getCellRowContentFormat(): string + { + return $this->cellRowContentFormat; + } + + /** + * Sets table border format. + * + * @return $this + */ + public function setBorderFormat(string $borderFormat): static + { + $this->borderFormat = $borderFormat; + + return $this; + } + + /** + * Gets table border format. + */ + public function getBorderFormat(): string + { + return $this->borderFormat; + } + + /** + * Sets cell padding type. + * + * @return $this + */ + public function setPadType(int $padType): static + { + if (!\in_array($padType, [\STR_PAD_LEFT, \STR_PAD_RIGHT, \STR_PAD_BOTH], true)) { + throw new InvalidArgumentException('Invalid padding type. Expected one of (STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH).'); + } + + $this->padType = $padType; + + return $this; + } + + /** + * Gets cell padding type. + */ + public function getPadType(): int + { + return $this->padType; + } + + public function getHeaderTitleFormat(): string + { + return $this->headerTitleFormat; + } + + /** + * @return $this + */ + public function setHeaderTitleFormat(string $format): static + { + $this->headerTitleFormat = $format; + + return $this; + } + + public function getFooterTitleFormat(): string + { + return $this->footerTitleFormat; + } + + /** + * @return $this + */ + public function setFooterTitleFormat(string $format): static + { + $this->footerTitleFormat = $format; + + return $this; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Input/ArgvInput.php b/tools/php-cs-fixer/vendor/symfony/console/Input/ArgvInput.php new file mode 100644 index 00000000..9ae2f54f --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Input/ArgvInput.php @@ -0,0 +1,364 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Exception\RuntimeException; + +/** + * ArgvInput represents an input coming from the CLI arguments. + * + * Usage: + * + * $input = new ArgvInput(); + * + * By default, the `$_SERVER['argv']` array is used for the input values. + * + * This can be overridden by explicitly passing the input values in the constructor: + * + * $input = new ArgvInput($_SERVER['argv']); + * + * If you pass it yourself, don't forget that the first element of the array + * is the name of the running application. + * + * When passing an argument to the constructor, be sure that it respects + * the same rules as the argv one. It's almost always better to use the + * `StringInput` when you want to provide your own input. + * + * @author Fabien Potencier + * + * @see http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html + * @see http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap12.html#tag_12_02 + */ +class ArgvInput extends Input +{ + private array $tokens; + private array $parsed; + + public function __construct(array $argv = null, InputDefinition $definition = null) + { + $argv ??= $_SERVER['argv'] ?? []; + + // strip the application name + array_shift($argv); + + $this->tokens = $argv; + + parent::__construct($definition); + } + + protected function setTokens(array $tokens): void + { + $this->tokens = $tokens; + } + + protected function parse(): void + { + $parseOptions = true; + $this->parsed = $this->tokens; + while (null !== $token = array_shift($this->parsed)) { + $parseOptions = $this->parseToken($token, $parseOptions); + } + } + + protected function parseToken(string $token, bool $parseOptions): bool + { + if ($parseOptions && '' == $token) { + $this->parseArgument($token); + } elseif ($parseOptions && '--' == $token) { + return false; + } elseif ($parseOptions && str_starts_with($token, '--')) { + $this->parseLongOption($token); + } elseif ($parseOptions && '-' === $token[0] && '-' !== $token) { + $this->parseShortOption($token); + } else { + $this->parseArgument($token); + } + + return $parseOptions; + } + + /** + * Parses a short option. + */ + private function parseShortOption(string $token): void + { + $name = substr($token, 1); + + if (\strlen($name) > 1) { + if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) { + // an option with a value (with no space) + $this->addShortOption($name[0], substr($name, 1)); + } else { + $this->parseShortOptionSet($name); + } + } else { + $this->addShortOption($name, null); + } + } + + /** + * Parses a short option set. + * + * @throws RuntimeException When option given doesn't exist + */ + private function parseShortOptionSet(string $name): void + { + $len = \strlen($name); + for ($i = 0; $i < $len; ++$i) { + if (!$this->definition->hasShortcut($name[$i])) { + $encoding = mb_detect_encoding($name, null, true); + throw new RuntimeException(sprintf('The "-%s" option does not exist.', false === $encoding ? $name[$i] : mb_substr($name, $i, 1, $encoding))); + } + + $option = $this->definition->getOptionForShortcut($name[$i]); + if ($option->acceptValue()) { + $this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1)); + + break; + } else { + $this->addLongOption($option->getName(), null); + } + } + } + + /** + * Parses a long option. + */ + private function parseLongOption(string $token): void + { + $name = substr($token, 2); + + if (false !== $pos = strpos($name, '=')) { + if ('' === $value = substr($name, $pos + 1)) { + array_unshift($this->parsed, $value); + } + $this->addLongOption(substr($name, 0, $pos), $value); + } else { + $this->addLongOption($name, null); + } + } + + /** + * Parses an argument. + * + * @throws RuntimeException When too many arguments are given + */ + private function parseArgument(string $token): void + { + $c = \count($this->arguments); + + // if input is expecting another argument, add it + if ($this->definition->hasArgument($c)) { + $arg = $this->definition->getArgument($c); + $this->arguments[$arg->getName()] = $arg->isArray() ? [$token] : $token; + + // if last argument isArray(), append token to last argument + } elseif ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) { + $arg = $this->definition->getArgument($c - 1); + $this->arguments[$arg->getName()][] = $token; + + // unexpected argument + } else { + $all = $this->definition->getArguments(); + $symfonyCommandName = null; + if (($inputArgument = $all[$key = array_key_first($all)] ?? null) && 'command' === $inputArgument->getName()) { + $symfonyCommandName = $this->arguments['command'] ?? null; + unset($all[$key]); + } + + if (\count($all)) { + if ($symfonyCommandName) { + $message = sprintf('Too many arguments to "%s" command, expected arguments "%s".', $symfonyCommandName, implode('" "', array_keys($all))); + } else { + $message = sprintf('Too many arguments, expected arguments "%s".', implode('" "', array_keys($all))); + } + } elseif ($symfonyCommandName) { + $message = sprintf('No arguments expected for "%s" command, got "%s".', $symfonyCommandName, $token); + } else { + $message = sprintf('No arguments expected, got "%s".', $token); + } + + throw new RuntimeException($message); + } + } + + /** + * Adds a short option value. + * + * @throws RuntimeException When option given doesn't exist + */ + private function addShortOption(string $shortcut, mixed $value): void + { + if (!$this->definition->hasShortcut($shortcut)) { + throw new RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut)); + } + + $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value); + } + + /** + * Adds a long option value. + * + * @throws RuntimeException When option given doesn't exist + */ + private function addLongOption(string $name, mixed $value): void + { + if (!$this->definition->hasOption($name)) { + if (!$this->definition->hasNegation($name)) { + throw new RuntimeException(sprintf('The "--%s" option does not exist.', $name)); + } + + $optionName = $this->definition->negationToName($name); + if (null !== $value) { + throw new RuntimeException(sprintf('The "--%s" option does not accept a value.', $name)); + } + $this->options[$optionName] = false; + + return; + } + + $option = $this->definition->getOption($name); + + if (null !== $value && !$option->acceptValue()) { + throw new RuntimeException(sprintf('The "--%s" option does not accept a value.', $name)); + } + + if (\in_array($value, ['', null], true) && $option->acceptValue() && \count($this->parsed)) { + // if option accepts an optional or mandatory argument + // let's see if there is one provided + $next = array_shift($this->parsed); + if ((isset($next[0]) && '-' !== $next[0]) || \in_array($next, ['', null], true)) { + $value = $next; + } else { + array_unshift($this->parsed, $next); + } + } + + if (null === $value) { + if ($option->isValueRequired()) { + throw new RuntimeException(sprintf('The "--%s" option requires a value.', $name)); + } + + if (!$option->isArray() && !$option->isValueOptional()) { + $value = true; + } + } + + if ($option->isArray()) { + $this->options[$name][] = $value; + } else { + $this->options[$name] = $value; + } + } + + public function getFirstArgument(): ?string + { + $isOption = false; + foreach ($this->tokens as $i => $token) { + if ($token && '-' === $token[0]) { + if (str_contains($token, '=') || !isset($this->tokens[$i + 1])) { + continue; + } + + // If it's a long option, consider that everything after "--" is the option name. + // Otherwise, use the last char (if it's a short option set, only the last one can take a value with space separator) + $name = '-' === $token[1] ? substr($token, 2) : substr($token, -1); + if (!isset($this->options[$name]) && !$this->definition->hasShortcut($name)) { + // noop + } elseif ((isset($this->options[$name]) || isset($this->options[$name = $this->definition->shortcutToName($name)])) && $this->tokens[$i + 1] === $this->options[$name]) { + $isOption = true; + } + + continue; + } + + if ($isOption) { + $isOption = false; + continue; + } + + return $token; + } + + return null; + } + + public function hasParameterOption(string|array $values, bool $onlyParams = false): bool + { + $values = (array) $values; + + foreach ($this->tokens as $token) { + if ($onlyParams && '--' === $token) { + return false; + } + foreach ($values as $value) { + // Options with values: + // For long options, test for '--option=' at beginning + // For short options, test for '-o' at beginning + $leading = str_starts_with($value, '--') ? $value.'=' : $value; + if ($token === $value || '' !== $leading && str_starts_with($token, $leading)) { + return true; + } + } + } + + return false; + } + + public function getParameterOption(string|array $values, string|bool|int|float|array|null $default = false, bool $onlyParams = false): mixed + { + $values = (array) $values; + $tokens = $this->tokens; + + while (0 < \count($tokens)) { + $token = array_shift($tokens); + if ($onlyParams && '--' === $token) { + return $default; + } + + foreach ($values as $value) { + if ($token === $value) { + return array_shift($tokens); + } + // Options with values: + // For long options, test for '--option=' at beginning + // For short options, test for '-o' at beginning + $leading = str_starts_with($value, '--') ? $value.'=' : $value; + if ('' !== $leading && str_starts_with($token, $leading)) { + return substr($token, \strlen($leading)); + } + } + } + + return $default; + } + + /** + * Returns a stringified representation of the args passed to the command. + */ + public function __toString(): string + { + $tokens = array_map(function ($token) { + if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) { + return $match[1].$this->escapeToken($match[2]); + } + + if ($token && '-' !== $token[0]) { + return $this->escapeToken($token); + } + + return $token; + }, $this->tokens); + + return implode(' ', $tokens); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Input/ArrayInput.php b/tools/php-cs-fixer/vendor/symfony/console/Input/ArrayInput.php new file mode 100644 index 00000000..03b200b1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Input/ArrayInput.php @@ -0,0 +1,193 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\InvalidOptionException; + +/** + * ArrayInput represents an input provided as an array. + * + * Usage: + * + * $input = new ArrayInput(['command' => 'foo:bar', 'foo' => 'bar', '--bar' => 'foobar']); + * + * @author Fabien Potencier + */ +class ArrayInput extends Input +{ + private array $parameters; + + public function __construct(array $parameters, InputDefinition $definition = null) + { + $this->parameters = $parameters; + + parent::__construct($definition); + } + + public function getFirstArgument(): ?string + { + foreach ($this->parameters as $param => $value) { + if ($param && \is_string($param) && '-' === $param[0]) { + continue; + } + + return $value; + } + + return null; + } + + public function hasParameterOption(string|array $values, bool $onlyParams = false): bool + { + $values = (array) $values; + + foreach ($this->parameters as $k => $v) { + if (!\is_int($k)) { + $v = $k; + } + + if ($onlyParams && '--' === $v) { + return false; + } + + if (\in_array($v, $values)) { + return true; + } + } + + return false; + } + + public function getParameterOption(string|array $values, string|bool|int|float|array|null $default = false, bool $onlyParams = false): mixed + { + $values = (array) $values; + + foreach ($this->parameters as $k => $v) { + if ($onlyParams && ('--' === $k || (\is_int($k) && '--' === $v))) { + return $default; + } + + if (\is_int($k)) { + if (\in_array($v, $values)) { + return true; + } + } elseif (\in_array($k, $values)) { + return $v; + } + } + + return $default; + } + + /** + * Returns a stringified representation of the args passed to the command. + */ + public function __toString(): string + { + $params = []; + foreach ($this->parameters as $param => $val) { + if ($param && \is_string($param) && '-' === $param[0]) { + $glue = ('-' === $param[1]) ? '=' : ' '; + if (\is_array($val)) { + foreach ($val as $v) { + $params[] = $param.('' != $v ? $glue.$this->escapeToken($v) : ''); + } + } else { + $params[] = $param.('' != $val ? $glue.$this->escapeToken($val) : ''); + } + } else { + $params[] = \is_array($val) ? implode(' ', array_map($this->escapeToken(...), $val)) : $this->escapeToken($val); + } + } + + return implode(' ', $params); + } + + protected function parse(): void + { + foreach ($this->parameters as $key => $value) { + if ('--' === $key) { + return; + } + if (str_starts_with($key, '--')) { + $this->addLongOption(substr($key, 2), $value); + } elseif (str_starts_with($key, '-')) { + $this->addShortOption(substr($key, 1), $value); + } else { + $this->addArgument($key, $value); + } + } + } + + /** + * Adds a short option value. + * + * @throws InvalidOptionException When option given doesn't exist + */ + private function addShortOption(string $shortcut, mixed $value): void + { + if (!$this->definition->hasShortcut($shortcut)) { + throw new InvalidOptionException(sprintf('The "-%s" option does not exist.', $shortcut)); + } + + $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value); + } + + /** + * Adds a long option value. + * + * @throws InvalidOptionException When option given doesn't exist + * @throws InvalidOptionException When a required value is missing + */ + private function addLongOption(string $name, mixed $value): void + { + if (!$this->definition->hasOption($name)) { + if (!$this->definition->hasNegation($name)) { + throw new InvalidOptionException(sprintf('The "--%s" option does not exist.', $name)); + } + + $optionName = $this->definition->negationToName($name); + $this->options[$optionName] = false; + + return; + } + + $option = $this->definition->getOption($name); + + if (null === $value) { + if ($option->isValueRequired()) { + throw new InvalidOptionException(sprintf('The "--%s" option requires a value.', $name)); + } + + if (!$option->isValueOptional()) { + $value = true; + } + } + + $this->options[$name] = $value; + } + + /** + * Adds an argument value. + * + * @throws InvalidArgumentException When argument given doesn't exist + */ + private function addArgument(string|int $name, mixed $value): void + { + if (!$this->definition->hasArgument($name)) { + throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name)); + } + + $this->arguments[$name] = $value; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Input/Input.php b/tools/php-cs-fixer/vendor/symfony/console/Input/Input.php new file mode 100644 index 00000000..6a9248b7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Input/Input.php @@ -0,0 +1,174 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\RuntimeException; + +/** + * Input is the base class for all concrete Input classes. + * + * Three concrete classes are provided by default: + * + * * `ArgvInput`: The input comes from the CLI arguments (argv) + * * `StringInput`: The input is provided as a string + * * `ArrayInput`: The input is provided as an array + * + * @author Fabien Potencier + */ +abstract class Input implements InputInterface, StreamableInputInterface +{ + protected InputDefinition $definition; + /** @var resource */ + protected $stream; + protected array $options = []; + protected array $arguments = []; + protected bool $interactive = true; + + public function __construct(InputDefinition $definition = null) + { + if (null === $definition) { + $this->definition = new InputDefinition(); + } else { + $this->bind($definition); + $this->validate(); + } + } + + public function bind(InputDefinition $definition): void + { + $this->arguments = []; + $this->options = []; + $this->definition = $definition; + + $this->parse(); + } + + /** + * Processes command line arguments. + */ + abstract protected function parse(): void; + + public function validate(): void + { + $definition = $this->definition; + $givenArguments = $this->arguments; + + $missingArguments = array_filter(array_keys($definition->getArguments()), fn ($argument) => !\array_key_exists($argument, $givenArguments) && $definition->getArgument($argument)->isRequired()); + + if (\count($missingArguments) > 0) { + throw new RuntimeException(sprintf('Not enough arguments (missing: "%s").', implode(', ', $missingArguments))); + } + } + + public function isInteractive(): bool + { + return $this->interactive; + } + + public function setInteractive(bool $interactive): void + { + $this->interactive = $interactive; + } + + public function getArguments(): array + { + return array_merge($this->definition->getArgumentDefaults(), $this->arguments); + } + + public function getArgument(string $name): mixed + { + if (!$this->definition->hasArgument($name)) { + throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name)); + } + + return $this->arguments[$name] ?? $this->definition->getArgument($name)->getDefault(); + } + + public function setArgument(string $name, mixed $value): void + { + if (!$this->definition->hasArgument($name)) { + throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name)); + } + + $this->arguments[$name] = $value; + } + + public function hasArgument(string $name): bool + { + return $this->definition->hasArgument($name); + } + + public function getOptions(): array + { + return array_merge($this->definition->getOptionDefaults(), $this->options); + } + + public function getOption(string $name): mixed + { + if ($this->definition->hasNegation($name)) { + if (null === $value = $this->getOption($this->definition->negationToName($name))) { + return $value; + } + + return !$value; + } + + if (!$this->definition->hasOption($name)) { + throw new InvalidArgumentException(sprintf('The "%s" option does not exist.', $name)); + } + + return \array_key_exists($name, $this->options) ? $this->options[$name] : $this->definition->getOption($name)->getDefault(); + } + + public function setOption(string $name, mixed $value): void + { + if ($this->definition->hasNegation($name)) { + $this->options[$this->definition->negationToName($name)] = !$value; + + return; + } elseif (!$this->definition->hasOption($name)) { + throw new InvalidArgumentException(sprintf('The "%s" option does not exist.', $name)); + } + + $this->options[$name] = $value; + } + + public function hasOption(string $name): bool + { + return $this->definition->hasOption($name) || $this->definition->hasNegation($name); + } + + /** + * Escapes a token through escapeshellarg if it contains unsafe chars. + */ + public function escapeToken(string $token): string + { + return preg_match('{^[\w-]+$}', $token) ? $token : escapeshellarg($token); + } + + /** + * @param resource $stream + */ + public function setStream($stream): void + { + $this->stream = $stream; + } + + /** + * @return resource + */ + public function getStream() + { + return $this->stream; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Input/InputArgument.php b/tools/php-cs-fixer/vendor/symfony/console/Input/InputArgument.php new file mode 100644 index 00000000..642ae660 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Input/InputArgument.php @@ -0,0 +1,149 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Completion\Suggestion; +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\LogicException; + +/** + * Represents a command line argument. + * + * @author Fabien Potencier + */ +class InputArgument +{ + public const REQUIRED = 1; + public const OPTIONAL = 2; + public const IS_ARRAY = 4; + + private string $name; + private int $mode; + private string|int|bool|array|null|float $default; + private array|\Closure $suggestedValues; + private string $description; + + /** + * @param string $name The argument name + * @param int|null $mode The argument mode: a bit mask of self::REQUIRED, self::OPTIONAL and self::IS_ARRAY + * @param string $description A description text + * @param string|bool|int|float|array|null $default The default value (for self::OPTIONAL mode only) + * @param array|\Closure(CompletionInput,CompletionSuggestions):list $suggestedValues The values used for input completion + * + * @throws InvalidArgumentException When argument mode is not valid + */ + public function __construct(string $name, int $mode = null, string $description = '', string|bool|int|float|array $default = null, \Closure|array $suggestedValues = []) + { + if (null === $mode) { + $mode = self::OPTIONAL; + } elseif ($mode > 7 || $mode < 1) { + throw new InvalidArgumentException(sprintf('Argument mode "%s" is not valid.', $mode)); + } + + $this->name = $name; + $this->mode = $mode; + $this->description = $description; + $this->suggestedValues = $suggestedValues; + + $this->setDefault($default); + } + + /** + * Returns the argument name. + */ + public function getName(): string + { + return $this->name; + } + + /** + * Returns true if the argument is required. + * + * @return bool true if parameter mode is self::REQUIRED, false otherwise + */ + public function isRequired(): bool + { + return self::REQUIRED === (self::REQUIRED & $this->mode); + } + + /** + * Returns true if the argument can take multiple values. + * + * @return bool true if mode is self::IS_ARRAY, false otherwise + */ + public function isArray(): bool + { + return self::IS_ARRAY === (self::IS_ARRAY & $this->mode); + } + + /** + * Sets the default value. + * + * @throws LogicException When incorrect default value is given + */ + public function setDefault(string|bool|int|float|array|null $default): void + { + if ($this->isRequired() && null !== $default) { + throw new LogicException('Cannot set a default value except for InputArgument::OPTIONAL mode.'); + } + + if ($this->isArray()) { + if (null === $default) { + $default = []; + } elseif (!\is_array($default)) { + throw new LogicException('A default value for an array argument must be an array.'); + } + } + + $this->default = $default; + } + + /** + * Returns the default value. + */ + public function getDefault(): string|bool|int|float|array|null + { + return $this->default; + } + + public function hasCompletion(): bool + { + return [] !== $this->suggestedValues; + } + + /** + * Adds suggestions to $suggestions for the current completion input. + * + * @see Command::complete() + */ + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + $values = $this->suggestedValues; + if ($values instanceof \Closure && !\is_array($values = $values($input))) { + throw new LogicException(sprintf('Closure for argument "%s" must return an array. Got "%s".', $this->name, get_debug_type($values))); + } + if ($values) { + $suggestions->suggestValues($values); + } + } + + /** + * Returns the description text. + */ + public function getDescription(): string + { + return $this->description; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Input/InputAwareInterface.php b/tools/php-cs-fixer/vendor/symfony/console/Input/InputAwareInterface.php new file mode 100644 index 00000000..ba4664cd --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Input/InputAwareInterface.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +/** + * InputAwareInterface should be implemented by classes that depends on the + * Console Input. + * + * @author Wouter J + */ +interface InputAwareInterface +{ + /** + * Sets the Console Input. + */ + public function setInput(InputInterface $input): void; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Input/InputDefinition.php b/tools/php-cs-fixer/vendor/symfony/console/Input/InputDefinition.php new file mode 100644 index 00000000..f27e2974 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Input/InputDefinition.php @@ -0,0 +1,402 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\LogicException; + +/** + * A InputDefinition represents a set of valid command line arguments and options. + * + * Usage: + * + * $definition = new InputDefinition([ + * new InputArgument('name', InputArgument::REQUIRED), + * new InputOption('foo', 'f', InputOption::VALUE_REQUIRED), + * ]); + * + * @author Fabien Potencier + */ +class InputDefinition +{ + private array $arguments = []; + private int $requiredCount = 0; + private ?InputArgument $lastArrayArgument = null; + private ?InputArgument $lastOptionalArgument = null; + private array $options = []; + private array $negations = []; + private array $shortcuts = []; + + /** + * @param array $definition An array of InputArgument and InputOption instance + */ + public function __construct(array $definition = []) + { + $this->setDefinition($definition); + } + + /** + * Sets the definition of the input. + */ + public function setDefinition(array $definition): void + { + $arguments = []; + $options = []; + foreach ($definition as $item) { + if ($item instanceof InputOption) { + $options[] = $item; + } else { + $arguments[] = $item; + } + } + + $this->setArguments($arguments); + $this->setOptions($options); + } + + /** + * Sets the InputArgument objects. + * + * @param InputArgument[] $arguments An array of InputArgument objects + */ + public function setArguments(array $arguments = []): void + { + $this->arguments = []; + $this->requiredCount = 0; + $this->lastOptionalArgument = null; + $this->lastArrayArgument = null; + $this->addArguments($arguments); + } + + /** + * Adds an array of InputArgument objects. + * + * @param InputArgument[] $arguments An array of InputArgument objects + */ + public function addArguments(?array $arguments = []): void + { + if (null !== $arguments) { + foreach ($arguments as $argument) { + $this->addArgument($argument); + } + } + } + + /** + * @throws LogicException When incorrect argument is given + */ + public function addArgument(InputArgument $argument): void + { + if (isset($this->arguments[$argument->getName()])) { + throw new LogicException(sprintf('An argument with name "%s" already exists.', $argument->getName())); + } + + if (null !== $this->lastArrayArgument) { + throw new LogicException(sprintf('Cannot add a required argument "%s" after an array argument "%s".', $argument->getName(), $this->lastArrayArgument->getName())); + } + + if ($argument->isRequired() && null !== $this->lastOptionalArgument) { + throw new LogicException(sprintf('Cannot add a required argument "%s" after an optional one "%s".', $argument->getName(), $this->lastOptionalArgument->getName())); + } + + if ($argument->isArray()) { + $this->lastArrayArgument = $argument; + } + + if ($argument->isRequired()) { + ++$this->requiredCount; + } else { + $this->lastOptionalArgument = $argument; + } + + $this->arguments[$argument->getName()] = $argument; + } + + /** + * Returns an InputArgument by name or by position. + * + * @throws InvalidArgumentException When argument given doesn't exist + */ + public function getArgument(string|int $name): InputArgument + { + if (!$this->hasArgument($name)) { + throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name)); + } + + $arguments = \is_int($name) ? array_values($this->arguments) : $this->arguments; + + return $arguments[$name]; + } + + /** + * Returns true if an InputArgument object exists by name or position. + */ + public function hasArgument(string|int $name): bool + { + $arguments = \is_int($name) ? array_values($this->arguments) : $this->arguments; + + return isset($arguments[$name]); + } + + /** + * Gets the array of InputArgument objects. + * + * @return InputArgument[] + */ + public function getArguments(): array + { + return $this->arguments; + } + + /** + * Returns the number of InputArguments. + */ + public function getArgumentCount(): int + { + return null !== $this->lastArrayArgument ? \PHP_INT_MAX : \count($this->arguments); + } + + /** + * Returns the number of required InputArguments. + */ + public function getArgumentRequiredCount(): int + { + return $this->requiredCount; + } + + /** + * @return array + */ + public function getArgumentDefaults(): array + { + $values = []; + foreach ($this->arguments as $argument) { + $values[$argument->getName()] = $argument->getDefault(); + } + + return $values; + } + + /** + * Sets the InputOption objects. + * + * @param InputOption[] $options An array of InputOption objects + */ + public function setOptions(array $options = []): void + { + $this->options = []; + $this->shortcuts = []; + $this->negations = []; + $this->addOptions($options); + } + + /** + * Adds an array of InputOption objects. + * + * @param InputOption[] $options An array of InputOption objects + */ + public function addOptions(array $options = []): void + { + foreach ($options as $option) { + $this->addOption($option); + } + } + + /** + * @throws LogicException When option given already exist + */ + public function addOption(InputOption $option): void + { + if (isset($this->options[$option->getName()]) && !$option->equals($this->options[$option->getName()])) { + throw new LogicException(sprintf('An option named "%s" already exists.', $option->getName())); + } + if (isset($this->negations[$option->getName()])) { + throw new LogicException(sprintf('An option named "%s" already exists.', $option->getName())); + } + + if ($option->getShortcut()) { + foreach (explode('|', $option->getShortcut()) as $shortcut) { + if (isset($this->shortcuts[$shortcut]) && !$option->equals($this->options[$this->shortcuts[$shortcut]])) { + throw new LogicException(sprintf('An option with shortcut "%s" already exists.', $shortcut)); + } + } + } + + $this->options[$option->getName()] = $option; + if ($option->getShortcut()) { + foreach (explode('|', $option->getShortcut()) as $shortcut) { + $this->shortcuts[$shortcut] = $option->getName(); + } + } + + if ($option->isNegatable()) { + $negatedName = 'no-'.$option->getName(); + if (isset($this->options[$negatedName])) { + throw new LogicException(sprintf('An option named "%s" already exists.', $negatedName)); + } + $this->negations[$negatedName] = $option->getName(); + } + } + + /** + * Returns an InputOption by name. + * + * @throws InvalidArgumentException When option given doesn't exist + */ + public function getOption(string $name): InputOption + { + if (!$this->hasOption($name)) { + throw new InvalidArgumentException(sprintf('The "--%s" option does not exist.', $name)); + } + + return $this->options[$name]; + } + + /** + * Returns true if an InputOption object exists by name. + * + * This method can't be used to check if the user included the option when + * executing the command (use getOption() instead). + */ + public function hasOption(string $name): bool + { + return isset($this->options[$name]); + } + + /** + * Gets the array of InputOption objects. + * + * @return InputOption[] + */ + public function getOptions(): array + { + return $this->options; + } + + /** + * Returns true if an InputOption object exists by shortcut. + */ + public function hasShortcut(string $name): bool + { + return isset($this->shortcuts[$name]); + } + + /** + * Returns true if an InputOption object exists by negated name. + */ + public function hasNegation(string $name): bool + { + return isset($this->negations[$name]); + } + + /** + * Gets an InputOption by shortcut. + */ + public function getOptionForShortcut(string $shortcut): InputOption + { + return $this->getOption($this->shortcutToName($shortcut)); + } + + /** + * @return array + */ + public function getOptionDefaults(): array + { + $values = []; + foreach ($this->options as $option) { + $values[$option->getName()] = $option->getDefault(); + } + + return $values; + } + + /** + * Returns the InputOption name given a shortcut. + * + * @throws InvalidArgumentException When option given does not exist + * + * @internal + */ + public function shortcutToName(string $shortcut): string + { + if (!isset($this->shortcuts[$shortcut])) { + throw new InvalidArgumentException(sprintf('The "-%s" option does not exist.', $shortcut)); + } + + return $this->shortcuts[$shortcut]; + } + + /** + * Returns the InputOption name given a negation. + * + * @throws InvalidArgumentException When option given does not exist + * + * @internal + */ + public function negationToName(string $negation): string + { + if (!isset($this->negations[$negation])) { + throw new InvalidArgumentException(sprintf('The "--%s" option does not exist.', $negation)); + } + + return $this->negations[$negation]; + } + + /** + * Gets the synopsis. + */ + public function getSynopsis(bool $short = false): string + { + $elements = []; + + if ($short && $this->getOptions()) { + $elements[] = '[options]'; + } elseif (!$short) { + foreach ($this->getOptions() as $option) { + $value = ''; + if ($option->acceptValue()) { + $value = sprintf( + ' %s%s%s', + $option->isValueOptional() ? '[' : '', + strtoupper($option->getName()), + $option->isValueOptional() ? ']' : '' + ); + } + + $shortcut = $option->getShortcut() ? sprintf('-%s|', $option->getShortcut()) : ''; + $negation = $option->isNegatable() ? sprintf('|--no-%s', $option->getName()) : ''; + $elements[] = sprintf('[%s--%s%s%s]', $shortcut, $option->getName(), $value, $negation); + } + } + + if (\count($elements) && $this->getArguments()) { + $elements[] = '[--]'; + } + + $tail = ''; + foreach ($this->getArguments() as $argument) { + $element = '<'.$argument->getName().'>'; + if ($argument->isArray()) { + $element .= '...'; + } + + if (!$argument->isRequired()) { + $element = '['.$element; + $tail .= ']'; + } + + $elements[] = $element; + } + + return implode(' ', $elements).$tail; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Input/InputInterface.php b/tools/php-cs-fixer/vendor/symfony/console/Input/InputInterface.php new file mode 100644 index 00000000..c177d960 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Input/InputInterface.php @@ -0,0 +1,138 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\RuntimeException; + +/** + * InputInterface is the interface implemented by all input classes. + * + * @author Fabien Potencier + */ +interface InputInterface +{ + /** + * Returns the first argument from the raw parameters (not parsed). + */ + public function getFirstArgument(): ?string; + + /** + * Returns true if the raw parameters (not parsed) contain a value. + * + * This method is to be used to introspect the input parameters + * before they have been validated. It must be used carefully. + * Does not necessarily return the correct result for short options + * when multiple flags are combined in the same option. + * + * @param string|array $values The values to look for in the raw parameters (can be an array) + * @param bool $onlyParams Only check real parameters, skip those following an end of options (--) signal + */ + public function hasParameterOption(string|array $values, bool $onlyParams = false): bool; + + /** + * Returns the value of a raw option (not parsed). + * + * This method is to be used to introspect the input parameters + * before they have been validated. It must be used carefully. + * Does not necessarily return the correct result for short options + * when multiple flags are combined in the same option. + * + * @param string|array $values The value(s) to look for in the raw parameters (can be an array) + * @param string|bool|int|float|array|null $default The default value to return if no result is found + * @param bool $onlyParams Only check real parameters, skip those following an end of options (--) signal + */ + public function getParameterOption(string|array $values, string|bool|int|float|array|null $default = false, bool $onlyParams = false): mixed; + + /** + * Binds the current Input instance with the given arguments and options. + * + * @throws RuntimeException + */ + public function bind(InputDefinition $definition): void; + + /** + * Validates the input. + * + * @throws RuntimeException When not enough arguments are given + */ + public function validate(): void; + + /** + * Returns all the given arguments merged with the default values. + * + * @return array + */ + public function getArguments(): array; + + /** + * Returns the argument value for a given argument name. + * + * @throws InvalidArgumentException When argument given doesn't exist + */ + public function getArgument(string $name): mixed; + + /** + * Sets an argument value by name. + * + * @throws InvalidArgumentException When argument given doesn't exist + */ + public function setArgument(string $name, mixed $value): void; + + /** + * Returns true if an InputArgument object exists by name or position. + */ + public function hasArgument(string $name): bool; + + /** + * Returns all the given options merged with the default values. + * + * @return array + */ + public function getOptions(): array; + + /** + * Returns the option value for a given option name. + * + * @throws InvalidArgumentException When option given doesn't exist + */ + public function getOption(string $name): mixed; + + /** + * Sets an option value by name. + * + * @throws InvalidArgumentException When option given doesn't exist + */ + public function setOption(string $name, mixed $value): void; + + /** + * Returns true if an InputOption object exists by name. + */ + public function hasOption(string $name): bool; + + /** + * Is this input means interactive? + */ + public function isInteractive(): bool; + + /** + * Sets the input interactivity. + */ + public function setInteractive(bool $interactive): void; + + /** + * Returns a stringified representation of the args passed to the command. + * + * InputArguments MUST be escaped as well as the InputOption values passed to the command. + */ + public function __toString(): string; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Input/InputOption.php b/tools/php-cs-fixer/vendor/symfony/console/Input/InputOption.php new file mode 100644 index 00000000..f8e9b0dd --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Input/InputOption.php @@ -0,0 +1,249 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Completion\Suggestion; +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\LogicException; + +/** + * Represents a command line option. + * + * @author Fabien Potencier + */ +class InputOption +{ + /** + * Do not accept input for the option (e.g. --yell). This is the default behavior of options. + */ + public const VALUE_NONE = 1; + + /** + * A value must be passed when the option is used (e.g. --iterations=5 or -i5). + */ + public const VALUE_REQUIRED = 2; + + /** + * The option may or may not have a value (e.g. --yell or --yell=loud). + */ + public const VALUE_OPTIONAL = 4; + + /** + * The option accepts multiple values (e.g. --dir=/foo --dir=/bar). + */ + public const VALUE_IS_ARRAY = 8; + + /** + * The option may have either positive or negative value (e.g. --ansi or --no-ansi). + */ + public const VALUE_NEGATABLE = 16; + + private string $name; + private string|array|null $shortcut; + private int $mode; + private string|int|bool|array|null|float $default; + private array|\Closure $suggestedValues; + private string $description; + + /** + * @param string|array|null $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts + * @param int|null $mode The option mode: One of the VALUE_* constants + * @param string|bool|int|float|array|null $default The default value (must be null for self::VALUE_NONE) + * @param array|\Closure(CompletionInput,CompletionSuggestions):list $suggestedValues The values used for input completion + * + * @throws InvalidArgumentException If option mode is invalid or incompatible + */ + public function __construct(string $name, string|array $shortcut = null, int $mode = null, string $description = '', string|bool|int|float|array $default = null, array|\Closure $suggestedValues = []) + { + if (str_starts_with($name, '--')) { + $name = substr($name, 2); + } + + if (empty($name)) { + throw new InvalidArgumentException('An option name cannot be empty.'); + } + + if (empty($shortcut)) { + $shortcut = null; + } + + if (null !== $shortcut) { + if (\is_array($shortcut)) { + $shortcut = implode('|', $shortcut); + } + $shortcuts = preg_split('{(\|)-?}', ltrim($shortcut, '-')); + $shortcuts = array_filter($shortcuts); + $shortcut = implode('|', $shortcuts); + + if (empty($shortcut)) { + throw new InvalidArgumentException('An option shortcut cannot be empty.'); + } + } + + if (null === $mode) { + $mode = self::VALUE_NONE; + } elseif ($mode >= (self::VALUE_NEGATABLE << 1) || $mode < 1) { + throw new InvalidArgumentException(sprintf('Option mode "%s" is not valid.', $mode)); + } + + $this->name = $name; + $this->shortcut = $shortcut; + $this->mode = $mode; + $this->description = $description; + $this->suggestedValues = $suggestedValues; + + if ($suggestedValues && !$this->acceptValue()) { + throw new LogicException('Cannot set suggested values if the option does not accept a value.'); + } + if ($this->isArray() && !$this->acceptValue()) { + throw new InvalidArgumentException('Impossible to have an option mode VALUE_IS_ARRAY if the option does not accept a value.'); + } + if ($this->isNegatable() && $this->acceptValue()) { + throw new InvalidArgumentException('Impossible to have an option mode VALUE_NEGATABLE if the option also accepts a value.'); + } + + $this->setDefault($default); + } + + /** + * Returns the option shortcut. + */ + public function getShortcut(): ?string + { + return $this->shortcut; + } + + /** + * Returns the option name. + */ + public function getName(): string + { + return $this->name; + } + + /** + * Returns true if the option accepts a value. + * + * @return bool true if value mode is not self::VALUE_NONE, false otherwise + */ + public function acceptValue(): bool + { + return $this->isValueRequired() || $this->isValueOptional(); + } + + /** + * Returns true if the option requires a value. + * + * @return bool true if value mode is self::VALUE_REQUIRED, false otherwise + */ + public function isValueRequired(): bool + { + return self::VALUE_REQUIRED === (self::VALUE_REQUIRED & $this->mode); + } + + /** + * Returns true if the option takes an optional value. + * + * @return bool true if value mode is self::VALUE_OPTIONAL, false otherwise + */ + public function isValueOptional(): bool + { + return self::VALUE_OPTIONAL === (self::VALUE_OPTIONAL & $this->mode); + } + + /** + * Returns true if the option can take multiple values. + * + * @return bool true if mode is self::VALUE_IS_ARRAY, false otherwise + */ + public function isArray(): bool + { + return self::VALUE_IS_ARRAY === (self::VALUE_IS_ARRAY & $this->mode); + } + + public function isNegatable(): bool + { + return self::VALUE_NEGATABLE === (self::VALUE_NEGATABLE & $this->mode); + } + + public function setDefault(string|bool|int|float|array|null $default): void + { + if (self::VALUE_NONE === (self::VALUE_NONE & $this->mode) && null !== $default) { + throw new LogicException('Cannot set a default value when using InputOption::VALUE_NONE mode.'); + } + + if ($this->isArray()) { + if (null === $default) { + $default = []; + } elseif (!\is_array($default)) { + throw new LogicException('A default value for an array option must be an array.'); + } + } + + $this->default = $this->acceptValue() || $this->isNegatable() ? $default : false; + } + + /** + * Returns the default value. + */ + public function getDefault(): string|bool|int|float|array|null + { + return $this->default; + } + + /** + * Returns the description text. + */ + public function getDescription(): string + { + return $this->description; + } + + public function hasCompletion(): bool + { + return [] !== $this->suggestedValues; + } + + /** + * Adds suggestions to $suggestions for the current completion input. + * + * @see Command::complete() + */ + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + $values = $this->suggestedValues; + if ($values instanceof \Closure && !\is_array($values = $values($input))) { + throw new LogicException(sprintf('Closure for option "%s" must return an array. Got "%s".', $this->name, get_debug_type($values))); + } + if ($values) { + $suggestions->suggestValues($values); + } + } + + /** + * Checks whether the given option equals this one. + */ + public function equals(self $option): bool + { + return $option->getName() === $this->getName() + && $option->getShortcut() === $this->getShortcut() + && $option->getDefault() === $this->getDefault() + && $option->isNegatable() === $this->isNegatable() + && $option->isArray() === $this->isArray() + && $option->isValueRequired() === $this->isValueRequired() + && $option->isValueOptional() === $this->isValueOptional() + ; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Input/StreamableInputInterface.php b/tools/php-cs-fixer/vendor/symfony/console/Input/StreamableInputInterface.php new file mode 100644 index 00000000..4a0dc017 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Input/StreamableInputInterface.php @@ -0,0 +1,37 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +/** + * StreamableInputInterface is the interface implemented by all input classes + * that have an input stream. + * + * @author Robin Chalas + */ +interface StreamableInputInterface extends InputInterface +{ + /** + * Sets the input stream to read from when interacting with the user. + * + * This is mainly useful for testing purpose. + * + * @param resource $stream The input stream + */ + public function setStream($stream): void; + + /** + * Returns the input stream. + * + * @return resource|null + */ + public function getStream(); +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Input/StringInput.php b/tools/php-cs-fixer/vendor/symfony/console/Input/StringInput.php new file mode 100644 index 00000000..33f0f4b3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Input/StringInput.php @@ -0,0 +1,83 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Input; + +use Symfony\Component\Console\Exception\InvalidArgumentException; + +/** + * StringInput represents an input provided as a string. + * + * Usage: + * + * $input = new StringInput('foo --bar="foobar"'); + * + * @author Fabien Potencier + */ +class StringInput extends ArgvInput +{ + public const REGEX_UNQUOTED_STRING = '([^\s\\\\]+?)'; + public const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')'; + + /** + * @param string $input A string representing the parameters from the CLI + */ + public function __construct(string $input) + { + parent::__construct([]); + + $this->setTokens($this->tokenize($input)); + } + + /** + * Tokenizes a string. + * + * @throws InvalidArgumentException When unable to parse input (should never happen) + */ + private function tokenize(string $input): array + { + $tokens = []; + $length = \strlen($input); + $cursor = 0; + $token = null; + while ($cursor < $length) { + if ('\\' === $input[$cursor]) { + $token .= $input[++$cursor] ?? ''; + ++$cursor; + continue; + } + + if (preg_match('/\s+/A', $input, $match, 0, $cursor)) { + if (null !== $token) { + $tokens[] = $token; + $token = null; + } + } elseif (preg_match('/([^="\'\s]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, 0, $cursor)) { + $token .= $match[1].$match[2].stripcslashes(str_replace(['"\'', '\'"', '\'\'', '""'], '', substr($match[3], 1, -1))); + } elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, 0, $cursor)) { + $token .= stripcslashes(substr($match[0], 1, -1)); + } elseif (preg_match('/'.self::REGEX_UNQUOTED_STRING.'/A', $input, $match, 0, $cursor)) { + $token .= $match[1]; + } else { + // should never happen + throw new InvalidArgumentException(sprintf('Unable to parse input near "... %s ...".', substr($input, $cursor, 10))); + } + + $cursor += \strlen($match[0]); + } + + if (null !== $token) { + $tokens[] = $token; + } + + return $tokens; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/LICENSE b/tools/php-cs-fixer/vendor/symfony/console/LICENSE new file mode 100644 index 00000000..0138f8f0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/console/Logger/ConsoleLogger.php b/tools/php-cs-fixer/vendor/symfony/console/Logger/ConsoleLogger.php new file mode 100644 index 00000000..fddef50c --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Logger/ConsoleLogger.php @@ -0,0 +1,119 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Logger; + +use Psr\Log\AbstractLogger; +use Psr\Log\InvalidArgumentException; +use Psr\Log\LogLevel; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * PSR-3 compliant console logger. + * + * @author Kévin Dunglas + * + * @see https://www.php-fig.org/psr/psr-3/ + */ +class ConsoleLogger extends AbstractLogger +{ + public const INFO = 'info'; + public const ERROR = 'error'; + + private OutputInterface $output; + private array $verbosityLevelMap = [ + LogLevel::EMERGENCY => OutputInterface::VERBOSITY_NORMAL, + LogLevel::ALERT => OutputInterface::VERBOSITY_NORMAL, + LogLevel::CRITICAL => OutputInterface::VERBOSITY_NORMAL, + LogLevel::ERROR => OutputInterface::VERBOSITY_NORMAL, + LogLevel::WARNING => OutputInterface::VERBOSITY_NORMAL, + LogLevel::NOTICE => OutputInterface::VERBOSITY_VERBOSE, + LogLevel::INFO => OutputInterface::VERBOSITY_VERY_VERBOSE, + LogLevel::DEBUG => OutputInterface::VERBOSITY_DEBUG, + ]; + private array $formatLevelMap = [ + LogLevel::EMERGENCY => self::ERROR, + LogLevel::ALERT => self::ERROR, + LogLevel::CRITICAL => self::ERROR, + LogLevel::ERROR => self::ERROR, + LogLevel::WARNING => self::INFO, + LogLevel::NOTICE => self::INFO, + LogLevel::INFO => self::INFO, + LogLevel::DEBUG => self::INFO, + ]; + private bool $errored = false; + + public function __construct(OutputInterface $output, array $verbosityLevelMap = [], array $formatLevelMap = []) + { + $this->output = $output; + $this->verbosityLevelMap = $verbosityLevelMap + $this->verbosityLevelMap; + $this->formatLevelMap = $formatLevelMap + $this->formatLevelMap; + } + + public function log($level, $message, array $context = []): void + { + if (!isset($this->verbosityLevelMap[$level])) { + throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $level)); + } + + $output = $this->output; + + // Write to the error output if necessary and available + if (self::ERROR === $this->formatLevelMap[$level]) { + if ($this->output instanceof ConsoleOutputInterface) { + $output = $output->getErrorOutput(); + } + $this->errored = true; + } + + // the if condition check isn't necessary -- it's the same one that $output will do internally anyway. + // We only do it for efficiency here as the message formatting is relatively expensive. + if ($output->getVerbosity() >= $this->verbosityLevelMap[$level]) { + $output->writeln(sprintf('<%1$s>[%2$s] %3$s', $this->formatLevelMap[$level], $level, $this->interpolate($message, $context)), $this->verbosityLevelMap[$level]); + } + } + + /** + * Returns true when any messages have been logged at error levels. + */ + public function hasErrored(): bool + { + return $this->errored; + } + + /** + * Interpolates context values into the message placeholders. + * + * @author PHP Framework Interoperability Group + */ + private function interpolate(string $message, array $context): string + { + if (!str_contains($message, '{')) { + return $message; + } + + $replacements = []; + foreach ($context as $key => $val) { + if (null === $val || \is_scalar($val) || $val instanceof \Stringable) { + $replacements["{{$key}}"] = $val; + } elseif ($val instanceof \DateTimeInterface) { + $replacements["{{$key}}"] = $val->format(\DateTimeInterface::RFC3339); + } elseif (\is_object($val)) { + $replacements["{{$key}}"] = '[object '.$val::class.']'; + } else { + $replacements["{{$key}}"] = '['.\gettype($val).']'; + } + } + + return strtr($message, $replacements); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Messenger/RunCommandContext.php b/tools/php-cs-fixer/vendor/symfony/console/Messenger/RunCommandContext.php new file mode 100644 index 00000000..2ee5415c --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Messenger/RunCommandContext.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Messenger; + +/** + * @author Kevin Bond + */ +final class RunCommandContext +{ + public function __construct( + public readonly RunCommandMessage $message, + public readonly int $exitCode, + public readonly string $output, + ) { + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Messenger/RunCommandMessage.php b/tools/php-cs-fixer/vendor/symfony/console/Messenger/RunCommandMessage.php new file mode 100644 index 00000000..b530c438 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Messenger/RunCommandMessage.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Messenger; + +use Symfony\Component\Console\Exception\RunCommandFailedException; + +/** + * @author Kevin Bond + */ +class RunCommandMessage implements \Stringable +{ + /** + * @param bool $throwOnFailure If the command has a non-zero exit code, throw {@see RunCommandFailedException} + * @param bool $catchExceptions @see Application::setCatchExceptions() + */ + public function __construct( + public readonly string $input, + public readonly bool $throwOnFailure = true, + public readonly bool $catchExceptions = false, + ) { + } + + public function __toString(): string + { + return $this->input; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Messenger/RunCommandMessageHandler.php b/tools/php-cs-fixer/vendor/symfony/console/Messenger/RunCommandMessageHandler.php new file mode 100644 index 00000000..14f9c176 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Messenger/RunCommandMessageHandler.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Messenger; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\RunCommandFailedException; +use Symfony\Component\Console\Input\StringInput; +use Symfony\Component\Console\Output\BufferedOutput; + +/** + * @author Kevin Bond + */ +final class RunCommandMessageHandler +{ + public function __construct(private readonly Application $application) + { + } + + public function __invoke(RunCommandMessage $message): RunCommandContext + { + $input = new StringInput($message->input); + $output = new BufferedOutput(); + + $this->application->setCatchExceptions($message->catchExceptions); + + try { + $exitCode = $this->application->run($input, $output); + } catch (\Throwable $e) { + throw new RunCommandFailedException($e, new RunCommandContext($message, Command::FAILURE, $output->fetch())); + } + + if ($message->throwOnFailure && Command::SUCCESS !== $exitCode) { + throw new RunCommandFailedException(sprintf('Command "%s" exited with code "%s".', $message->input, $exitCode), new RunCommandContext($message, $exitCode, $output->fetch())); + } + + return new RunCommandContext($message, $exitCode, $output->fetch()); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Output/AnsiColorMode.php b/tools/php-cs-fixer/vendor/symfony/console/Output/AnsiColorMode.php new file mode 100644 index 00000000..5f9f744f --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Output/AnsiColorMode.php @@ -0,0 +1,106 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +use Symfony\Component\Console\Exception\InvalidArgumentException; + +/** + * @author Fabien Potencier + * @author Julien Boudry + */ +enum AnsiColorMode +{ + /* + * Classical 4-bit Ansi colors, including 8 classical colors and 8 bright color. Output syntax is "ESC[${foreGroundColorcode};${backGroundColorcode}m" + * Must be compatible with all terminals and it's the minimal version supported. + */ + case Ansi4; + + /* + * 8-bit Ansi colors (240 different colors + 16 duplicate color codes, ensuring backward compatibility). + * Output syntax is: "ESC[38;5;${foreGroundColorcode};48;5;${backGroundColorcode}m" + * Should be compatible with most terminals. + */ + case Ansi8; + + /* + * 24-bit Ansi colors (RGB). + * Output syntax is: "ESC[38;2;${foreGroundColorcodeRed};${foreGroundColorcodeGreen};${foreGroundColorcodeBlue};48;2;${backGroundColorcodeRed};${backGroundColorcodeGreen};${backGroundColorcodeBlue}m" + * May be compatible with many modern terminals. + */ + case Ansi24; + + /** + * Converts an RGB hexadecimal color to the corresponding Ansi code. + */ + public function convertFromHexToAnsiColorCode(string $hexColor): string + { + $hexColor = str_replace('#', '', $hexColor); + + if (3 === \strlen($hexColor)) { + $hexColor = $hexColor[0].$hexColor[0].$hexColor[1].$hexColor[1].$hexColor[2].$hexColor[2]; + } + + if (6 !== \strlen($hexColor)) { + throw new InvalidArgumentException(sprintf('Invalid "#%s" color.', $hexColor)); + } + + $color = hexdec($hexColor); + + $r = ($color >> 16) & 255; + $g = ($color >> 8) & 255; + $b = $color & 255; + + return match ($this) { + self::Ansi4 => (string) $this->convertFromRGB($r, $g, $b), + self::Ansi8 => '8;5;'.((string) $this->convertFromRGB($r, $g, $b)), + self::Ansi24 => sprintf('8;2;%d;%d;%d', $r, $g, $b) + }; + } + + private function convertFromRGB(int $r, int $g, int $b): int + { + return match ($this) { + self::Ansi4 => $this->degradeHexColorToAnsi4($r, $g, $b), + self::Ansi8 => $this->degradeHexColorToAnsi8($r, $g, $b), + default => throw new InvalidArgumentException("RGB cannot be converted to {$this->name}.") + }; + } + + private function degradeHexColorToAnsi4(int $r, int $g, int $b): int + { + return round($b / 255) << 2 | (round($g / 255) << 1) | round($r / 255); + } + + /** + * Inspired from https://github.com/ajalt/colormath/blob/e464e0da1b014976736cf97250063248fc77b8e7/colormath/src/commonMain/kotlin/com/github/ajalt/colormath/model/Ansi256.kt code (MIT license). + */ + private function degradeHexColorToAnsi8(int $r, int $g, int $b): int + { + if ($r === $g && $g === $b) { + if ($r < 8) { + return 16; + } + + if ($r > 248) { + return 231; + } + + return (int) round(($r - 8) / 247 * 24) + 232; + } else { + return 16 + + (36 * (int) round($r / 255 * 5)) + + (6 * (int) round($g / 255 * 5)) + + (int) round($b / 255 * 5); + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Output/BufferedOutput.php b/tools/php-cs-fixer/vendor/symfony/console/Output/BufferedOutput.php new file mode 100644 index 00000000..3c8d3906 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Output/BufferedOutput.php @@ -0,0 +1,40 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +/** + * @author Jean-François Simon + */ +class BufferedOutput extends Output +{ + private string $buffer = ''; + + /** + * Empties buffer and returns its content. + */ + public function fetch(): string + { + $content = $this->buffer; + $this->buffer = ''; + + return $content; + } + + protected function doWrite(string $message, bool $newline): void + { + $this->buffer .= $message; + + if ($newline) { + $this->buffer .= \PHP_EOL; + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Output/ConsoleOutput.php b/tools/php-cs-fixer/vendor/symfony/console/Output/ConsoleOutput.php new file mode 100644 index 00000000..f9e6c771 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Output/ConsoleOutput.php @@ -0,0 +1,153 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +use Symfony\Component\Console\Formatter\OutputFormatterInterface; + +/** + * ConsoleOutput is the default class for all CLI output. It uses STDOUT and STDERR. + * + * This class is a convenient wrapper around `StreamOutput` for both STDOUT and STDERR. + * + * $output = new ConsoleOutput(); + * + * This is equivalent to: + * + * $output = new StreamOutput(fopen('php://stdout', 'w')); + * $stdErr = new StreamOutput(fopen('php://stderr', 'w')); + * + * @author Fabien Potencier + */ +class ConsoleOutput extends StreamOutput implements ConsoleOutputInterface +{ + private OutputInterface $stderr; + private array $consoleSectionOutputs = []; + + /** + * @param int $verbosity The verbosity level (one of the VERBOSITY constants in OutputInterface) + * @param bool|null $decorated Whether to decorate messages (null for auto-guessing) + * @param OutputFormatterInterface|null $formatter Output formatter instance (null to use default OutputFormatter) + */ + public function __construct(int $verbosity = self::VERBOSITY_NORMAL, bool $decorated = null, OutputFormatterInterface $formatter = null) + { + parent::__construct($this->openOutputStream(), $verbosity, $decorated, $formatter); + + if (null === $formatter) { + // for BC reasons, stdErr has it own Formatter only when user don't inject a specific formatter. + $this->stderr = new StreamOutput($this->openErrorStream(), $verbosity, $decorated); + + return; + } + + $actualDecorated = $this->isDecorated(); + $this->stderr = new StreamOutput($this->openErrorStream(), $verbosity, $decorated, $this->getFormatter()); + + if (null === $decorated) { + $this->setDecorated($actualDecorated && $this->stderr->isDecorated()); + } + } + + /** + * Creates a new output section. + */ + public function section(): ConsoleSectionOutput + { + return new ConsoleSectionOutput($this->getStream(), $this->consoleSectionOutputs, $this->getVerbosity(), $this->isDecorated(), $this->getFormatter()); + } + + public function setDecorated(bool $decorated): void + { + parent::setDecorated($decorated); + $this->stderr->setDecorated($decorated); + } + + public function setFormatter(OutputFormatterInterface $formatter): void + { + parent::setFormatter($formatter); + $this->stderr->setFormatter($formatter); + } + + public function setVerbosity(int $level): void + { + parent::setVerbosity($level); + $this->stderr->setVerbosity($level); + } + + public function getErrorOutput(): OutputInterface + { + return $this->stderr; + } + + public function setErrorOutput(OutputInterface $error): void + { + $this->stderr = $error; + } + + /** + * Returns true if current environment supports writing console output to + * STDOUT. + */ + protected function hasStdoutSupport(): bool + { + return false === $this->isRunningOS400(); + } + + /** + * Returns true if current environment supports writing console output to + * STDERR. + */ + protected function hasStderrSupport(): bool + { + return false === $this->isRunningOS400(); + } + + /** + * Checks if current executing environment is IBM iSeries (OS400), which + * doesn't properly convert character-encodings between ASCII to EBCDIC. + */ + private function isRunningOS400(): bool + { + $checks = [ + \function_exists('php_uname') ? php_uname('s') : '', + getenv('OSTYPE'), + \PHP_OS, + ]; + + return false !== stripos(implode(';', $checks), 'OS400'); + } + + /** + * @return resource + */ + private function openOutputStream() + { + if (!$this->hasStdoutSupport()) { + return fopen('php://output', 'w'); + } + + // Use STDOUT when possible to prevent from opening too many file descriptors + return \defined('STDOUT') ? \STDOUT : (@fopen('php://stdout', 'w') ?: fopen('php://output', 'w')); + } + + /** + * @return resource + */ + private function openErrorStream() + { + if (!$this->hasStderrSupport()) { + return fopen('php://output', 'w'); + } + + // Use STDERR when possible to prevent from opening too many file descriptors + return \defined('STDERR') ? \STDERR : (@fopen('php://stderr', 'w') ?: fopen('php://output', 'w')); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Output/ConsoleOutputInterface.php b/tools/php-cs-fixer/vendor/symfony/console/Output/ConsoleOutputInterface.php new file mode 100644 index 00000000..1f8f147c --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Output/ConsoleOutputInterface.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +/** + * ConsoleOutputInterface is the interface implemented by ConsoleOutput class. + * This adds information about stderr and section output stream. + * + * @author Dariusz Górecki + */ +interface ConsoleOutputInterface extends OutputInterface +{ + /** + * Gets the OutputInterface for errors. + */ + public function getErrorOutput(): OutputInterface; + + public function setErrorOutput(OutputInterface $error): void; + + public function section(): ConsoleSectionOutput; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Output/ConsoleSectionOutput.php b/tools/php-cs-fixer/vendor/symfony/console/Output/ConsoleSectionOutput.php new file mode 100644 index 00000000..d5b5aff7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Output/ConsoleSectionOutput.php @@ -0,0 +1,237 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +use Symfony\Component\Console\Formatter\OutputFormatterInterface; +use Symfony\Component\Console\Helper\Helper; +use Symfony\Component\Console\Terminal; + +/** + * @author Pierre du Plessis + * @author Gabriel Ostrolucký + */ +class ConsoleSectionOutput extends StreamOutput +{ + private array $content = []; + private int $lines = 0; + private array $sections; + private Terminal $terminal; + private int $maxHeight = 0; + + /** + * @param resource $stream + * @param ConsoleSectionOutput[] $sections + */ + public function __construct($stream, array &$sections, int $verbosity, bool $decorated, OutputFormatterInterface $formatter) + { + parent::__construct($stream, $verbosity, $decorated, $formatter); + array_unshift($sections, $this); + $this->sections = &$sections; + $this->terminal = new Terminal(); + } + + /** + * Defines a maximum number of lines for this section. + * + * When more lines are added, the section will automatically scroll to the + * end (i.e. remove the first lines to comply with the max height). + */ + public function setMaxHeight(int $maxHeight): void + { + // when changing max height, clear output of current section and redraw again with the new height + $previousMaxHeight = $this->maxHeight; + $this->maxHeight = $maxHeight; + $existingContent = $this->popStreamContentUntilCurrentSection($previousMaxHeight ? min($previousMaxHeight, $this->lines) : $this->lines); + + parent::doWrite($this->getVisibleContent(), false); + parent::doWrite($existingContent, false); + } + + /** + * Clears previous output for this section. + * + * @param int $lines Number of lines to clear. If null, then the entire output of this section is cleared + */ + public function clear(int $lines = null): void + { + if (empty($this->content) || !$this->isDecorated()) { + return; + } + + if ($lines) { + array_splice($this->content, -$lines); + } else { + $lines = $this->lines; + $this->content = []; + } + + $this->lines -= $lines; + + parent::doWrite($this->popStreamContentUntilCurrentSection($this->maxHeight ? min($this->maxHeight, $lines) : $lines), false); + } + + /** + * Overwrites the previous output with a new message. + */ + public function overwrite(string|iterable $message): void + { + $this->clear(); + $this->writeln($message); + } + + public function getContent(): string + { + return implode('', $this->content); + } + + public function getVisibleContent(): string + { + if (0 === $this->maxHeight) { + return $this->getContent(); + } + + return implode('', \array_slice($this->content, -$this->maxHeight)); + } + + /** + * @internal + */ + public function addContent(string $input, bool $newline = true): int + { + $width = $this->terminal->getWidth(); + $lines = explode(\PHP_EOL, $input); + $linesAdded = 0; + $count = \count($lines) - 1; + foreach ($lines as $i => $lineContent) { + // re-add the line break (that has been removed in the above `explode()` for + // - every line that is not the last line + // - if $newline is required, also add it to the last line + if ($i < $count || $newline) { + $lineContent .= \PHP_EOL; + } + + // skip line if there is no text (or newline for that matter) + if ('' === $lineContent) { + continue; + } + + // For the first line, check if the previous line (last entry of `$this->content`) + // needs to be continued (i.e. does not end with a line break). + if (0 === $i + && (false !== $lastLine = end($this->content)) + && !str_ends_with($lastLine, \PHP_EOL) + ) { + // deduct the line count of the previous line + $this->lines -= (int) ceil($this->getDisplayLength($lastLine) / $width) ?: 1; + // concatenate previous and new line + $lineContent = $lastLine.$lineContent; + // replace last entry of `$this->content` with the new expanded line + array_splice($this->content, -1, 1, $lineContent); + } else { + // otherwise just add the new content + $this->content[] = $lineContent; + } + + $linesAdded += (int) ceil($this->getDisplayLength($lineContent) / $width) ?: 1; + } + + $this->lines += $linesAdded; + + return $linesAdded; + } + + /** + * @internal + */ + public function addNewLineOfInputSubmit(): void + { + $this->content[] = \PHP_EOL; + ++$this->lines; + } + + protected function doWrite(string $message, bool $newline): void + { + // Simulate newline behavior for consistent output formatting, avoiding extra logic + if (!$newline && str_ends_with($message, \PHP_EOL)) { + $message = substr($message, 0, -\strlen(\PHP_EOL)); + $newline = true; + } + + if (!$this->isDecorated()) { + parent::doWrite($message, $newline); + + return; + } + + // Check if the previous line (last entry of `$this->content`) needs to be continued + // (i.e. does not end with a line break). In which case, it needs to be erased first. + $linesToClear = $deleteLastLine = ($lastLine = end($this->content) ?: '') && !str_ends_with($lastLine, \PHP_EOL) ? 1 : 0; + + $linesAdded = $this->addContent($message, $newline); + + if ($lineOverflow = $this->maxHeight > 0 && $this->lines > $this->maxHeight) { + // on overflow, clear the whole section and redraw again (to remove the first lines) + $linesToClear = $this->maxHeight; + } + + $erasedContent = $this->popStreamContentUntilCurrentSection($linesToClear); + + if ($lineOverflow) { + // redraw existing lines of the section + $previousLinesOfSection = \array_slice($this->content, $this->lines - $this->maxHeight, $this->maxHeight - $linesAdded); + parent::doWrite(implode('', $previousLinesOfSection), false); + } + + // if the last line was removed, re-print its content together with the new content. + // otherwise, just print the new content. + parent::doWrite($deleteLastLine ? $lastLine.$message : $message, true); + parent::doWrite($erasedContent, false); + } + + /** + * At initial stage, cursor is at the end of stream output. This method makes cursor crawl upwards until it hits + * current section. Then it erases content it crawled through. Optionally, it erases part of current section too. + */ + private function popStreamContentUntilCurrentSection(int $numberOfLinesToClearFromCurrentSection = 0): string + { + $numberOfLinesToClear = $numberOfLinesToClearFromCurrentSection; + $erasedContent = []; + + foreach ($this->sections as $section) { + if ($section === $this) { + break; + } + + $numberOfLinesToClear += $section->maxHeight ? min($section->lines, $section->maxHeight) : $section->lines; + if ('' !== $sectionContent = $section->getVisibleContent()) { + if (!str_ends_with($sectionContent, \PHP_EOL)) { + $sectionContent .= \PHP_EOL; + } + $erasedContent[] = $sectionContent; + } + } + + if ($numberOfLinesToClear > 0) { + // move cursor up n lines + parent::doWrite(sprintf("\x1b[%dA", $numberOfLinesToClear), false); + // erase to end of screen + parent::doWrite("\x1b[0J", false); + } + + return implode('', array_reverse($erasedContent)); + } + + private function getDisplayLength(string $text): int + { + return Helper::width(Helper::removeDecoration($this->getFormatter(), str_replace("\t", ' ', $text))); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Output/NullOutput.php b/tools/php-cs-fixer/vendor/symfony/console/Output/NullOutput.php new file mode 100644 index 00000000..40ae3328 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Output/NullOutput.php @@ -0,0 +1,89 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +use Symfony\Component\Console\Formatter\NullOutputFormatter; +use Symfony\Component\Console\Formatter\OutputFormatterInterface; + +/** + * NullOutput suppresses all output. + * + * $output = new NullOutput(); + * + * @author Fabien Potencier + * @author Tobias Schultze + */ +class NullOutput implements OutputInterface +{ + private NullOutputFormatter $formatter; + + public function setFormatter(OutputFormatterInterface $formatter): void + { + // do nothing + } + + public function getFormatter(): OutputFormatterInterface + { + // to comply with the interface we must return a OutputFormatterInterface + return $this->formatter ??= new NullOutputFormatter(); + } + + public function setDecorated(bool $decorated): void + { + // do nothing + } + + public function isDecorated(): bool + { + return false; + } + + public function setVerbosity(int $level): void + { + // do nothing + } + + public function getVerbosity(): int + { + return self::VERBOSITY_QUIET; + } + + public function isQuiet(): bool + { + return true; + } + + public function isVerbose(): bool + { + return false; + } + + public function isVeryVerbose(): bool + { + return false; + } + + public function isDebug(): bool + { + return false; + } + + public function writeln(string|iterable $messages, int $options = self::OUTPUT_NORMAL): void + { + // do nothing + } + + public function write(string|iterable $messages, bool $newline = false, int $options = self::OUTPUT_NORMAL): void + { + // do nothing + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Output/Output.php b/tools/php-cs-fixer/vendor/symfony/console/Output/Output.php new file mode 100644 index 00000000..fe8564bb --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Output/Output.php @@ -0,0 +1,138 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Formatter\OutputFormatterInterface; + +/** + * Base class for output classes. + * + * There are five levels of verbosity: + * + * * normal: no option passed (normal output) + * * verbose: -v (more output) + * * very verbose: -vv (highly extended output) + * * debug: -vvv (all debug output) + * * quiet: -q (no output) + * + * @author Fabien Potencier + */ +abstract class Output implements OutputInterface +{ + private int $verbosity; + private OutputFormatterInterface $formatter; + + /** + * @param int|null $verbosity The verbosity level (one of the VERBOSITY constants in OutputInterface) + * @param bool $decorated Whether to decorate messages + * @param OutputFormatterInterface|null $formatter Output formatter instance (null to use default OutputFormatter) + */ + public function __construct(?int $verbosity = self::VERBOSITY_NORMAL, bool $decorated = false, OutputFormatterInterface $formatter = null) + { + $this->verbosity = $verbosity ?? self::VERBOSITY_NORMAL; + $this->formatter = $formatter ?? new OutputFormatter(); + $this->formatter->setDecorated($decorated); + } + + public function setFormatter(OutputFormatterInterface $formatter): void + { + $this->formatter = $formatter; + } + + public function getFormatter(): OutputFormatterInterface + { + return $this->formatter; + } + + public function setDecorated(bool $decorated): void + { + $this->formatter->setDecorated($decorated); + } + + public function isDecorated(): bool + { + return $this->formatter->isDecorated(); + } + + public function setVerbosity(int $level): void + { + $this->verbosity = $level; + } + + public function getVerbosity(): int + { + return $this->verbosity; + } + + public function isQuiet(): bool + { + return self::VERBOSITY_QUIET === $this->verbosity; + } + + public function isVerbose(): bool + { + return self::VERBOSITY_VERBOSE <= $this->verbosity; + } + + public function isVeryVerbose(): bool + { + return self::VERBOSITY_VERY_VERBOSE <= $this->verbosity; + } + + public function isDebug(): bool + { + return self::VERBOSITY_DEBUG <= $this->verbosity; + } + + public function writeln(string|iterable $messages, int $options = self::OUTPUT_NORMAL): void + { + $this->write($messages, true, $options); + } + + public function write(string|iterable $messages, bool $newline = false, int $options = self::OUTPUT_NORMAL): void + { + if (!is_iterable($messages)) { + $messages = [$messages]; + } + + $types = self::OUTPUT_NORMAL | self::OUTPUT_RAW | self::OUTPUT_PLAIN; + $type = $types & $options ?: self::OUTPUT_NORMAL; + + $verbosities = self::VERBOSITY_QUIET | self::VERBOSITY_NORMAL | self::VERBOSITY_VERBOSE | self::VERBOSITY_VERY_VERBOSE | self::VERBOSITY_DEBUG; + $verbosity = $verbosities & $options ?: self::VERBOSITY_NORMAL; + + if ($verbosity > $this->getVerbosity()) { + return; + } + + foreach ($messages as $message) { + switch ($type) { + case OutputInterface::OUTPUT_NORMAL: + $message = $this->formatter->format($message); + break; + case OutputInterface::OUTPUT_RAW: + break; + case OutputInterface::OUTPUT_PLAIN: + $message = strip_tags($this->formatter->format($message)); + break; + } + + $this->doWrite($message ?? '', $newline); + } + } + + /** + * Writes a message to the output. + */ + abstract protected function doWrite(string $message, bool $newline): void; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Output/OutputInterface.php b/tools/php-cs-fixer/vendor/symfony/console/Output/OutputInterface.php new file mode 100644 index 00000000..41315fbf --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Output/OutputInterface.php @@ -0,0 +1,100 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +use Symfony\Component\Console\Formatter\OutputFormatterInterface; + +/** + * OutputInterface is the interface implemented by all Output classes. + * + * @author Fabien Potencier + */ +interface OutputInterface +{ + public const VERBOSITY_QUIET = 16; + public const VERBOSITY_NORMAL = 32; + public const VERBOSITY_VERBOSE = 64; + public const VERBOSITY_VERY_VERBOSE = 128; + public const VERBOSITY_DEBUG = 256; + + public const OUTPUT_NORMAL = 1; + public const OUTPUT_RAW = 2; + public const OUTPUT_PLAIN = 4; + + /** + * Writes a message to the output. + * + * @param bool $newline Whether to add a newline + * @param int $options A bitmask of options (one of the OUTPUT or VERBOSITY constants), + * 0 is considered the same as self::OUTPUT_NORMAL | self::VERBOSITY_NORMAL + */ + public function write(string|iterable $messages, bool $newline = false, int $options = 0): void; + + /** + * Writes a message to the output and adds a newline at the end. + * + * @param int $options A bitmask of options (one of the OUTPUT or VERBOSITY constants), + * 0 is considered the same as self::OUTPUT_NORMAL | self::VERBOSITY_NORMAL + */ + public function writeln(string|iterable $messages, int $options = 0): void; + + /** + * Sets the verbosity of the output. + * + * @param self::VERBOSITY_* $level + */ + public function setVerbosity(int $level): void; + + /** + * Gets the current verbosity of the output. + * + * @return self::VERBOSITY_* + */ + public function getVerbosity(): int; + + /** + * Returns whether verbosity is quiet (-q). + */ + public function isQuiet(): bool; + + /** + * Returns whether verbosity is verbose (-v). + */ + public function isVerbose(): bool; + + /** + * Returns whether verbosity is very verbose (-vv). + */ + public function isVeryVerbose(): bool; + + /** + * Returns whether verbosity is debug (-vvv). + */ + public function isDebug(): bool; + + /** + * Sets the decorated flag. + */ + public function setDecorated(bool $decorated): void; + + /** + * Gets the decorated flag. + */ + public function isDecorated(): bool; + + public function setFormatter(OutputFormatterInterface $formatter): void; + + /** + * Returns current output formatter instance. + */ + public function getFormatter(): OutputFormatterInterface; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Output/StreamOutput.php b/tools/php-cs-fixer/vendor/symfony/console/Output/StreamOutput.php new file mode 100644 index 00000000..f5119ea0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Output/StreamOutput.php @@ -0,0 +1,111 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Formatter\OutputFormatterInterface; + +/** + * StreamOutput writes the output to a given stream. + * + * Usage: + * + * $output = new StreamOutput(fopen('php://stdout', 'w')); + * + * As `StreamOutput` can use any stream, you can also use a file: + * + * $output = new StreamOutput(fopen('/path/to/output.log', 'a', false)); + * + * @author Fabien Potencier + */ +class StreamOutput extends Output +{ + /** @var resource */ + private $stream; + + /** + * @param resource $stream A stream resource + * @param int $verbosity The verbosity level (one of the VERBOSITY constants in OutputInterface) + * @param bool|null $decorated Whether to decorate messages (null for auto-guessing) + * @param OutputFormatterInterface|null $formatter Output formatter instance (null to use default OutputFormatter) + * + * @throws InvalidArgumentException When first argument is not a real stream + */ + public function __construct($stream, int $verbosity = self::VERBOSITY_NORMAL, bool $decorated = null, OutputFormatterInterface $formatter = null) + { + if (!\is_resource($stream) || 'stream' !== get_resource_type($stream)) { + throw new InvalidArgumentException('The StreamOutput class needs a stream as its first argument.'); + } + + $this->stream = $stream; + + $decorated ??= $this->hasColorSupport(); + + parent::__construct($verbosity, $decorated, $formatter); + } + + /** + * Gets the stream attached to this StreamOutput instance. + * + * @return resource + */ + public function getStream() + { + return $this->stream; + } + + protected function doWrite(string $message, bool $newline): void + { + if ($newline) { + $message .= \PHP_EOL; + } + + @fwrite($this->stream, $message); + + fflush($this->stream); + } + + /** + * Returns true if the stream supports colorization. + * + * Colorization is disabled if not supported by the stream: + * + * This is tricky on Windows, because Cygwin, Msys2 etc emulate pseudo + * terminals via named pipes, so we can only check the environment. + * + * Reference: Composer\XdebugHandler\Process::supportsColor + * https://github.com/composer/xdebug-handler + * + * @return bool true if the stream supports colorization, false otherwise + */ + protected function hasColorSupport(): bool + { + // Follow https://no-color.org/ + if (isset($_SERVER['NO_COLOR']) || false !== getenv('NO_COLOR')) { + return false; + } + + if ('Hyper' === getenv('TERM_PROGRAM')) { + return true; + } + + if (\DIRECTORY_SEPARATOR === '\\') { + return (\function_exists('sapi_windows_vt100_support') + && @sapi_windows_vt100_support($this->stream)) + || false !== getenv('ANSICON') + || 'ON' === getenv('ConEmuANSI') + || 'xterm' === getenv('TERM'); + } + + return stream_isatty($this->stream); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Output/TrimmedBufferOutput.php b/tools/php-cs-fixer/vendor/symfony/console/Output/TrimmedBufferOutput.php new file mode 100644 index 00000000..5655e7bc --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Output/TrimmedBufferOutput.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Output; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Formatter\OutputFormatterInterface; + +/** + * A BufferedOutput that keeps only the last N chars. + * + * @author Jérémy Derussé + */ +class TrimmedBufferOutput extends Output +{ + private int $maxLength; + private string $buffer = ''; + + public function __construct(int $maxLength, ?int $verbosity = self::VERBOSITY_NORMAL, bool $decorated = false, OutputFormatterInterface $formatter = null) + { + if ($maxLength <= 0) { + throw new InvalidArgumentException(sprintf('"%s()" expects a strictly positive maxLength. Got %d.', __METHOD__, $maxLength)); + } + + parent::__construct($verbosity, $decorated, $formatter); + $this->maxLength = $maxLength; + } + + /** + * Empties buffer and returns its content. + */ + public function fetch(): string + { + $content = $this->buffer; + $this->buffer = ''; + + return $content; + } + + protected function doWrite(string $message, bool $newline): void + { + $this->buffer .= $message; + + if ($newline) { + $this->buffer .= \PHP_EOL; + } + + $this->buffer = substr($this->buffer, 0 - $this->maxLength); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Question/ChoiceQuestion.php b/tools/php-cs-fixer/vendor/symfony/console/Question/ChoiceQuestion.php new file mode 100644 index 00000000..e449ff68 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Question/ChoiceQuestion.php @@ -0,0 +1,177 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Question; + +use Symfony\Component\Console\Exception\InvalidArgumentException; + +/** + * Represents a choice question. + * + * @author Fabien Potencier + */ +class ChoiceQuestion extends Question +{ + private array $choices; + private bool $multiselect = false; + private string $prompt = ' > '; + private string $errorMessage = 'Value "%s" is invalid'; + + /** + * @param string $question The question to ask to the user + * @param array $choices The list of available choices + * @param mixed $default The default answer to return + */ + public function __construct(string $question, array $choices, mixed $default = null) + { + if (!$choices) { + throw new \LogicException('Choice question must have at least 1 choice available.'); + } + + parent::__construct($question, $default); + + $this->choices = $choices; + $this->setValidator($this->getDefaultValidator()); + $this->setAutocompleterValues($choices); + } + + /** + * Returns available choices. + */ + public function getChoices(): array + { + return $this->choices; + } + + /** + * Sets multiselect option. + * + * When multiselect is set to true, multiple choices can be answered. + * + * @return $this + */ + public function setMultiselect(bool $multiselect): static + { + $this->multiselect = $multiselect; + $this->setValidator($this->getDefaultValidator()); + + return $this; + } + + /** + * Returns whether the choices are multiselect. + */ + public function isMultiselect(): bool + { + return $this->multiselect; + } + + /** + * Gets the prompt for choices. + */ + public function getPrompt(): string + { + return $this->prompt; + } + + /** + * Sets the prompt for choices. + * + * @return $this + */ + public function setPrompt(string $prompt): static + { + $this->prompt = $prompt; + + return $this; + } + + /** + * Sets the error message for invalid values. + * + * The error message has a string placeholder (%s) for the invalid value. + * + * @return $this + */ + public function setErrorMessage(string $errorMessage): static + { + $this->errorMessage = $errorMessage; + $this->setValidator($this->getDefaultValidator()); + + return $this; + } + + private function getDefaultValidator(): callable + { + $choices = $this->choices; + $errorMessage = $this->errorMessage; + $multiselect = $this->multiselect; + $isAssoc = $this->isAssoc($choices); + + return function ($selected) use ($choices, $errorMessage, $multiselect, $isAssoc) { + if ($multiselect) { + // Check for a separated comma values + if (!preg_match('/^[^,]+(?:,[^,]+)*$/', (string) $selected, $matches)) { + throw new InvalidArgumentException(sprintf($errorMessage, $selected)); + } + + $selectedChoices = explode(',', (string) $selected); + } else { + $selectedChoices = [$selected]; + } + + if ($this->isTrimmable()) { + foreach ($selectedChoices as $k => $v) { + $selectedChoices[$k] = trim((string) $v); + } + } + + $multiselectChoices = []; + foreach ($selectedChoices as $value) { + $results = []; + foreach ($choices as $key => $choice) { + if ($choice === $value) { + $results[] = $key; + } + } + + if (\count($results) > 1) { + throw new InvalidArgumentException(sprintf('The provided answer is ambiguous. Value should be one of "%s".', implode('" or "', $results))); + } + + $result = array_search($value, $choices); + + if (!$isAssoc) { + if (false !== $result) { + $result = $choices[$result]; + } elseif (isset($choices[$value])) { + $result = $choices[$value]; + } + } elseif (false === $result && isset($choices[$value])) { + $result = $value; + } + + if (false === $result) { + throw new InvalidArgumentException(sprintf($errorMessage, $value)); + } + + // For associative choices, consistently return the key as string: + $multiselectChoices[] = $isAssoc ? (string) $result : $result; + } + + if ($multiselect) { + return $multiselectChoices; + } + + return current($multiselectChoices); + }; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Question/ConfirmationQuestion.php b/tools/php-cs-fixer/vendor/symfony/console/Question/ConfirmationQuestion.php new file mode 100644 index 00000000..40eab242 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Question/ConfirmationQuestion.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Question; + +/** + * Represents a yes/no question. + * + * @author Fabien Potencier + */ +class ConfirmationQuestion extends Question +{ + private string $trueAnswerRegex; + + /** + * @param string $question The question to ask to the user + * @param bool $default The default answer to return, true or false + * @param string $trueAnswerRegex A regex to match the "yes" answer + */ + public function __construct(string $question, bool $default = true, string $trueAnswerRegex = '/^y/i') + { + parent::__construct($question, $default); + + $this->trueAnswerRegex = $trueAnswerRegex; + $this->setNormalizer($this->getDefaultNormalizer()); + } + + /** + * Returns the default answer normalizer. + */ + private function getDefaultNormalizer(): callable + { + $default = $this->getDefault(); + $regex = $this->trueAnswerRegex; + + return function ($answer) use ($default, $regex) { + if (\is_bool($answer)) { + return $answer; + } + + $answerIsTrue = (bool) preg_match($regex, $answer); + if (false === $default) { + return $answer && $answerIsTrue; + } + + return '' === $answer || $answerIsTrue; + }; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Question/Question.php b/tools/php-cs-fixer/vendor/symfony/console/Question/Question.php new file mode 100644 index 00000000..c79683cd --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Question/Question.php @@ -0,0 +1,282 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Question; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\LogicException; + +/** + * Represents a Question. + * + * @author Fabien Potencier + */ +class Question +{ + private string $question; + private ?int $attempts = null; + private bool $hidden = false; + private bool $hiddenFallback = true; + private ?\Closure $autocompleterCallback = null; + private ?\Closure $validator = null; + private string|int|bool|null|float $default; + private ?\Closure $normalizer = null; + private bool $trimmable = true; + private bool $multiline = false; + + /** + * @param string $question The question to ask to the user + * @param string|bool|int|float|null $default The default answer to return if the user enters nothing + */ + public function __construct(string $question, string|bool|int|float $default = null) + { + $this->question = $question; + $this->default = $default; + } + + /** + * Returns the question. + */ + public function getQuestion(): string + { + return $this->question; + } + + /** + * Returns the default answer. + */ + public function getDefault(): string|bool|int|float|null + { + return $this->default; + } + + /** + * Returns whether the user response accepts newline characters. + */ + public function isMultiline(): bool + { + return $this->multiline; + } + + /** + * Sets whether the user response should accept newline characters. + * + * @return $this + */ + public function setMultiline(bool $multiline): static + { + $this->multiline = $multiline; + + return $this; + } + + /** + * Returns whether the user response must be hidden. + */ + public function isHidden(): bool + { + return $this->hidden; + } + + /** + * Sets whether the user response must be hidden or not. + * + * @return $this + * + * @throws LogicException In case the autocompleter is also used + */ + public function setHidden(bool $hidden): static + { + if ($this->autocompleterCallback) { + throw new LogicException('A hidden question cannot use the autocompleter.'); + } + + $this->hidden = $hidden; + + return $this; + } + + /** + * In case the response cannot be hidden, whether to fallback on non-hidden question or not. + */ + public function isHiddenFallback(): bool + { + return $this->hiddenFallback; + } + + /** + * Sets whether to fallback on non-hidden question if the response cannot be hidden. + * + * @return $this + */ + public function setHiddenFallback(bool $fallback): static + { + $this->hiddenFallback = $fallback; + + return $this; + } + + /** + * Gets values for the autocompleter. + */ + public function getAutocompleterValues(): ?iterable + { + $callback = $this->getAutocompleterCallback(); + + return $callback ? $callback('') : null; + } + + /** + * Sets values for the autocompleter. + * + * @return $this + * + * @throws LogicException + */ + public function setAutocompleterValues(?iterable $values): static + { + if (\is_array($values)) { + $values = $this->isAssoc($values) ? array_merge(array_keys($values), array_values($values)) : array_values($values); + + $callback = static fn () => $values; + } elseif ($values instanceof \Traversable) { + $callback = static function () use ($values) { + static $valueCache; + + return $valueCache ??= iterator_to_array($values, false); + }; + } else { + $callback = null; + } + + return $this->setAutocompleterCallback($callback); + } + + /** + * Gets the callback function used for the autocompleter. + */ + public function getAutocompleterCallback(): ?callable + { + return $this->autocompleterCallback; + } + + /** + * Sets the callback function used for the autocompleter. + * + * The callback is passed the user input as argument and should return an iterable of corresponding suggestions. + * + * @return $this + */ + public function setAutocompleterCallback(?callable $callback): static + { + if ($this->hidden && null !== $callback) { + throw new LogicException('A hidden question cannot use the autocompleter.'); + } + + $this->autocompleterCallback = null === $callback ? null : $callback(...); + + return $this; + } + + /** + * Sets a validator for the question. + * + * @return $this + */ + public function setValidator(?callable $validator): static + { + $this->validator = null === $validator ? null : $validator(...); + + return $this; + } + + /** + * Gets the validator for the question. + */ + public function getValidator(): ?callable + { + return $this->validator; + } + + /** + * Sets the maximum number of attempts. + * + * Null means an unlimited number of attempts. + * + * @return $this + * + * @throws InvalidArgumentException in case the number of attempts is invalid + */ + public function setMaxAttempts(?int $attempts): static + { + if (null !== $attempts && $attempts < 1) { + throw new InvalidArgumentException('Maximum number of attempts must be a positive value.'); + } + + $this->attempts = $attempts; + + return $this; + } + + /** + * Gets the maximum number of attempts. + * + * Null means an unlimited number of attempts. + */ + public function getMaxAttempts(): ?int + { + return $this->attempts; + } + + /** + * Sets a normalizer for the response. + * + * The normalizer can be a callable (a string), a closure or a class implementing __invoke. + * + * @return $this + */ + public function setNormalizer(callable $normalizer): static + { + $this->normalizer = $normalizer(...); + + return $this; + } + + /** + * Gets the normalizer for the response. + * + * The normalizer can ba a callable (a string), a closure or a class implementing __invoke. + */ + public function getNormalizer(): ?callable + { + return $this->normalizer; + } + + protected function isAssoc(array $array): bool + { + return (bool) \count(array_filter(array_keys($array), 'is_string')); + } + + public function isTrimmable(): bool + { + return $this->trimmable; + } + + /** + * @return $this + */ + public function setTrimmable(bool $trimmable): static + { + $this->trimmable = $trimmable; + + return $this; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/README.md b/tools/php-cs-fixer/vendor/symfony/console/README.md new file mode 100644 index 00000000..ded2bc11 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/README.md @@ -0,0 +1,36 @@ +Console Component +================= + +The Console component eases the creation of beautiful and testable command line +interfaces. + +Sponsor +------- + +The Console component for Symfony 7.0 is [backed][1] by [Les-Tilleuls.coop][2]. + +Les-Tilleuls.coop is a team of 70+ Symfony experts who can help you design, develop and +fix your projects. They provide a wide range of professional services including development, +consulting, coaching, training and audits. They also are highly skilled in JS, Go and DevOps. +They are a worker cooperative! + +Help Symfony by [sponsoring][3] its development! + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/console.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) + +Credits +------- + +`Resources/bin/hiddeninput.exe` is a third party binary provided within this +component. Find sources and license at https://github.com/Seldaek/hidden-input. + +[1]: https://symfony.com/backers +[2]: https://les-tilleuls.coop +[3]: https://symfony.com/sponsor diff --git a/tools/php-cs-fixer/vendor/symfony/console/Resources/bin/hiddeninput.exe b/tools/php-cs-fixer/vendor/symfony/console/Resources/bin/hiddeninput.exe new file mode 100644 index 00000000..c8cf65e8 Binary files /dev/null and b/tools/php-cs-fixer/vendor/symfony/console/Resources/bin/hiddeninput.exe differ diff --git a/tools/php-cs-fixer/vendor/symfony/console/Resources/completion.bash b/tools/php-cs-fixer/vendor/symfony/console/Resources/completion.bash new file mode 100644 index 00000000..0d76eacc --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Resources/completion.bash @@ -0,0 +1,94 @@ +# This file is part of the Symfony package. +# +# (c) Fabien Potencier +# +# For the full copyright and license information, please view +# https://symfony.com/doc/current/contributing/code/license.html + +_sf_{{ COMMAND_NAME }}() { + + # Use the default completion for shell redirect operators. + for w in '>' '>>' '&>' '<'; do + if [[ $w = "${COMP_WORDS[COMP_CWORD-1]}" ]]; then + compopt -o filenames + COMPREPLY=($(compgen -f -- "${COMP_WORDS[COMP_CWORD]}")) + return 0 + fi + done + + # Use newline as only separator to allow space in completion values + IFS=$'\n' + local sf_cmd="${COMP_WORDS[0]}" + + # for an alias, get the real script behind it + sf_cmd_type=$(type -t $sf_cmd) + if [[ $sf_cmd_type == "alias" ]]; then + sf_cmd=$(alias $sf_cmd | sed -E "s/alias $sf_cmd='(.*)'/\1/") + elif [[ $sf_cmd_type == "file" ]]; then + sf_cmd=$(type -p $sf_cmd) + fi + + if [[ $sf_cmd_type != "function" && ! -x $sf_cmd ]]; then + return 1 + fi + + local cur prev words cword + _get_comp_words_by_ref -n := cur prev words cword + + local completecmd=("$sf_cmd" "_complete" "--no-interaction" "-sbash" "-c$cword" "-a{{ VERSION }}") + for w in ${words[@]}; do + w=$(printf -- '%b' "$w") + # remove quotes from typed values + quote="${w:0:1}" + if [ "$quote" == \' ]; then + w="${w%\'}" + w="${w#\'}" + elif [ "$quote" == \" ]; then + w="${w%\"}" + w="${w#\"}" + fi + # empty values are ignored + if [ ! -z "$w" ]; then + completecmd+=("-i$w") + fi + done + + local sfcomplete + if sfcomplete=$(${completecmd[@]} 2>&1); then + local quote suggestions + quote=${cur:0:1} + + # Use single quotes by default if suggestions contains backslash (FQCN) + if [ "$quote" == '' ] && [[ "$sfcomplete" =~ \\ ]]; then + quote=\' + fi + + if [ "$quote" == \' ]; then + # single quotes: no additional escaping (does not accept ' in values) + suggestions=$(for s in $sfcomplete; do printf $'%q%q%q\n' "$quote" "$s" "$quote"; done) + elif [ "$quote" == \" ]; then + # double quotes: double escaping for \ $ ` " + suggestions=$(for s in $sfcomplete; do + s=${s//\\/\\\\} + s=${s//\$/\\\$} + s=${s//\`/\\\`} + s=${s//\"/\\\"} + printf $'%q%q%q\n' "$quote" "$s" "$quote"; + done) + else + # no quotes: double escaping + suggestions=$(for s in $sfcomplete; do printf $'%q\n' $(printf '%q' "$s"); done) + fi + COMPREPLY=($(IFS=$'\n' compgen -W "$suggestions" -- $(printf -- "%q" "$cur"))) + __ltrim_colon_completions "$cur" + else + if [[ "$sfcomplete" != *"Command \"_complete\" is not defined."* ]]; then + >&2 echo + >&2 echo $sfcomplete + fi + + return 1 + fi +} + +complete -F _sf_{{ COMMAND_NAME }} {{ COMMAND_NAME }} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Resources/completion.fish b/tools/php-cs-fixer/vendor/symfony/console/Resources/completion.fish new file mode 100644 index 00000000..1c34292a --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Resources/completion.fish @@ -0,0 +1,29 @@ +# This file is part of the Symfony package. +# +# (c) Fabien Potencier +# +# For the full copyright and license information, please view +# https://symfony.com/doc/current/contributing/code/license.html + +function _sf_{{ COMMAND_NAME }} + set sf_cmd (commandline -o) + set c (count (commandline -oc)) + + set completecmd "$sf_cmd[1]" "_complete" "--no-interaction" "-sfish" "-a{{ VERSION }}" + + for i in $sf_cmd + if [ $i != "" ] + set completecmd $completecmd "-i$i" + end + end + + set completecmd $completecmd "-c$c" + + set sfcomplete ($completecmd) + + for i in $sfcomplete + echo $i + end +end + +complete -c '{{ COMMAND_NAME }}' -a '(_sf_{{ COMMAND_NAME }})' -f diff --git a/tools/php-cs-fixer/vendor/symfony/console/Resources/completion.zsh b/tools/php-cs-fixer/vendor/symfony/console/Resources/completion.zsh new file mode 100644 index 00000000..ff76fe5f --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Resources/completion.zsh @@ -0,0 +1,82 @@ +#compdef {{ COMMAND_NAME }} + +# This file is part of the Symfony package. +# +# (c) Fabien Potencier +# +# For the full copyright and license information, please view +# https://symfony.com/doc/current/contributing/code/license.html + +# +# zsh completions for {{ COMMAND_NAME }} +# +# References: +# - https://github.com/spf13/cobra/blob/master/zsh_completions.go +# - https://github.com/symfony/symfony/blob/5.4/src/Symfony/Component/Console/Resources/completion.bash +# +_sf_{{ COMMAND_NAME }}() { + local lastParam flagPrefix requestComp out comp + local -a completions + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $CURRENT location, so we need + # to truncate the command-line ($words) up to the $CURRENT location. + # (We cannot use $CURSOR as its value does not work when a command is an alias.) + words=("${=words[1,CURRENT]}") lastParam=${words[-1]} + + # For zsh, when completing a flag with an = (e.g., {{ COMMAND_NAME }} -n=) + # completions must be prefixed with the flag + setopt local_options BASH_REMATCH + if [[ "${lastParam}" =~ '-.*=' ]]; then + # We are dealing with a flag with an = + flagPrefix="-P ${BASH_REMATCH}" + fi + + # Prepare the command to obtain completions + requestComp="${words[0]} ${words[1]} _complete --no-interaction -szsh -a{{ VERSION }} -c$((CURRENT-1))" i="" + for w in ${words[@]}; do + w=$(printf -- '%b' "$w") + # remove quotes from typed values + quote="${w:0:1}" + if [ "$quote" = \' ]; then + w="${w%\'}" + w="${w#\'}" + elif [ "$quote" = \" ]; then + w="${w%\"}" + w="${w#\"}" + fi + # empty values are ignored + if [ ! -z "$w" ]; then + i="${i}-i${w} " + fi + done + + # Ensure at least 1 input + if [ "${i}" = "" ]; then + requestComp="${requestComp} -i\" \"" + else + requestComp="${requestComp} ${i}" + fi + + # Use eval to handle any environment variables and such + out=$(eval ${requestComp} 2>/dev/null) + + while IFS='\n' read -r comp; do + if [ -n "$comp" ]; then + # If requested, completions are returned with a description. + # The description is preceded by a TAB character. + # For zsh's _describe, we need to use a : instead of a TAB. + # We first need to escape any : as part of the completion itself. + comp=${comp//:/\\:} + local tab=$(printf '\t') + comp=${comp//$tab/:} + completions+=${comp} + fi + done < <(printf "%s\n" "${out[@]}") + + # Let inbuilt _describe handle completions + eval _describe "completions" completions $flagPrefix + return $? +} + +compdef _sf_{{ COMMAND_NAME }} {{ COMMAND_NAME }} diff --git a/tools/php-cs-fixer/vendor/symfony/console/SignalRegistry/SignalMap.php b/tools/php-cs-fixer/vendor/symfony/console/SignalRegistry/SignalMap.php new file mode 100644 index 00000000..de419bda --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/SignalRegistry/SignalMap.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\SignalRegistry; + +/** + * @author Grégoire Pineau + */ +class SignalMap +{ + private static array $map; + + public static function getSignalName(int $signal): ?string + { + if (!\extension_loaded('pcntl')) { + return null; + } + + if (!isset(self::$map)) { + $r = new \ReflectionExtension('pcntl'); + $c = $r->getConstants(); + $map = array_filter($c, fn ($k) => str_starts_with($k, 'SIG') && !str_starts_with($k, 'SIG_'), \ARRAY_FILTER_USE_KEY); + self::$map = array_flip($map); + } + + return self::$map[$signal] ?? null; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/SignalRegistry/SignalRegistry.php b/tools/php-cs-fixer/vendor/symfony/console/SignalRegistry/SignalRegistry.php new file mode 100644 index 00000000..ef2e5f04 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/SignalRegistry/SignalRegistry.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\SignalRegistry; + +final class SignalRegistry +{ + private array $signalHandlers = []; + + public function __construct() + { + if (\function_exists('pcntl_async_signals')) { + pcntl_async_signals(true); + } + } + + public function register(int $signal, callable $signalHandler): void + { + if (!isset($this->signalHandlers[$signal])) { + $previousCallback = pcntl_signal_get_handler($signal); + + if (\is_callable($previousCallback)) { + $this->signalHandlers[$signal][] = $previousCallback; + } + } + + $this->signalHandlers[$signal][] = $signalHandler; + + pcntl_signal($signal, $this->handle(...)); + } + + public static function isSupported(): bool + { + return \function_exists('pcntl_signal'); + } + + /** + * @internal + */ + public function handle(int $signal): void + { + $count = \count($this->signalHandlers[$signal]); + + foreach ($this->signalHandlers[$signal] as $i => $signalHandler) { + $hasNext = $i !== $count - 1; + $signalHandler($signal, $hasNext); + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/SingleCommandApplication.php b/tools/php-cs-fixer/vendor/symfony/console/SingleCommandApplication.php new file mode 100644 index 00000000..4f0b5ba3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/SingleCommandApplication.php @@ -0,0 +1,72 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Grégoire Pineau + */ +class SingleCommandApplication extends Command +{ + private string $version = 'UNKNOWN'; + private bool $autoExit = true; + private bool $running = false; + + /** + * @return $this + */ + public function setVersion(string $version): static + { + $this->version = $version; + + return $this; + } + + /** + * @final + * + * @return $this + */ + public function setAutoExit(bool $autoExit): static + { + $this->autoExit = $autoExit; + + return $this; + } + + public function run(InputInterface $input = null, OutputInterface $output = null): int + { + if ($this->running) { + return parent::run($input, $output); + } + + // We use the command name as the application name + $application = new Application($this->getName() ?: 'UNKNOWN', $this->version); + $application->setAutoExit($this->autoExit); + // Fix the usage of the command displayed with "--help" + $this->setName($_SERVER['argv'][0]); + $application->add($this); + $application->setDefaultCommand($this->getName(), true); + + $this->running = true; + try { + $ret = $application->run($input, $output); + } finally { + $this->running = false; + } + + return $ret ?? 1; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Style/OutputStyle.php b/tools/php-cs-fixer/vendor/symfony/console/Style/OutputStyle.php new file mode 100644 index 00000000..05076c00 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Style/OutputStyle.php @@ -0,0 +1,111 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Style; + +use Symfony\Component\Console\Formatter\OutputFormatterInterface; +use Symfony\Component\Console\Helper\ProgressBar; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Decorates output to add console style guide helpers. + * + * @author Kevin Bond + */ +abstract class OutputStyle implements OutputInterface, StyleInterface +{ + private OutputInterface $output; + + public function __construct(OutputInterface $output) + { + $this->output = $output; + } + + public function newLine(int $count = 1): void + { + $this->output->write(str_repeat(\PHP_EOL, $count)); + } + + public function createProgressBar(int $max = 0): ProgressBar + { + return new ProgressBar($this->output, $max); + } + + public function write(string|iterable $messages, bool $newline = false, int $type = self::OUTPUT_NORMAL): void + { + $this->output->write($messages, $newline, $type); + } + + public function writeln(string|iterable $messages, int $type = self::OUTPUT_NORMAL): void + { + $this->output->writeln($messages, $type); + } + + public function setVerbosity(int $level): void + { + $this->output->setVerbosity($level); + } + + public function getVerbosity(): int + { + return $this->output->getVerbosity(); + } + + public function setDecorated(bool $decorated): void + { + $this->output->setDecorated($decorated); + } + + public function isDecorated(): bool + { + return $this->output->isDecorated(); + } + + public function setFormatter(OutputFormatterInterface $formatter): void + { + $this->output->setFormatter($formatter); + } + + public function getFormatter(): OutputFormatterInterface + { + return $this->output->getFormatter(); + } + + public function isQuiet(): bool + { + return $this->output->isQuiet(); + } + + public function isVerbose(): bool + { + return $this->output->isVerbose(); + } + + public function isVeryVerbose(): bool + { + return $this->output->isVeryVerbose(); + } + + public function isDebug(): bool + { + return $this->output->isDebug(); + } + + protected function getErrorOutput(): OutputInterface + { + if (!$this->output instanceof ConsoleOutputInterface) { + return $this->output; + } + + return $this->output->getErrorOutput(); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Style/StyleInterface.php b/tools/php-cs-fixer/vendor/symfony/console/Style/StyleInterface.php new file mode 100644 index 00000000..869b1609 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Style/StyleInterface.php @@ -0,0 +1,110 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Style; + +/** + * Output style helpers. + * + * @author Kevin Bond + */ +interface StyleInterface +{ + /** + * Formats a command title. + */ + public function title(string $message): void; + + /** + * Formats a section title. + */ + public function section(string $message): void; + + /** + * Formats a list. + */ + public function listing(array $elements): void; + + /** + * Formats informational text. + */ + public function text(string|array $message): void; + + /** + * Formats a success result bar. + */ + public function success(string|array $message): void; + + /** + * Formats an error result bar. + */ + public function error(string|array $message): void; + + /** + * Formats an warning result bar. + */ + public function warning(string|array $message): void; + + /** + * Formats a note admonition. + */ + public function note(string|array $message): void; + + /** + * Formats a caution admonition. + */ + public function caution(string|array $message): void; + + /** + * Formats a table. + */ + public function table(array $headers, array $rows): void; + + /** + * Asks a question. + */ + public function ask(string $question, string $default = null, callable $validator = null): mixed; + + /** + * Asks a question with the user input hidden. + */ + public function askHidden(string $question, callable $validator = null): mixed; + + /** + * Asks for confirmation. + */ + public function confirm(string $question, bool $default = true): bool; + + /** + * Asks a choice question. + */ + public function choice(string $question, array $choices, mixed $default = null): mixed; + + /** + * Add newline(s). + */ + public function newLine(int $count = 1): void; + + /** + * Starts the progress output. + */ + public function progressStart(int $max = 0): void; + + /** + * Advances the progress output X steps. + */ + public function progressAdvance(int $step = 1): void; + + /** + * Finishes the progress output. + */ + public function progressFinish(): void; +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Style/SymfonyStyle.php b/tools/php-cs-fixer/vendor/symfony/console/Style/SymfonyStyle.php new file mode 100644 index 00000000..0da5d698 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Style/SymfonyStyle.php @@ -0,0 +1,456 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Style; + +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\RuntimeException; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Helper\Helper; +use Symfony\Component\Console\Helper\OutputWrapper; +use Symfony\Component\Console\Helper\ProgressBar; +use Symfony\Component\Console\Helper\SymfonyQuestionHelper; +use Symfony\Component\Console\Helper\Table; +use Symfony\Component\Console\Helper\TableCell; +use Symfony\Component\Console\Helper\TableSeparator; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\ConsoleSectionOutput; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Output\TrimmedBufferOutput; +use Symfony\Component\Console\Question\ChoiceQuestion; +use Symfony\Component\Console\Question\ConfirmationQuestion; +use Symfony\Component\Console\Question\Question; +use Symfony\Component\Console\Terminal; + +/** + * Output decorator helpers for the Symfony Style Guide. + * + * @author Kevin Bond + */ +class SymfonyStyle extends OutputStyle +{ + public const MAX_LINE_LENGTH = 120; + + private InputInterface $input; + private OutputInterface $output; + private SymfonyQuestionHelper $questionHelper; + private ProgressBar $progressBar; + private int $lineLength; + private TrimmedBufferOutput $bufferedOutput; + + public function __construct(InputInterface $input, OutputInterface $output) + { + $this->input = $input; + $this->bufferedOutput = new TrimmedBufferOutput(\DIRECTORY_SEPARATOR === '\\' ? 4 : 2, $output->getVerbosity(), false, clone $output->getFormatter()); + // Windows cmd wraps lines as soon as the terminal width is reached, whether there are following chars or not. + $width = (new Terminal())->getWidth() ?: self::MAX_LINE_LENGTH; + $this->lineLength = min($width - (int) (\DIRECTORY_SEPARATOR === '\\'), self::MAX_LINE_LENGTH); + + parent::__construct($this->output = $output); + } + + /** + * Formats a message as a block of text. + */ + public function block(string|array $messages, string $type = null, string $style = null, string $prefix = ' ', bool $padding = false, bool $escape = true): void + { + $messages = \is_array($messages) ? array_values($messages) : [$messages]; + + $this->autoPrependBlock(); + $this->writeln($this->createBlock($messages, $type, $style, $prefix, $padding, $escape)); + $this->newLine(); + } + + public function title(string $message): void + { + $this->autoPrependBlock(); + $this->writeln([ + sprintf('%s', OutputFormatter::escapeTrailingBackslash($message)), + sprintf('%s', str_repeat('=', Helper::width(Helper::removeDecoration($this->getFormatter(), $message)))), + ]); + $this->newLine(); + } + + public function section(string $message): void + { + $this->autoPrependBlock(); + $this->writeln([ + sprintf('%s', OutputFormatter::escapeTrailingBackslash($message)), + sprintf('%s', str_repeat('-', Helper::width(Helper::removeDecoration($this->getFormatter(), $message)))), + ]); + $this->newLine(); + } + + public function listing(array $elements): void + { + $this->autoPrependText(); + $elements = array_map(fn ($element) => sprintf(' * %s', $element), $elements); + + $this->writeln($elements); + $this->newLine(); + } + + public function text(string|array $message): void + { + $this->autoPrependText(); + + $messages = \is_array($message) ? array_values($message) : [$message]; + foreach ($messages as $message) { + $this->writeln(sprintf(' %s', $message)); + } + } + + /** + * Formats a command comment. + */ + public function comment(string|array $message): void + { + $this->block($message, null, null, ' // ', false, false); + } + + public function success(string|array $message): void + { + $this->block($message, 'OK', 'fg=black;bg=green', ' ', true); + } + + public function error(string|array $message): void + { + $this->block($message, 'ERROR', 'fg=white;bg=red', ' ', true); + } + + public function warning(string|array $message): void + { + $this->block($message, 'WARNING', 'fg=black;bg=yellow', ' ', true); + } + + public function note(string|array $message): void + { + $this->block($message, 'NOTE', 'fg=yellow', ' ! '); + } + + /** + * Formats an info message. + */ + public function info(string|array $message): void + { + $this->block($message, 'INFO', 'fg=green', ' ', true); + } + + public function caution(string|array $message): void + { + $this->block($message, 'CAUTION', 'fg=white;bg=red', ' ! ', true); + } + + public function table(array $headers, array $rows): void + { + $this->createTable() + ->setHeaders($headers) + ->setRows($rows) + ->render() + ; + + $this->newLine(); + } + + /** + * Formats a horizontal table. + */ + public function horizontalTable(array $headers, array $rows): void + { + $this->createTable() + ->setHorizontal(true) + ->setHeaders($headers) + ->setRows($rows) + ->render() + ; + + $this->newLine(); + } + + /** + * Formats a list of key/value horizontally. + * + * Each row can be one of: + * * 'A title' + * * ['key' => 'value'] + * * new TableSeparator() + */ + public function definitionList(string|array|TableSeparator ...$list): void + { + $headers = []; + $row = []; + foreach ($list as $value) { + if ($value instanceof TableSeparator) { + $headers[] = $value; + $row[] = $value; + continue; + } + if (\is_string($value)) { + $headers[] = new TableCell($value, ['colspan' => 2]); + $row[] = null; + continue; + } + if (!\is_array($value)) { + throw new InvalidArgumentException('Value should be an array, string, or an instance of TableSeparator.'); + } + $headers[] = key($value); + $row[] = current($value); + } + + $this->horizontalTable($headers, [$row]); + } + + public function ask(string $question, string $default = null, callable $validator = null): mixed + { + $question = new Question($question, $default); + $question->setValidator($validator); + + return $this->askQuestion($question); + } + + public function askHidden(string $question, callable $validator = null): mixed + { + $question = new Question($question); + + $question->setHidden(true); + $question->setValidator($validator); + + return $this->askQuestion($question); + } + + public function confirm(string $question, bool $default = true): bool + { + return $this->askQuestion(new ConfirmationQuestion($question, $default)); + } + + public function choice(string $question, array $choices, mixed $default = null, bool $multiSelect = false): mixed + { + if (null !== $default) { + $values = array_flip($choices); + $default = $values[$default] ?? $default; + } + + $questionChoice = new ChoiceQuestion($question, $choices, $default); + $questionChoice->setMultiselect($multiSelect); + + return $this->askQuestion($questionChoice); + } + + public function progressStart(int $max = 0): void + { + $this->progressBar = $this->createProgressBar($max); + $this->progressBar->start(); + } + + public function progressAdvance(int $step = 1): void + { + $this->getProgressBar()->advance($step); + } + + public function progressFinish(): void + { + $this->getProgressBar()->finish(); + $this->newLine(2); + unset($this->progressBar); + } + + public function createProgressBar(int $max = 0): ProgressBar + { + $progressBar = parent::createProgressBar($max); + + if ('\\' !== \DIRECTORY_SEPARATOR || 'Hyper' === getenv('TERM_PROGRAM')) { + $progressBar->setEmptyBarCharacter('░'); // light shade character \u2591 + $progressBar->setProgressCharacter(''); + $progressBar->setBarCharacter('▓'); // dark shade character \u2593 + } + + return $progressBar; + } + + /** + * @see ProgressBar::iterate() + * + * @template TKey + * @template TValue + * + * @param iterable $iterable + * @param int|null $max Number of steps to complete the bar (0 if indeterminate), if null it will be inferred from $iterable + * + * @return iterable + */ + public function progressIterate(iterable $iterable, int $max = null): iterable + { + yield from $this->createProgressBar()->iterate($iterable, $max); + + $this->newLine(2); + } + + public function askQuestion(Question $question): mixed + { + if ($this->input->isInteractive()) { + $this->autoPrependBlock(); + } + + $this->questionHelper ??= new SymfonyQuestionHelper(); + + $answer = $this->questionHelper->ask($this->input, $this, $question); + + if ($this->input->isInteractive()) { + if ($this->output instanceof ConsoleSectionOutput) { + // add the new line of the `return` to submit the input to ConsoleSectionOutput, because ConsoleSectionOutput is holding all it's lines. + // this is relevant when a `ConsoleSectionOutput::clear` is called. + $this->output->addNewLineOfInputSubmit(); + } + $this->newLine(); + $this->bufferedOutput->write("\n"); + } + + return $answer; + } + + public function writeln(string|iterable $messages, int $type = self::OUTPUT_NORMAL): void + { + if (!is_iterable($messages)) { + $messages = [$messages]; + } + + foreach ($messages as $message) { + parent::writeln($message, $type); + $this->writeBuffer($message, true, $type); + } + } + + public function write(string|iterable $messages, bool $newline = false, int $type = self::OUTPUT_NORMAL): void + { + if (!is_iterable($messages)) { + $messages = [$messages]; + } + + foreach ($messages as $message) { + parent::write($message, $newline, $type); + $this->writeBuffer($message, $newline, $type); + } + } + + public function newLine(int $count = 1): void + { + parent::newLine($count); + $this->bufferedOutput->write(str_repeat("\n", $count)); + } + + /** + * Returns a new instance which makes use of stderr if available. + */ + public function getErrorStyle(): self + { + return new self($this->input, $this->getErrorOutput()); + } + + public function createTable(): Table + { + $output = $this->output instanceof ConsoleOutputInterface ? $this->output->section() : $this->output; + $style = clone Table::getStyleDefinition('symfony-style-guide'); + $style->setCellHeaderFormat('%s'); + + return (new Table($output))->setStyle($style); + } + + private function getProgressBar(): ProgressBar + { + return $this->progressBar + ?? throw new RuntimeException('The ProgressBar is not started.'); + } + + private function autoPrependBlock(): void + { + $chars = substr(str_replace(\PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2); + + if (!isset($chars[0])) { + $this->newLine(); // empty history, so we should start with a new line. + + return; + } + // Prepend new line for each non LF chars (This means no blank line was output before) + $this->newLine(2 - substr_count($chars, "\n")); + } + + private function autoPrependText(): void + { + $fetched = $this->bufferedOutput->fetch(); + // Prepend new line if last char isn't EOL: + if ($fetched && !str_ends_with($fetched, "\n")) { + $this->newLine(); + } + } + + private function writeBuffer(string $message, bool $newLine, int $type): void + { + // We need to know if the last chars are PHP_EOL + $this->bufferedOutput->write($message, $newLine, $type); + } + + private function createBlock(iterable $messages, string $type = null, string $style = null, string $prefix = ' ', bool $padding = false, bool $escape = false): array + { + $indentLength = 0; + $prefixLength = Helper::width(Helper::removeDecoration($this->getFormatter(), $prefix)); + $lines = []; + + if (null !== $type) { + $type = sprintf('[%s] ', $type); + $indentLength = Helper::width($type); + $lineIndentation = str_repeat(' ', $indentLength); + } + + // wrap and add newlines for each element + $outputWrapper = new OutputWrapper(); + foreach ($messages as $key => $message) { + if ($escape) { + $message = OutputFormatter::escape($message); + } + + $lines = array_merge( + $lines, + explode(\PHP_EOL, $outputWrapper->wrap( + $message, + $this->lineLength - $prefixLength - $indentLength, + \PHP_EOL + )) + ); + + if (\count($messages) > 1 && $key < \count($messages) - 1) { + $lines[] = ''; + } + } + + $firstLineIndex = 0; + if ($padding && $this->isDecorated()) { + $firstLineIndex = 1; + array_unshift($lines, ''); + $lines[] = ''; + } + + foreach ($lines as $i => &$line) { + if (null !== $type) { + $line = $firstLineIndex === $i ? $type.$line : $lineIndentation.$line; + } + + $line = $prefix.$line; + $line .= str_repeat(' ', max($this->lineLength - Helper::width(Helper::removeDecoration($this->getFormatter(), $line)), 0)); + + if ($style) { + $line = sprintf('<%s>%s', $style, $line); + } + } + + return $lines; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Terminal.php b/tools/php-cs-fixer/vendor/symfony/console/Terminal.php new file mode 100644 index 00000000..3eda0376 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Terminal.php @@ -0,0 +1,236 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console; + +use Symfony\Component\Console\Output\AnsiColorMode; + +class Terminal +{ + public const DEFAULT_COLOR_MODE = AnsiColorMode::Ansi4; + + private static ?AnsiColorMode $colorMode = null; + private static ?int $width = null; + private static ?int $height = null; + private static ?bool $stty = null; + + /** + * About Ansi color types: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors + * For more information about true color support with terminals https://github.com/termstandard/colors/. + */ + public static function getColorMode(): AnsiColorMode + { + // Use Cache from previous run (or user forced mode) + if (null !== self::$colorMode) { + return self::$colorMode; + } + + // Try with $COLORTERM first + if (\is_string($colorterm = getenv('COLORTERM'))) { + $colorterm = strtolower($colorterm); + + if (str_contains($colorterm, 'truecolor')) { + self::setColorMode(AnsiColorMode::Ansi24); + + return self::$colorMode; + } + + if (str_contains($colorterm, '256color')) { + self::setColorMode(AnsiColorMode::Ansi8); + + return self::$colorMode; + } + } + + // Try with $TERM + if (\is_string($term = getenv('TERM'))) { + $term = strtolower($term); + + if (str_contains($term, 'truecolor')) { + self::setColorMode(AnsiColorMode::Ansi24); + + return self::$colorMode; + } + + if (str_contains($term, '256color')) { + self::setColorMode(AnsiColorMode::Ansi8); + + return self::$colorMode; + } + } + + self::setColorMode(self::DEFAULT_COLOR_MODE); + + return self::$colorMode; + } + + /** + * Force a terminal color mode rendering. + */ + public static function setColorMode(?AnsiColorMode $colorMode): void + { + self::$colorMode = $colorMode; + } + + /** + * Gets the terminal width. + */ + public function getWidth(): int + { + $width = getenv('COLUMNS'); + if (false !== $width) { + return (int) trim($width); + } + + if (null === self::$width) { + self::initDimensions(); + } + + return self::$width ?: 80; + } + + /** + * Gets the terminal height. + */ + public function getHeight(): int + { + $height = getenv('LINES'); + if (false !== $height) { + return (int) trim($height); + } + + if (null === self::$height) { + self::initDimensions(); + } + + return self::$height ?: 50; + } + + /** + * @internal + */ + public static function hasSttyAvailable(): bool + { + if (null !== self::$stty) { + return self::$stty; + } + + // skip check if shell_exec function is disabled + if (!\function_exists('shell_exec')) { + return false; + } + + return self::$stty = (bool) shell_exec('stty 2> '.('\\' === \DIRECTORY_SEPARATOR ? 'NUL' : '/dev/null')); + } + + private static function initDimensions(): void + { + if ('\\' === \DIRECTORY_SEPARATOR) { + $ansicon = getenv('ANSICON'); + if (false !== $ansicon && preg_match('/^(\d+)x(\d+)(?: \((\d+)x(\d+)\))?$/', trim($ansicon), $matches)) { + // extract [w, H] from "wxh (WxH)" + // or [w, h] from "wxh" + self::$width = (int) $matches[1]; + self::$height = isset($matches[4]) ? (int) $matches[4] : (int) $matches[2]; + } elseif (!self::hasVt100Support() && self::hasSttyAvailable()) { + // only use stty on Windows if the terminal does not support vt100 (e.g. Windows 7 + git-bash) + // testing for stty in a Windows 10 vt100-enabled console will implicitly disable vt100 support on STDOUT + self::initDimensionsUsingStty(); + } elseif (null !== $dimensions = self::getConsoleMode()) { + // extract [w, h] from "wxh" + self::$width = (int) $dimensions[0]; + self::$height = (int) $dimensions[1]; + } + } else { + self::initDimensionsUsingStty(); + } + } + + /** + * Returns whether STDOUT has vt100 support (some Windows 10+ configurations). + */ + private static function hasVt100Support(): bool + { + return \function_exists('sapi_windows_vt100_support') && sapi_windows_vt100_support(fopen('php://stdout', 'w')); + } + + /** + * Initializes dimensions using the output of an stty columns line. + */ + private static function initDimensionsUsingStty(): void + { + if ($sttyString = self::getSttyColumns()) { + if (preg_match('/rows.(\d+);.columns.(\d+);/is', $sttyString, $matches)) { + // extract [w, h] from "rows h; columns w;" + self::$width = (int) $matches[2]; + self::$height = (int) $matches[1]; + } elseif (preg_match('/;.(\d+).rows;.(\d+).columns/is', $sttyString, $matches)) { + // extract [w, h] from "; h rows; w columns" + self::$width = (int) $matches[2]; + self::$height = (int) $matches[1]; + } + } + } + + /** + * Runs and parses mode CON if it's available, suppressing any error output. + * + * @return int[]|null An array composed of the width and the height or null if it could not be parsed + */ + private static function getConsoleMode(): ?array + { + $info = self::readFromProcess('mode CON'); + + if (null === $info || !preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $matches)) { + return null; + } + + return [(int) $matches[2], (int) $matches[1]]; + } + + /** + * Runs and parses stty -a if it's available, suppressing any error output. + */ + private static function getSttyColumns(): ?string + { + return self::readFromProcess(['stty', '-a']); + } + + private static function readFromProcess(string|array $command): ?string + { + if (!\function_exists('proc_open')) { + return null; + } + + $descriptorspec = [ + 1 => ['pipe', 'w'], + 2 => ['pipe', 'w'], + ]; + + $cp = \function_exists('sapi_windows_cp_set') ? sapi_windows_cp_get() : 0; + + $process = proc_open($command, $descriptorspec, $pipes, null, null, ['suppress_errors' => true]); + if (!\is_resource($process)) { + return null; + } + + $info = stream_get_contents($pipes[1]); + fclose($pipes[1]); + fclose($pipes[2]); + proc_close($process); + + if ($cp) { + sapi_windows_cp_set($cp); + } + + return $info; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Tester/ApplicationTester.php b/tools/php-cs-fixer/vendor/symfony/console/Tester/ApplicationTester.php new file mode 100644 index 00000000..58aee54d --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Tester/ApplicationTester.php @@ -0,0 +1,85 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Tester; + +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Input\ArrayInput; + +/** + * Eases the testing of console applications. + * + * When testing an application, don't forget to disable the auto exit flag: + * + * $application = new Application(); + * $application->setAutoExit(false); + * + * @author Fabien Potencier + */ +class ApplicationTester +{ + use TesterTrait; + + private Application $application; + + public function __construct(Application $application) + { + $this->application = $application; + } + + /** + * Executes the application. + * + * Available options: + * + * * interactive: Sets the input interactive flag + * * decorated: Sets the output decorated flag + * * verbosity: Sets the output verbosity flag + * * capture_stderr_separately: Make output of stdOut and stdErr separately available + * + * @return int The command exit code + */ + public function run(array $input, array $options = []): int + { + $prevShellVerbosity = getenv('SHELL_VERBOSITY'); + + try { + $this->input = new ArrayInput($input); + if (isset($options['interactive'])) { + $this->input->setInteractive($options['interactive']); + } + + if ($this->inputs) { + $this->input->setStream(self::createStream($this->inputs)); + } + + $this->initOutput($options); + + return $this->statusCode = $this->application->run($this->input, $this->output); + } finally { + // SHELL_VERBOSITY is set by Application::configureIO so we need to unset/reset it + // to its previous value to avoid one test's verbosity to spread to the following tests + if (false === $prevShellVerbosity) { + if (\function_exists('putenv')) { + @putenv('SHELL_VERBOSITY'); + } + unset($_ENV['SHELL_VERBOSITY']); + unset($_SERVER['SHELL_VERBOSITY']); + } else { + if (\function_exists('putenv')) { + @putenv('SHELL_VERBOSITY='.$prevShellVerbosity); + } + $_ENV['SHELL_VERBOSITY'] = $prevShellVerbosity; + $_SERVER['SHELL_VERBOSITY'] = $prevShellVerbosity; + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Tester/CommandCompletionTester.php b/tools/php-cs-fixer/vendor/symfony/console/Tester/CommandCompletionTester.php new file mode 100644 index 00000000..a90fe52e --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Tester/CommandCompletionTester.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Tester; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; + +/** + * Eases the testing of command completion. + * + * @author Jérôme Tamarelle + */ +class CommandCompletionTester +{ + private Command $command; + + public function __construct(Command $command) + { + $this->command = $command; + } + + /** + * Create completion suggestions from input tokens. + */ + public function complete(array $input): array + { + $currentIndex = \count($input); + if ('' === end($input)) { + array_pop($input); + } + array_unshift($input, $this->command->getName()); + + $completionInput = CompletionInput::fromTokens($input, $currentIndex); + $completionInput->bind($this->command->getDefinition()); + $suggestions = new CompletionSuggestions(); + + $this->command->complete($completionInput, $suggestions); + + $options = []; + foreach ($suggestions->getOptionSuggestions() as $option) { + $options[] = '--'.$option->getName(); + } + + return array_map('strval', array_merge($options, $suggestions->getValueSuggestions())); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Tester/CommandTester.php b/tools/php-cs-fixer/vendor/symfony/console/Tester/CommandTester.php new file mode 100644 index 00000000..2ff813b7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Tester/CommandTester.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Tester; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\ArrayInput; + +/** + * Eases the testing of console commands. + * + * @author Fabien Potencier + * @author Robin Chalas + */ +class CommandTester +{ + use TesterTrait; + + private Command $command; + + public function __construct(Command $command) + { + $this->command = $command; + } + + /** + * Executes the command. + * + * Available execution options: + * + * * interactive: Sets the input interactive flag + * * decorated: Sets the output decorated flag + * * verbosity: Sets the output verbosity flag + * * capture_stderr_separately: Make output of stdOut and stdErr separately available + * + * @param array $input An array of command arguments and options + * @param array $options An array of execution options + * + * @return int The command exit code + */ + public function execute(array $input, array $options = []): int + { + // set the command name automatically if the application requires + // this argument and no command name was passed + if (!isset($input['command']) + && (null !== $application = $this->command->getApplication()) + && $application->getDefinition()->hasArgument('command') + ) { + $input = array_merge(['command' => $this->command->getName()], $input); + } + + $this->input = new ArrayInput($input); + // Use an in-memory input stream even if no inputs are set so that QuestionHelper::ask() does not rely on the blocking STDIN. + $this->input->setStream(self::createStream($this->inputs)); + + if (isset($options['interactive'])) { + $this->input->setInteractive($options['interactive']); + } + + if (!isset($options['decorated'])) { + $options['decorated'] = false; + } + + $this->initOutput($options); + + return $this->statusCode = $this->command->run($this->input, $this->output); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Tester/Constraint/CommandIsSuccessful.php b/tools/php-cs-fixer/vendor/symfony/console/Tester/Constraint/CommandIsSuccessful.php new file mode 100644 index 00000000..09c6194b --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Tester/Constraint/CommandIsSuccessful.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Tester\Constraint; + +use PHPUnit\Framework\Constraint\Constraint; +use Symfony\Component\Console\Command\Command; + +final class CommandIsSuccessful extends Constraint +{ + public function toString(): string + { + return 'is successful'; + } + + protected function matches($other): bool + { + return Command::SUCCESS === $other; + } + + protected function failureDescription($other): string + { + return 'the command '.$this->toString(); + } + + protected function additionalFailureDescription($other): string + { + $mapping = [ + Command::FAILURE => 'Command failed.', + Command::INVALID => 'Command was invalid.', + ]; + + return $mapping[$other] ?? sprintf('Command returned exit status %d.', $other); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/Tester/TesterTrait.php b/tools/php-cs-fixer/vendor/symfony/console/Tester/TesterTrait.php new file mode 100644 index 00000000..1ab7a70a --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/Tester/TesterTrait.php @@ -0,0 +1,178 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Tester; + +use PHPUnit\Framework\Assert; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\ConsoleOutput; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Output\StreamOutput; +use Symfony\Component\Console\Tester\Constraint\CommandIsSuccessful; + +/** + * @author Amrouche Hamza + */ +trait TesterTrait +{ + private StreamOutput $output; + private array $inputs = []; + private bool $captureStreamsIndependently = false; + private InputInterface $input; + private int $statusCode; + + /** + * Gets the display returned by the last execution of the command or application. + * + * @throws \RuntimeException If it's called before the execute method + */ + public function getDisplay(bool $normalize = false): string + { + if (!isset($this->output)) { + throw new \RuntimeException('Output not initialized, did you execute the command before requesting the display?'); + } + + rewind($this->output->getStream()); + + $display = stream_get_contents($this->output->getStream()); + + if ($normalize) { + $display = str_replace(\PHP_EOL, "\n", $display); + } + + return $display; + } + + /** + * Gets the output written to STDERR by the application. + * + * @param bool $normalize Whether to normalize end of lines to \n or not + */ + public function getErrorOutput(bool $normalize = false): string + { + if (!$this->captureStreamsIndependently) { + throw new \LogicException('The error output is not available when the tester is run without "capture_stderr_separately" option set.'); + } + + rewind($this->output->getErrorOutput()->getStream()); + + $display = stream_get_contents($this->output->getErrorOutput()->getStream()); + + if ($normalize) { + $display = str_replace(\PHP_EOL, "\n", $display); + } + + return $display; + } + + /** + * Gets the input instance used by the last execution of the command or application. + */ + public function getInput(): InputInterface + { + return $this->input; + } + + /** + * Gets the output instance used by the last execution of the command or application. + */ + public function getOutput(): OutputInterface + { + return $this->output; + } + + /** + * Gets the status code returned by the last execution of the command or application. + * + * @throws \RuntimeException If it's called before the execute method + */ + public function getStatusCode(): int + { + return $this->statusCode ?? throw new \RuntimeException('Status code not initialized, did you execute the command before requesting the status code?'); + } + + public function assertCommandIsSuccessful(string $message = ''): void + { + Assert::assertThat($this->statusCode, new CommandIsSuccessful(), $message); + } + + /** + * Sets the user inputs. + * + * @param array $inputs An array of strings representing each input + * passed to the command input stream + * + * @return $this + */ + public function setInputs(array $inputs): static + { + $this->inputs = $inputs; + + return $this; + } + + /** + * Initializes the output property. + * + * Available options: + * + * * decorated: Sets the output decorated flag + * * verbosity: Sets the output verbosity flag + * * capture_stderr_separately: Make output of stdOut and stdErr separately available + */ + private function initOutput(array $options): void + { + $this->captureStreamsIndependently = $options['capture_stderr_separately'] ?? false; + if (!$this->captureStreamsIndependently) { + $this->output = new StreamOutput(fopen('php://memory', 'w', false)); + if (isset($options['decorated'])) { + $this->output->setDecorated($options['decorated']); + } + if (isset($options['verbosity'])) { + $this->output->setVerbosity($options['verbosity']); + } + } else { + $this->output = new ConsoleOutput( + $options['verbosity'] ?? ConsoleOutput::VERBOSITY_NORMAL, + $options['decorated'] ?? null + ); + + $errorOutput = new StreamOutput(fopen('php://memory', 'w', false)); + $errorOutput->setFormatter($this->output->getFormatter()); + $errorOutput->setVerbosity($this->output->getVerbosity()); + $errorOutput->setDecorated($this->output->isDecorated()); + + $reflectedOutput = new \ReflectionObject($this->output); + $strErrProperty = $reflectedOutput->getProperty('stderr'); + $strErrProperty->setValue($this->output, $errorOutput); + + $reflectedParent = $reflectedOutput->getParentClass(); + $streamProperty = $reflectedParent->getProperty('stream'); + $streamProperty->setValue($this->output, fopen('php://memory', 'w', false)); + } + } + + /** + * @return resource + */ + private static function createStream(array $inputs) + { + $stream = fopen('php://memory', 'r+', false); + + foreach ($inputs as $input) { + fwrite($stream, $input.\PHP_EOL); + } + + rewind($stream); + + return $stream; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/console/composer.json b/tools/php-cs-fixer/vendor/symfony/console/composer.json new file mode 100644 index 00000000..0ed1bd9a --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/console/composer.json @@ -0,0 +1,54 @@ +{ + "name": "symfony/console", + "type": "library", + "description": "Eases the creation of beautiful and testable command line interfaces", + "keywords": ["console", "cli", "command-line", "terminal"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.2", + "symfony/polyfill-mbstring": "~1.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/string": "^6.4|^7.0" + }, + "require-dev": { + "symfony/config": "^6.4|^7.0", + "symfony/event-dispatcher": "^6.4|^7.0", + "symfony/http-foundation": "^6.4|^7.0", + "symfony/http-kernel": "^6.4|^7.0", + "symfony/dependency-injection": "^6.4|^7.0", + "symfony/lock": "^6.4|^7.0", + "symfony/messenger": "^6.4|^7.0", + "symfony/process": "^6.4|^7.0", + "symfony/stopwatch": "^6.4|^7.0", + "symfony/var-dumper": "^6.4|^7.0", + "psr/log": "^1|^2|^3" + }, + "provide": { + "psr/log-implementation": "1.0|2.0|3.0" + }, + "conflict": { + "symfony/dependency-injection": "<6.4", + "symfony/dotenv": "<6.4", + "symfony/event-dispatcher": "<6.4", + "symfony/lock": "<6.4", + "symfony/process": "<6.4" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\Console\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/tools/php-cs-fixer/vendor/symfony/deprecation-contracts/CHANGELOG.md b/tools/php-cs-fixer/vendor/symfony/deprecation-contracts/CHANGELOG.md new file mode 100644 index 00000000..7932e261 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/deprecation-contracts/CHANGELOG.md @@ -0,0 +1,5 @@ +CHANGELOG +========= + +The changelog is maintained for all Symfony contracts at the following URL: +https://github.com/symfony/contracts/blob/main/CHANGELOG.md diff --git a/tools/php-cs-fixer/vendor/symfony/deprecation-contracts/LICENSE b/tools/php-cs-fixer/vendor/symfony/deprecation-contracts/LICENSE new file mode 100644 index 00000000..0ed3a246 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/deprecation-contracts/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2020-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/deprecation-contracts/README.md b/tools/php-cs-fixer/vendor/symfony/deprecation-contracts/README.md new file mode 100644 index 00000000..9814864c --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/deprecation-contracts/README.md @@ -0,0 +1,26 @@ +Symfony Deprecation Contracts +============================= + +A generic function and convention to trigger deprecation notices. + +This package provides a single global function named `trigger_deprecation()` that triggers silenced deprecation notices. + +By using a custom PHP error handler such as the one provided by the Symfony ErrorHandler component, +the triggered deprecations can be caught and logged for later discovery, both on dev and prod environments. + +The function requires at least 3 arguments: + - the name of the Composer package that is triggering the deprecation + - the version of the package that introduced the deprecation + - the message of the deprecation + - more arguments can be provided: they will be inserted in the message using `printf()` formatting + +Example: +```php +trigger_deprecation('symfony/blockchain', '8.9', 'Using "%s" is deprecated, use "%s" instead.', 'bitcoin', 'fabcoin'); +``` + +This will generate the following message: +`Since symfony/blockchain 8.9: Using "bitcoin" is deprecated, use "fabcoin" instead.` + +While not recommended, the deprecation notices can be completely ignored by declaring an empty +`function trigger_deprecation() {}` in your application. diff --git a/tools/php-cs-fixer/vendor/symfony/deprecation-contracts/composer.json b/tools/php-cs-fixer/vendor/symfony/deprecation-contracts/composer.json new file mode 100644 index 00000000..c6d02d87 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/deprecation-contracts/composer.json @@ -0,0 +1,35 @@ +{ + "name": "symfony/deprecation-contracts", + "type": "library", + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.1" + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/deprecation-contracts/function.php b/tools/php-cs-fixer/vendor/symfony/deprecation-contracts/function.php new file mode 100644 index 00000000..2d56512b --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/deprecation-contracts/function.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (!function_exists('trigger_deprecation')) { + /** + * Triggers a silenced deprecation notice. + * + * @param string $package The name of the Composer package that is triggering the deprecation + * @param string $version The version of the package that introduced the deprecation + * @param string $message The message of the deprecation + * @param mixed ...$args Values to insert in the message using printf() formatting + * + * @author Nicolas Grekas + */ + function trigger_deprecation(string $package, string $version, string $message, mixed ...$args): void + { + @trigger_error(($package || $version ? "Since $package $version: " : '').($args ? vsprintf($message, $args) : $message), \E_USER_DEPRECATED); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/CHANGELOG.md b/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/CHANGELOG.md new file mode 100644 index 00000000..7932e261 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/CHANGELOG.md @@ -0,0 +1,5 @@ +CHANGELOG +========= + +The changelog is maintained for all Symfony contracts at the following URL: +https://github.com/symfony/contracts/blob/main/CHANGELOG.md diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/Event.php b/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/Event.php new file mode 100644 index 00000000..2e7f9989 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/Event.php @@ -0,0 +1,51 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\EventDispatcher; + +use Psr\EventDispatcher\StoppableEventInterface; + +/** + * Event is the base class for classes containing event data. + * + * This class contains no event data. It is used by events that do not pass + * state information to an event handler when an event is raised. + * + * You can call the method stopPropagation() to abort the execution of + * further listeners in your event listener. + * + * @author Guilherme Blanco + * @author Jonathan Wage + * @author Roman Borschel + * @author Bernhard Schussek + * @author Nicolas Grekas + */ +class Event implements StoppableEventInterface +{ + private bool $propagationStopped = false; + + public function isPropagationStopped(): bool + { + return $this->propagationStopped; + } + + /** + * Stops the propagation of the event to further event listeners. + * + * If multiple event listeners are connected to the same event, no + * further event listener will be triggered once any trigger calls + * stopPropagation(). + */ + public function stopPropagation(): void + { + $this->propagationStopped = true; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/EventDispatcherInterface.php b/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/EventDispatcherInterface.php new file mode 100644 index 00000000..610d6ac0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/EventDispatcherInterface.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\EventDispatcher; + +use Psr\EventDispatcher\EventDispatcherInterface as PsrEventDispatcherInterface; + +/** + * Allows providing hooks on domain-specific lifecycles by dispatching events. + */ +interface EventDispatcherInterface extends PsrEventDispatcherInterface +{ + /** + * Dispatches an event to all registered listeners. + * + * @template T of object + * + * @param T $event The event to pass to the event handlers/listeners + * @param string|null $eventName The name of the event to dispatch. If not supplied, + * the class of $event should be used instead. + * + * @return T The passed $event MUST be returned + */ + public function dispatch(object $event, string $eventName = null): object; +} diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/LICENSE b/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/LICENSE new file mode 100644 index 00000000..7536caea --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2018-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/README.md b/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/README.md new file mode 100644 index 00000000..332b961c --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/README.md @@ -0,0 +1,9 @@ +Symfony EventDispatcher Contracts +================================= + +A set of abstractions extracted out of the Symfony components. + +Can be used to build on semantics that the Symfony components proved useful and +that already have battle tested implementations. + +See https://github.com/symfony/contracts/blob/main/README.md for more information. diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/composer.json b/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/composer.json new file mode 100644 index 00000000..3618d53e --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher-contracts/composer.json @@ -0,0 +1,35 @@ +{ + "name": "symfony/event-dispatcher-contracts", + "type": "library", + "description": "Generic abstractions related to dispatching event", + "keywords": ["abstractions", "contracts", "decoupling", "interfaces", "interoperability", "standards"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.1", + "psr/event-dispatcher": "^1" + }, + "autoload": { + "psr-4": { "Symfony\\Contracts\\EventDispatcher\\": "" } + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher/Attribute/AsEventListener.php b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/Attribute/AsEventListener.php new file mode 100644 index 00000000..bb931b82 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/Attribute/AsEventListener.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Attribute; + +/** + * Service tag to autoconfigure event listeners. + * + * @author Alexander M. Turek + */ +#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] +class AsEventListener +{ + public function __construct( + public ?string $event = null, + public ?string $method = null, + public int $priority = 0, + public ?string $dispatcher = null, + ) { + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher/CHANGELOG.md b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/CHANGELOG.md new file mode 100644 index 00000000..76b2eab6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/CHANGELOG.md @@ -0,0 +1,96 @@ +CHANGELOG +========= + +6.0 +--- + + * Remove `LegacyEventDispatcherProxy` + +5.4 +--- + + * Allow `#[AsEventListener]` attribute on methods + +5.3 +--- + + * Add `#[AsEventListener]` attribute for declaring listeners on PHP 8 + +5.1.0 +----- + + * The `LegacyEventDispatcherProxy` class has been deprecated. + * Added an optional `dispatcher` attribute to the listener and subscriber tags in `RegisterListenerPass`. + +5.0.0 +----- + + * The signature of the `EventDispatcherInterface::dispatch()` method has been changed to `dispatch($event, string $eventName = null): object`. + * The `Event` class has been removed in favor of `Symfony\Contracts\EventDispatcher\Event`. + * The `TraceableEventDispatcherInterface` has been removed. + * The `WrappedListener` class is now final. + +4.4.0 +----- + + * `AddEventAliasesPass` has been added, allowing applications and bundles to extend the event alias mapping used by `RegisterListenersPass`. + * Made the `event` attribute of the `kernel.event_listener` tag optional for FQCN events. + +4.3.0 +----- + + * The signature of the `EventDispatcherInterface::dispatch()` method should be updated to `dispatch($event, string $eventName = null)`, not doing so is deprecated + * deprecated the `Event` class, use `Symfony\Contracts\EventDispatcher\Event` instead + +4.1.0 +----- + + * added support for invokable event listeners tagged with `kernel.event_listener` by default + * The `TraceableEventDispatcher::getOrphanedEvents()` method has been added. + * The `TraceableEventDispatcherInterface` has been deprecated. + +4.0.0 +----- + + * removed the `ContainerAwareEventDispatcher` class + * added the `reset()` method to the `TraceableEventDispatcherInterface` + +3.4.0 +----- + + * Implementing `TraceableEventDispatcherInterface` without the `reset()` method has been deprecated. + +3.3.0 +----- + + * The ContainerAwareEventDispatcher class has been deprecated. Use EventDispatcher with closure factories instead. + +3.0.0 +----- + + * The method `getListenerPriority($eventName, $listener)` has been added to the + `EventDispatcherInterface`. + * The methods `Event::setDispatcher()`, `Event::getDispatcher()`, `Event::setName()` + and `Event::getName()` have been removed. + The event dispatcher and the event name are passed to the listener call. + +2.5.0 +----- + + * added Debug\TraceableEventDispatcher (originally in HttpKernel) + * changed Debug\TraceableEventDispatcherInterface to extend EventDispatcherInterface + * added RegisterListenersPass (originally in HttpKernel) + +2.1.0 +----- + + * added TraceableEventDispatcherInterface + * added ContainerAwareEventDispatcher + * added a reference to the EventDispatcher on the Event + * added a reference to the Event name on the event + * added fluid interface to the dispatch() method which now returns the Event + object + * added GenericEvent event class + * added the possibility for subscribers to subscribe several times for the + same event + * added ImmutableEventDispatcher diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php new file mode 100644 index 00000000..1163e070 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php @@ -0,0 +1,356 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Debug; + +use Psr\EventDispatcher\StoppableEventInterface; +use Psr\Log\LoggerInterface; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\Stopwatch\Stopwatch; +use Symfony\Contracts\Service\ResetInterface; + +/** + * Collects some data about event listeners. + * + * This event dispatcher delegates the dispatching to another one. + * + * @author Fabien Potencier + */ +class TraceableEventDispatcher implements EventDispatcherInterface, ResetInterface +{ + protected ?LoggerInterface $logger; + protected Stopwatch $stopwatch; + + /** + * @var \SplObjectStorage|null + */ + private ?\SplObjectStorage $callStack = null; + private EventDispatcherInterface $dispatcher; + private array $wrappedListeners = []; + private array $orphanedEvents = []; + private ?RequestStack $requestStack; + private string $currentRequestHash = ''; + + public function __construct(EventDispatcherInterface $dispatcher, Stopwatch $stopwatch, LoggerInterface $logger = null, RequestStack $requestStack = null) + { + $this->dispatcher = $dispatcher; + $this->stopwatch = $stopwatch; + $this->logger = $logger; + $this->requestStack = $requestStack; + } + + public function addListener(string $eventName, callable|array $listener, int $priority = 0): void + { + $this->dispatcher->addListener($eventName, $listener, $priority); + } + + public function addSubscriber(EventSubscriberInterface $subscriber): void + { + $this->dispatcher->addSubscriber($subscriber); + } + + public function removeListener(string $eventName, callable|array $listener): void + { + if (isset($this->wrappedListeners[$eventName])) { + foreach ($this->wrappedListeners[$eventName] as $index => $wrappedListener) { + if ($wrappedListener->getWrappedListener() === $listener || ($listener instanceof \Closure && $wrappedListener->getWrappedListener() == $listener)) { + $listener = $wrappedListener; + unset($this->wrappedListeners[$eventName][$index]); + break; + } + } + } + + $this->dispatcher->removeListener($eventName, $listener); + } + + public function removeSubscriber(EventSubscriberInterface $subscriber): void + { + $this->dispatcher->removeSubscriber($subscriber); + } + + public function getListeners(string $eventName = null): array + { + return $this->dispatcher->getListeners($eventName); + } + + public function getListenerPriority(string $eventName, callable|array $listener): ?int + { + // we might have wrapped listeners for the event (if called while dispatching) + // in that case get the priority by wrapper + if (isset($this->wrappedListeners[$eventName])) { + foreach ($this->wrappedListeners[$eventName] as $wrappedListener) { + if ($wrappedListener->getWrappedListener() === $listener || ($listener instanceof \Closure && $wrappedListener->getWrappedListener() == $listener)) { + return $this->dispatcher->getListenerPriority($eventName, $wrappedListener); + } + } + } + + return $this->dispatcher->getListenerPriority($eventName, $listener); + } + + public function hasListeners(string $eventName = null): bool + { + return $this->dispatcher->hasListeners($eventName); + } + + public function dispatch(object $event, string $eventName = null): object + { + $eventName ??= $event::class; + + $this->callStack ??= new \SplObjectStorage(); + + $currentRequestHash = $this->currentRequestHash = $this->requestStack && ($request = $this->requestStack->getCurrentRequest()) ? spl_object_hash($request) : ''; + + if (null !== $this->logger && $event instanceof StoppableEventInterface && $event->isPropagationStopped()) { + $this->logger->debug(sprintf('The "%s" event is already stopped. No listeners have been called.', $eventName)); + } + + $this->preProcess($eventName); + try { + $this->beforeDispatch($eventName, $event); + try { + $e = $this->stopwatch->start($eventName, 'section'); + try { + $this->dispatcher->dispatch($event, $eventName); + } finally { + if ($e->isStarted()) { + $e->stop(); + } + } + } finally { + $this->afterDispatch($eventName, $event); + } + } finally { + $this->currentRequestHash = $currentRequestHash; + $this->postProcess($eventName); + } + + return $event; + } + + public function getCalledListeners(Request $request = null): array + { + if (null === $this->callStack) { + return []; + } + + $hash = $request ? spl_object_hash($request) : null; + $called = []; + foreach ($this->callStack as $listener) { + [$eventName, $requestHash] = $this->callStack->getInfo(); + if (null === $hash || $hash === $requestHash) { + $called[] = $listener->getInfo($eventName); + } + } + + return $called; + } + + public function getNotCalledListeners(Request $request = null): array + { + try { + $allListeners = $this->dispatcher instanceof EventDispatcher ? $this->getListenersWithPriority() : $this->getListenersWithoutPriority(); + } catch (\Exception $e) { + $this->logger?->info('An exception was thrown while getting the uncalled listeners.', ['exception' => $e]); + + // unable to retrieve the uncalled listeners + return []; + } + + $hash = $request ? spl_object_hash($request) : null; + $calledListeners = []; + + if (null !== $this->callStack) { + foreach ($this->callStack as $calledListener) { + [, $requestHash] = $this->callStack->getInfo(); + + if (null === $hash || $hash === $requestHash) { + $calledListeners[] = $calledListener->getWrappedListener(); + } + } + } + + $notCalled = []; + + foreach ($allListeners as $eventName => $listeners) { + foreach ($listeners as [$listener, $priority]) { + if (!\in_array($listener, $calledListeners, true)) { + if (!$listener instanceof WrappedListener) { + $listener = new WrappedListener($listener, null, $this->stopwatch, $this, $priority); + } + $notCalled[] = $listener->getInfo($eventName); + } + } + } + + uasort($notCalled, $this->sortNotCalledListeners(...)); + + return $notCalled; + } + + public function getOrphanedEvents(Request $request = null): array + { + if ($request) { + return $this->orphanedEvents[spl_object_hash($request)] ?? []; + } + + if (!$this->orphanedEvents) { + return []; + } + + return array_merge(...array_values($this->orphanedEvents)); + } + + public function reset(): void + { + $this->callStack = null; + $this->orphanedEvents = []; + $this->currentRequestHash = ''; + } + + /** + * Proxies all method calls to the original event dispatcher. + * + * @param string $method The method name + * @param array $arguments The method arguments + */ + public function __call(string $method, array $arguments): mixed + { + return $this->dispatcher->{$method}(...$arguments); + } + + /** + * Called before dispatching the event. + */ + protected function beforeDispatch(string $eventName, object $event): void + { + } + + /** + * Called after dispatching the event. + */ + protected function afterDispatch(string $eventName, object $event): void + { + } + + private function preProcess(string $eventName): void + { + if (!$this->dispatcher->hasListeners($eventName)) { + $this->orphanedEvents[$this->currentRequestHash][] = $eventName; + + return; + } + + foreach ($this->dispatcher->getListeners($eventName) as $listener) { + $priority = $this->getListenerPriority($eventName, $listener); + $wrappedListener = new WrappedListener($listener instanceof WrappedListener ? $listener->getWrappedListener() : $listener, null, $this->stopwatch, $this); + $this->wrappedListeners[$eventName][] = $wrappedListener; + $this->dispatcher->removeListener($eventName, $listener); + $this->dispatcher->addListener($eventName, $wrappedListener, $priority); + $this->callStack->attach($wrappedListener, [$eventName, $this->currentRequestHash]); + } + } + + private function postProcess(string $eventName): void + { + unset($this->wrappedListeners[$eventName]); + $skipped = false; + foreach ($this->dispatcher->getListeners($eventName) as $listener) { + if (!$listener instanceof WrappedListener) { // #12845: a new listener was added during dispatch. + continue; + } + // Unwrap listener + $priority = $this->getListenerPriority($eventName, $listener); + $this->dispatcher->removeListener($eventName, $listener); + $this->dispatcher->addListener($eventName, $listener->getWrappedListener(), $priority); + + if (null !== $this->logger) { + $context = ['event' => $eventName, 'listener' => $listener->getPretty()]; + } + + if ($listener->wasCalled()) { + $this->logger?->debug('Notified event "{event}" to listener "{listener}".', $context); + } else { + $this->callStack->detach($listener); + } + + if (null !== $this->logger && $skipped) { + $this->logger->debug('Listener "{listener}" was not called for event "{event}".', $context); + } + + if ($listener->stoppedPropagation()) { + $this->logger?->debug('Listener "{listener}" stopped propagation of the event "{event}".', $context); + + $skipped = true; + } + } + } + + private function sortNotCalledListeners(array $a, array $b): int + { + if (0 !== $cmp = strcmp($a['event'], $b['event'])) { + return $cmp; + } + + if (\is_int($a['priority']) && !\is_int($b['priority'])) { + return 1; + } + + if (!\is_int($a['priority']) && \is_int($b['priority'])) { + return -1; + } + + if ($a['priority'] === $b['priority']) { + return 0; + } + + if ($a['priority'] > $b['priority']) { + return -1; + } + + return 1; + } + + private function getListenersWithPriority(): array + { + $result = []; + + $allListeners = new \ReflectionProperty(EventDispatcher::class, 'listeners'); + + foreach ($allListeners->getValue($this->dispatcher) as $eventName => $listenersByPriority) { + foreach ($listenersByPriority as $priority => $listeners) { + foreach ($listeners as $listener) { + $result[$eventName][] = [$listener, $priority]; + } + } + } + + return $result; + } + + private function getListenersWithoutPriority(): array + { + $result = []; + + foreach ($this->getListeners() as $eventName => $listeners) { + foreach ($listeners as $listener) { + $result[$eventName][] = [$listener, null]; + } + } + + return $result; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher/Debug/WrappedListener.php b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/Debug/WrappedListener.php new file mode 100644 index 00000000..f23c963d --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/Debug/WrappedListener.php @@ -0,0 +1,144 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Debug; + +use Psr\EventDispatcher\StoppableEventInterface; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\Stopwatch\Stopwatch; +use Symfony\Component\VarDumper\Caster\ClassStub; + +/** + * @author Fabien Potencier + */ +final class WrappedListener +{ + private string|array|object $listener; + private ?\Closure $optimizedListener; + private string $name; + private bool $called = false; + private bool $stoppedPropagation = false; + private Stopwatch $stopwatch; + private ?EventDispatcherInterface $dispatcher; + private string $pretty; + private string $callableRef; + private ClassStub|string $stub; + private ?int $priority = null; + private static bool $hasClassStub; + + public function __construct(callable|array $listener, ?string $name, Stopwatch $stopwatch, EventDispatcherInterface $dispatcher = null, int $priority = null) + { + $this->listener = $listener; + $this->optimizedListener = $listener instanceof \Closure ? $listener : (\is_callable($listener) ? $listener(...) : null); + $this->stopwatch = $stopwatch; + $this->dispatcher = $dispatcher; + $this->priority = $priority; + + if (\is_array($listener)) { + [$this->name, $this->callableRef] = $this->parseListener($listener); + $this->pretty = $this->name.'::'.$listener[1]; + $this->callableRef .= '::'.$listener[1]; + } elseif ($listener instanceof \Closure) { + $r = new \ReflectionFunction($listener); + if (str_contains($r->name, '{closure}')) { + $this->pretty = $this->name = 'closure'; + } elseif ($class = $r->getClosureCalledClass()) { + $this->name = $class->name; + $this->pretty = $this->name.'::'.$r->name; + } else { + $this->pretty = $this->name = $r->name; + } + } elseif (\is_string($listener)) { + $this->pretty = $this->name = $listener; + } else { + $this->name = get_debug_type($listener); + $this->pretty = $this->name.'::__invoke'; + $this->callableRef = $listener::class.'::__invoke'; + } + + if (null !== $name) { + $this->name = $name; + } + + self::$hasClassStub ??= class_exists(ClassStub::class); + } + + public function getWrappedListener(): callable|array + { + return $this->listener; + } + + public function wasCalled(): bool + { + return $this->called; + } + + public function stoppedPropagation(): bool + { + return $this->stoppedPropagation; + } + + public function getPretty(): string + { + return $this->pretty; + } + + public function getInfo(string $eventName): array + { + $this->stub ??= self::$hasClassStub ? new ClassStub($this->pretty.'()', $this->callableRef ?? $this->listener) : $this->pretty.'()'; + + return [ + 'event' => $eventName, + 'priority' => $this->priority ??= $this->dispatcher?->getListenerPriority($eventName, $this->listener), + 'pretty' => $this->pretty, + 'stub' => $this->stub, + ]; + } + + public function __invoke(object $event, string $eventName, EventDispatcherInterface $dispatcher): void + { + $dispatcher = $this->dispatcher ?: $dispatcher; + + $this->called = true; + $this->priority ??= $dispatcher->getListenerPriority($eventName, $this->listener); + + $e = $this->stopwatch->start($this->name, 'event_listener'); + + try { + ($this->optimizedListener ?? $this->listener)($event, $eventName, $dispatcher); + } finally { + if ($e->isStarted()) { + $e->stop(); + } + } + + if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) { + $this->stoppedPropagation = true; + } + } + + private function parseListener(array $listener): array + { + if ($listener[0] instanceof \Closure) { + foreach ((new \ReflectionFunction($listener[0]))->getAttributes(\Closure::class) as $attribute) { + if ($name = $attribute->getArguments()['name'] ?? false) { + return [$name, $attribute->getArguments()['class'] ?? $name]; + } + } + } + + if (\is_object($listener[0])) { + return [get_debug_type($listener[0]), $listener[0]::class]; + } + + return [$listener[0], $listener[0]]; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher/DependencyInjection/AddEventAliasesPass.php b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/DependencyInjection/AddEventAliasesPass.php new file mode 100644 index 00000000..13b4336a --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/DependencyInjection/AddEventAliasesPass.php @@ -0,0 +1,40 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; + +/** + * This pass allows bundles to extend the list of event aliases. + * + * @author Alexander M. Turek + */ +class AddEventAliasesPass implements CompilerPassInterface +{ + private array $eventAliases; + + public function __construct(array $eventAliases) + { + $this->eventAliases = $eventAliases; + } + + public function process(ContainerBuilder $container): void + { + $eventAliases = $container->hasParameter('event_dispatcher.event_aliases') ? $container->getParameter('event_dispatcher.event_aliases') : []; + + $container->setParameter( + 'event_dispatcher.event_aliases', + array_merge($eventAliases, $this->eventAliases) + ); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php new file mode 100644 index 00000000..29a76bbc --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php @@ -0,0 +1,213 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\DependencyInjection; + +use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Contracts\EventDispatcher\Event; + +/** + * Compiler pass to register tagged services for an event dispatcher. + */ +class RegisterListenersPass implements CompilerPassInterface +{ + private array $hotPathEvents = []; + private array $noPreloadEvents = []; + + /** + * @return $this + */ + public function setHotPathEvents(array $hotPathEvents): static + { + $this->hotPathEvents = array_flip($hotPathEvents); + + return $this; + } + + /** + * @return $this + */ + public function setNoPreloadEvents(array $noPreloadEvents): static + { + $this->noPreloadEvents = array_flip($noPreloadEvents); + + return $this; + } + + public function process(ContainerBuilder $container): void + { + if (!$container->hasDefinition('event_dispatcher') && !$container->hasAlias('event_dispatcher')) { + return; + } + + $aliases = []; + + if ($container->hasParameter('event_dispatcher.event_aliases')) { + $aliases = $container->getParameter('event_dispatcher.event_aliases'); + } + + $globalDispatcherDefinition = $container->findDefinition('event_dispatcher'); + + foreach ($container->findTaggedServiceIds('kernel.event_listener', true) as $id => $events) { + $noPreload = 0; + + foreach ($events as $event) { + $priority = $event['priority'] ?? 0; + + if (!isset($event['event'])) { + if ($container->getDefinition($id)->hasTag('kernel.event_subscriber')) { + continue; + } + + $event['method'] ??= '__invoke'; + $event['event'] = $this->getEventFromTypeDeclaration($container, $id, $event['method']); + } + + $event['event'] = $aliases[$event['event']] ?? $event['event']; + + if (!isset($event['method'])) { + $event['method'] = 'on'.preg_replace_callback([ + '/(?<=\b|_)[a-z]/i', + '/[^a-z0-9]/i', + ], fn ($matches) => strtoupper($matches[0]), $event['event']); + $event['method'] = preg_replace('/[^a-z0-9]/i', '', $event['method']); + + if (null !== ($class = $container->getDefinition($id)->getClass()) && ($r = $container->getReflectionClass($class, false)) && !$r->hasMethod($event['method'])) { + if (!$r->hasMethod('__invoke')) { + throw new InvalidArgumentException(sprintf('None of the "%s" or "__invoke" methods exist for the service "%s". Please define the "method" attribute on "kernel.event_listener" tags.', $event['method'], $id)); + } + + $event['method'] = '__invoke'; + } + } + + $dispatcherDefinition = $globalDispatcherDefinition; + if (isset($event['dispatcher'])) { + $dispatcherDefinition = $container->findDefinition($event['dispatcher']); + } + + $dispatcherDefinition->addMethodCall('addListener', [$event['event'], [new ServiceClosureArgument(new Reference($id)), $event['method']], $priority]); + + if (isset($this->hotPathEvents[$event['event']])) { + $container->getDefinition($id)->addTag('container.hot_path'); + } elseif (isset($this->noPreloadEvents[$event['event']])) { + ++$noPreload; + } + } + + if ($noPreload && \count($events) === $noPreload) { + $container->getDefinition($id)->addTag('container.no_preload'); + } + } + + $extractingDispatcher = new ExtractingEventDispatcher(); + + foreach ($container->findTaggedServiceIds('kernel.event_subscriber', true) as $id => $tags) { + $def = $container->getDefinition($id); + + // We must assume that the class value has been correctly filled, even if the service is created by a factory + $class = $def->getClass(); + + if (!$r = $container->getReflectionClass($class)) { + throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id)); + } + if (!$r->isSubclassOf(EventSubscriberInterface::class)) { + throw new InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, EventSubscriberInterface::class)); + } + $class = $r->name; + + $dispatcherDefinitions = []; + foreach ($tags as $attributes) { + if (!isset($attributes['dispatcher']) || isset($dispatcherDefinitions[$attributes['dispatcher']])) { + continue; + } + + $dispatcherDefinitions[$attributes['dispatcher']] = $container->findDefinition($attributes['dispatcher']); + } + + if (!$dispatcherDefinitions) { + $dispatcherDefinitions = [$globalDispatcherDefinition]; + } + + $noPreload = 0; + ExtractingEventDispatcher::$aliases = $aliases; + ExtractingEventDispatcher::$subscriber = $class; + $extractingDispatcher->addSubscriber($extractingDispatcher); + foreach ($extractingDispatcher->listeners as $args) { + $args[1] = [new ServiceClosureArgument(new Reference($id)), $args[1]]; + foreach ($dispatcherDefinitions as $dispatcherDefinition) { + $dispatcherDefinition->addMethodCall('addListener', $args); + } + + if (isset($this->hotPathEvents[$args[0]])) { + $container->getDefinition($id)->addTag('container.hot_path'); + } elseif (isset($this->noPreloadEvents[$args[0]])) { + ++$noPreload; + } + } + if ($noPreload && \count($extractingDispatcher->listeners) === $noPreload) { + $container->getDefinition($id)->addTag('container.no_preload'); + } + $extractingDispatcher->listeners = []; + ExtractingEventDispatcher::$aliases = []; + } + } + + private function getEventFromTypeDeclaration(ContainerBuilder $container, string $id, string $method): string + { + if ( + null === ($class = $container->getDefinition($id)->getClass()) + || !($r = $container->getReflectionClass($class, false)) + || !$r->hasMethod($method) + || 1 > ($m = $r->getMethod($method))->getNumberOfParameters() + || !($type = $m->getParameters()[0]->getType()) instanceof \ReflectionNamedType + || $type->isBuiltin() + || Event::class === ($name = $type->getName()) + ) { + throw new InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "kernel.event_listener" tags.', $id)); + } + + return $name; + } +} + +/** + * @internal + */ +class ExtractingEventDispatcher extends EventDispatcher implements EventSubscriberInterface +{ + public array $listeners = []; + + public static array $aliases = []; + public static string $subscriber; + + public function addListener(string $eventName, callable|array $listener, int $priority = 0): void + { + $this->listeners[] = [$eventName, $listener[1], $priority]; + } + + public static function getSubscribedEvents(): array + { + $events = []; + + foreach ([self::$subscriber, 'getSubscribedEvents']() as $eventName => $params) { + $events[self::$aliases[$eventName] ?? $eventName] = $params; + } + + return $events; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher/EventDispatcher.php b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/EventDispatcher.php new file mode 100644 index 00000000..65d86263 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/EventDispatcher.php @@ -0,0 +1,256 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +use Psr\EventDispatcher\StoppableEventInterface; +use Symfony\Component\EventDispatcher\Debug\WrappedListener; + +/** + * The EventDispatcherInterface is the central point of Symfony's event listener system. + * + * Listeners are registered on the manager and events are dispatched through the + * manager. + * + * @author Guilherme Blanco + * @author Jonathan Wage + * @author Roman Borschel + * @author Bernhard Schussek + * @author Fabien Potencier + * @author Jordi Boggiano + * @author Jordan Alliot + * @author Nicolas Grekas + */ +class EventDispatcher implements EventDispatcherInterface +{ + private array $listeners = []; + private array $sorted = []; + private array $optimized; + + public function __construct() + { + if (__CLASS__ === static::class) { + $this->optimized = []; + } + } + + public function dispatch(object $event, string $eventName = null): object + { + $eventName ??= $event::class; + + if (isset($this->optimized)) { + $listeners = $this->optimized[$eventName] ?? (empty($this->listeners[$eventName]) ? [] : $this->optimizeListeners($eventName)); + } else { + $listeners = $this->getListeners($eventName); + } + + if ($listeners) { + $this->callListeners($listeners, $eventName, $event); + } + + return $event; + } + + public function getListeners(string $eventName = null): array + { + if (null !== $eventName) { + if (empty($this->listeners[$eventName])) { + return []; + } + + if (!isset($this->sorted[$eventName])) { + $this->sortListeners($eventName); + } + + return $this->sorted[$eventName]; + } + + foreach ($this->listeners as $eventName => $eventListeners) { + if (!isset($this->sorted[$eventName])) { + $this->sortListeners($eventName); + } + } + + return array_filter($this->sorted); + } + + public function getListenerPriority(string $eventName, callable|array $listener): ?int + { + if (empty($this->listeners[$eventName])) { + return null; + } + + if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure && 2 >= \count($listener)) { + $listener[0] = $listener[0](); + $listener[1] ??= '__invoke'; + } + + foreach ($this->listeners[$eventName] as $priority => &$listeners) { + foreach ($listeners as &$v) { + if ($v !== $listener && \is_array($v) && isset($v[0]) && $v[0] instanceof \Closure && 2 >= \count($v)) { + $v[0] = $v[0](); + $v[1] ??= '__invoke'; + } + if ($v === $listener || ($listener instanceof \Closure && $v == $listener)) { + return $priority; + } + } + } + + return null; + } + + public function hasListeners(string $eventName = null): bool + { + if (null !== $eventName) { + return !empty($this->listeners[$eventName]); + } + + foreach ($this->listeners as $eventListeners) { + if ($eventListeners) { + return true; + } + } + + return false; + } + + public function addListener(string $eventName, callable|array $listener, int $priority = 0): void + { + $this->listeners[$eventName][$priority][] = $listener; + unset($this->sorted[$eventName], $this->optimized[$eventName]); + } + + public function removeListener(string $eventName, callable|array $listener): void + { + if (empty($this->listeners[$eventName])) { + return; + } + + if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure && 2 >= \count($listener)) { + $listener[0] = $listener[0](); + $listener[1] ??= '__invoke'; + } + + foreach ($this->listeners[$eventName] as $priority => &$listeners) { + foreach ($listeners as $k => &$v) { + if ($v !== $listener && \is_array($v) && isset($v[0]) && $v[0] instanceof \Closure && 2 >= \count($v)) { + $v[0] = $v[0](); + $v[1] ??= '__invoke'; + } + if ($v === $listener || ($listener instanceof \Closure && $v == $listener)) { + unset($listeners[$k], $this->sorted[$eventName], $this->optimized[$eventName]); + } + } + + if (!$listeners) { + unset($this->listeners[$eventName][$priority]); + } + } + } + + public function addSubscriber(EventSubscriberInterface $subscriber): void + { + foreach ($subscriber->getSubscribedEvents() as $eventName => $params) { + if (\is_string($params)) { + $this->addListener($eventName, [$subscriber, $params]); + } elseif (\is_string($params[0])) { + $this->addListener($eventName, [$subscriber, $params[0]], $params[1] ?? 0); + } else { + foreach ($params as $listener) { + $this->addListener($eventName, [$subscriber, $listener[0]], $listener[1] ?? 0); + } + } + } + } + + public function removeSubscriber(EventSubscriberInterface $subscriber): void + { + foreach ($subscriber->getSubscribedEvents() as $eventName => $params) { + if (\is_array($params) && \is_array($params[0])) { + foreach ($params as $listener) { + $this->removeListener($eventName, [$subscriber, $listener[0]]); + } + } else { + $this->removeListener($eventName, [$subscriber, \is_string($params) ? $params : $params[0]]); + } + } + } + + /** + * Triggers the listeners of an event. + * + * This method can be overridden to add functionality that is executed + * for each listener. + * + * @param callable[] $listeners The event listeners + * @param string $eventName The name of the event to dispatch + * @param object $event The event object to pass to the event handlers/listeners + */ + protected function callListeners(iterable $listeners, string $eventName, object $event): void + { + $stoppable = $event instanceof StoppableEventInterface; + + foreach ($listeners as $listener) { + if ($stoppable && $event->isPropagationStopped()) { + break; + } + $listener($event, $eventName, $this); + } + } + + /** + * Sorts the internal list of listeners for the given event by priority. + */ + private function sortListeners(string $eventName): void + { + krsort($this->listeners[$eventName]); + $this->sorted[$eventName] = []; + + foreach ($this->listeners[$eventName] as &$listeners) { + foreach ($listeners as &$listener) { + if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure && 2 >= \count($listener)) { + $listener[0] = $listener[0](); + $listener[1] ??= '__invoke'; + } + $this->sorted[$eventName][] = $listener; + } + } + } + + /** + * Optimizes the internal list of listeners for the given event by priority. + */ + private function optimizeListeners(string $eventName): array + { + krsort($this->listeners[$eventName]); + $this->optimized[$eventName] = []; + + foreach ($this->listeners[$eventName] as &$listeners) { + foreach ($listeners as &$listener) { + $closure = &$this->optimized[$eventName][]; + if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure && 2 >= \count($listener)) { + $closure = static function (...$args) use (&$listener, &$closure) { + if ($listener[0] instanceof \Closure) { + $listener[0] = $listener[0](); + $listener[1] ??= '__invoke'; + } + ($closure = $listener(...))(...$args); + }; + } else { + $closure = $listener instanceof WrappedListener ? $listener : $listener(...); + } + } + } + + return $this->optimized[$eventName]; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher/EventDispatcherInterface.php b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/EventDispatcherInterface.php new file mode 100644 index 00000000..6d4a5b4d --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/EventDispatcherInterface.php @@ -0,0 +1,66 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface; + +/** + * The EventDispatcherInterface is the central point of Symfony's event listener system. + * Listeners are registered on the manager and events are dispatched through the + * manager. + * + * @author Bernhard Schussek + */ +interface EventDispatcherInterface extends ContractsEventDispatcherInterface +{ + /** + * Adds an event listener that listens on the specified events. + * + * @param int $priority The higher this value, the earlier an event + * listener will be triggered in the chain (defaults to 0) + */ + public function addListener(string $eventName, callable $listener, int $priority = 0): void; + + /** + * Adds an event subscriber. + * + * The subscriber is asked for all the events it is + * interested in and added as a listener for these events. + */ + public function addSubscriber(EventSubscriberInterface $subscriber): void; + + /** + * Removes an event listener from the specified events. + */ + public function removeListener(string $eventName, callable $listener): void; + + public function removeSubscriber(EventSubscriberInterface $subscriber): void; + + /** + * Gets the listeners of a specific event or all listeners sorted by descending priority. + * + * @return array + */ + public function getListeners(string $eventName = null): array; + + /** + * Gets the listener priority for a specific event. + * + * Returns null if the event or the listener does not exist. + */ + public function getListenerPriority(string $eventName, callable $listener): ?int; + + /** + * Checks whether an event has any registered listeners. + */ + public function hasListeners(string $eventName = null): bool; +} diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher/EventSubscriberInterface.php b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/EventSubscriberInterface.php new file mode 100644 index 00000000..2085e428 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/EventSubscriberInterface.php @@ -0,0 +1,49 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +/** + * An EventSubscriber knows itself what events it is interested in. + * If an EventSubscriber is added to an EventDispatcherInterface, the manager invokes + * {@link getSubscribedEvents} and registers the subscriber as a listener for all + * returned events. + * + * @author Guilherme Blanco + * @author Jonathan Wage + * @author Roman Borschel + * @author Bernhard Schussek + */ +interface EventSubscriberInterface +{ + /** + * Returns an array of event names this subscriber wants to listen to. + * + * The array keys are event names and the value can be: + * + * * The method name to call (priority defaults to 0) + * * An array composed of the method name to call and the priority + * * An array of arrays composed of the method names to call and respective + * priorities, or 0 if unset + * + * For instance: + * + * * ['eventName' => 'methodName'] + * * ['eventName' => ['methodName', $priority]] + * * ['eventName' => [['methodName1', $priority], ['methodName2']]] + * + * The code must not depend on runtime state as it will only be called at compile time. + * All logic depending on runtime state must be put into the individual methods handling the events. + * + * @return array> + */ + public static function getSubscribedEvents(); +} diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher/GenericEvent.php b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/GenericEvent.php new file mode 100644 index 00000000..b14faa5f --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/GenericEvent.php @@ -0,0 +1,158 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +use Symfony\Contracts\EventDispatcher\Event; + +/** + * Event encapsulation class. + * + * Encapsulates events thus decoupling the observer from the subject they encapsulate. + * + * @author Drak + * + * @implements \ArrayAccess + * @implements \IteratorAggregate + */ +class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate +{ + protected mixed $subject; + protected array $arguments; + + /** + * Encapsulate an event with $subject and $args. + * + * @param mixed $subject The subject of the event, usually an object or a callable + * @param array $arguments Arguments to store in the event + */ + public function __construct(mixed $subject = null, array $arguments = []) + { + $this->subject = $subject; + $this->arguments = $arguments; + } + + /** + * Getter for subject property. + */ + public function getSubject(): mixed + { + return $this->subject; + } + + /** + * Get argument by key. + * + * @throws \InvalidArgumentException if key is not found + */ + public function getArgument(string $key): mixed + { + if ($this->hasArgument($key)) { + return $this->arguments[$key]; + } + + throw new \InvalidArgumentException(sprintf('Argument "%s" not found.', $key)); + } + + /** + * Add argument to event. + * + * @return $this + */ + public function setArgument(string $key, mixed $value): static + { + $this->arguments[$key] = $value; + + return $this; + } + + /** + * Getter for all arguments. + */ + public function getArguments(): array + { + return $this->arguments; + } + + /** + * Set args property. + * + * @return $this + */ + public function setArguments(array $args = []): static + { + $this->arguments = $args; + + return $this; + } + + /** + * Has argument. + */ + public function hasArgument(string $key): bool + { + return \array_key_exists($key, $this->arguments); + } + + /** + * ArrayAccess for argument getter. + * + * @param string $key Array key + * + * @throws \InvalidArgumentException if key does not exist in $this->args + */ + public function offsetGet(mixed $key): mixed + { + return $this->getArgument($key); + } + + /** + * ArrayAccess for argument setter. + * + * @param string $key Array key to set + */ + public function offsetSet(mixed $key, mixed $value): void + { + $this->setArgument($key, $value); + } + + /** + * ArrayAccess for unset argument. + * + * @param string $key Array key + */ + public function offsetUnset(mixed $key): void + { + if ($this->hasArgument($key)) { + unset($this->arguments[$key]); + } + } + + /** + * ArrayAccess has argument. + * + * @param string $key Array key + */ + public function offsetExists(mixed $key): bool + { + return $this->hasArgument($key); + } + + /** + * IteratorAggregate for iterating over the object like an array. + * + * @return \ArrayIterator + */ + public function getIterator(): \ArrayIterator + { + return new \ArrayIterator($this->arguments); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher/ImmutableEventDispatcher.php b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/ImmutableEventDispatcher.php new file mode 100644 index 00000000..1e863ccb --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/ImmutableEventDispatcher.php @@ -0,0 +1,67 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +/** + * A read-only proxy for an event dispatcher. + * + * @author Bernhard Schussek + */ +class ImmutableEventDispatcher implements EventDispatcherInterface +{ + private EventDispatcherInterface $dispatcher; + + public function __construct(EventDispatcherInterface $dispatcher) + { + $this->dispatcher = $dispatcher; + } + + public function dispatch(object $event, string $eventName = null): object + { + return $this->dispatcher->dispatch($event, $eventName); + } + + public function addListener(string $eventName, callable|array $listener, int $priority = 0): never + { + throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); + } + + public function addSubscriber(EventSubscriberInterface $subscriber): never + { + throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); + } + + public function removeListener(string $eventName, callable|array $listener): never + { + throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); + } + + public function removeSubscriber(EventSubscriberInterface $subscriber): never + { + throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); + } + + public function getListeners(string $eventName = null): array + { + return $this->dispatcher->getListeners($eventName); + } + + public function getListenerPriority(string $eventName, callable|array $listener): ?int + { + return $this->dispatcher->getListenerPriority($eventName, $listener); + } + + public function hasListeners(string $eventName = null): bool + { + return $this->dispatcher->hasListeners($eventName); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher/LICENSE b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/LICENSE new file mode 100644 index 00000000..0138f8f0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher/README.md b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/README.md new file mode 100644 index 00000000..dcdb68d2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/README.md @@ -0,0 +1,15 @@ +EventDispatcher Component +========================= + +The EventDispatcher component provides tools that allow your application +components to communicate with each other by dispatching events and listening to +them. + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/event_dispatcher.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/tools/php-cs-fixer/vendor/symfony/event-dispatcher/composer.json b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/composer.json new file mode 100644 index 00000000..598bbdc5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/event-dispatcher/composer.json @@ -0,0 +1,47 @@ +{ + "name": "symfony/event-dispatcher", + "type": "library", + "description": "Provides tools that allow your application components to communicate with each other by dispatching events and listening to them", + "keywords": [], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.2", + "symfony/event-dispatcher-contracts": "^2.5|^3" + }, + "require-dev": { + "symfony/dependency-injection": "^6.4|^7.0", + "symfony/expression-language": "^6.4|^7.0", + "symfony/config": "^6.4|^7.0", + "symfony/error-handler": "^6.4|^7.0", + "symfony/http-foundation": "^6.4|^7.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/stopwatch": "^6.4|^7.0", + "psr/log": "^1|^2|^3" + }, + "conflict": { + "symfony/dependency-injection": "<6.4", + "symfony/service-contracts": "<2.5" + }, + "provide": { + "psr/event-dispatcher-implementation": "1.0", + "symfony/event-dispatcher-implementation": "2.0|3.0" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\EventDispatcher\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/tools/php-cs-fixer/vendor/symfony/filesystem/CHANGELOG.md b/tools/php-cs-fixer/vendor/symfony/filesystem/CHANGELOG.md new file mode 100644 index 00000000..b4bd22eb --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/filesystem/CHANGELOG.md @@ -0,0 +1,87 @@ +CHANGELOG +========= + +7.0 +--- + + * Add argument `$lock` to `Filesystem::appendToFile()` + +5.4 +--- + + * Add `Path` class + * Add `$lock` argument to `Filesystem::appendToFile()` + +5.0.0 +----- + + * `Filesystem::dumpFile()` and `appendToFile()` don't accept arrays anymore + +4.4.0 +----- + + * support for passing a `null` value to `Filesystem::isAbsolutePath()` is deprecated and will be removed in 5.0 + * `tempnam()` now accepts a third argument `$suffix`. + +4.3.0 +----- + + * support for passing arrays to `Filesystem::dumpFile()` is deprecated and will be removed in 5.0 + * support for passing arrays to `Filesystem::appendToFile()` is deprecated and will be removed in 5.0 + +4.0.0 +----- + + * removed `LockHandler` + * Support for passing relative paths to `Filesystem::makePathRelative()` has been removed. + +3.4.0 +----- + + * support for passing relative paths to `Filesystem::makePathRelative()` is deprecated and will be removed in 4.0 + +3.3.0 +----- + + * added `appendToFile()` to append contents to existing files + +3.2.0 +----- + + * added `readlink()` as a platform independent method to read links + +3.0.0 +----- + + * removed `$mode` argument from `Filesystem::dumpFile()` + +2.8.0 +----- + + * added tempnam() a stream aware version of PHP's native tempnam() + +2.6.0 +----- + + * added LockHandler + +2.3.12 +------ + + * deprecated dumpFile() file mode argument. + +2.3.0 +----- + + * added the dumpFile() method to atomically write files + +2.2.0 +----- + + * added a delete option for the mirror() method + +2.1.0 +----- + + * 24eb396 : BC Break : mkdir() function now throws exception in case of failure instead of returning Boolean value + * created the component diff --git a/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/ExceptionInterface.php b/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/ExceptionInterface.php new file mode 100644 index 00000000..fc438d9f --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/ExceptionInterface.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Filesystem\Exception; + +/** + * Exception interface for all exceptions thrown by the component. + * + * @author Romain Neutron + */ +interface ExceptionInterface extends \Throwable +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/FileNotFoundException.php b/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/FileNotFoundException.php new file mode 100644 index 00000000..48b64080 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/FileNotFoundException.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Filesystem\Exception; + +/** + * Exception class thrown when a file couldn't be found. + * + * @author Fabien Potencier + * @author Christian Gärtner + */ +class FileNotFoundException extends IOException +{ + public function __construct(string $message = null, int $code = 0, \Throwable $previous = null, string $path = null) + { + if (null === $message) { + if (null === $path) { + $message = 'File could not be found.'; + } else { + $message = sprintf('File "%s" could not be found.', $path); + } + } + + parent::__construct($message, $code, $previous, $path); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/IOException.php b/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/IOException.php new file mode 100644 index 00000000..a3c54455 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/IOException.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Filesystem\Exception; + +/** + * Exception class thrown when a filesystem operation failure happens. + * + * @author Romain Neutron + * @author Christian Gärtner + * @author Fabien Potencier + */ +class IOException extends \RuntimeException implements IOExceptionInterface +{ + private ?string $path; + + public function __construct(string $message, int $code = 0, \Throwable $previous = null, string $path = null) + { + $this->path = $path; + + parent::__construct($message, $code, $previous); + } + + public function getPath(): ?string + { + return $this->path; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/IOExceptionInterface.php b/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/IOExceptionInterface.php new file mode 100644 index 00000000..90c71db8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/IOExceptionInterface.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Filesystem\Exception; + +/** + * IOException interface for file and input/output stream related exceptions thrown by the component. + * + * @author Christian Gärtner + */ +interface IOExceptionInterface extends ExceptionInterface +{ + /** + * Returns the associated path for the exception. + */ + public function getPath(): ?string; +} diff --git a/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/InvalidArgumentException.php b/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/InvalidArgumentException.php new file mode 100644 index 00000000..abadc200 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/InvalidArgumentException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Filesystem\Exception; + +/** + * @author Christian Flothmann + */ +class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/RuntimeException.php b/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/RuntimeException.php new file mode 100644 index 00000000..a7512dca --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/filesystem/Exception/RuntimeException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Filesystem\Exception; + +/** + * @author Théo Fidry + */ +class RuntimeException extends \RuntimeException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/filesystem/Filesystem.php b/tools/php-cs-fixer/vendor/symfony/filesystem/Filesystem.php new file mode 100644 index 00000000..e8ba4958 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/filesystem/Filesystem.php @@ -0,0 +1,739 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Filesystem; + +use Symfony\Component\Filesystem\Exception\FileNotFoundException; +use Symfony\Component\Filesystem\Exception\InvalidArgumentException; +use Symfony\Component\Filesystem\Exception\IOException; + +/** + * Provides basic utility to manipulate the file system. + * + * @author Fabien Potencier + */ +class Filesystem +{ + private static ?string $lastError = null; + + /** + * Copies a file. + * + * If the target file is older than the origin file, it's always overwritten. + * If the target file is newer, it is overwritten only when the + * $overwriteNewerFiles option is set to true. + * + * @throws FileNotFoundException When originFile doesn't exist + * @throws IOException When copy fails + */ + public function copy(string $originFile, string $targetFile, bool $overwriteNewerFiles = false): void + { + $originIsLocal = stream_is_local($originFile) || 0 === stripos($originFile, 'file://'); + if ($originIsLocal && !is_file($originFile)) { + throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile); + } + + $this->mkdir(\dirname($targetFile)); + + $doCopy = true; + if (!$overwriteNewerFiles && null === parse_url($originFile, \PHP_URL_HOST) && is_file($targetFile)) { + $doCopy = filemtime($originFile) > filemtime($targetFile); + } + + if ($doCopy) { + // https://bugs.php.net/64634 + if (!$source = self::box('fopen', $originFile, 'r')) { + throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading: ', $originFile, $targetFile).self::$lastError, 0, null, $originFile); + } + + // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default + if (!$target = self::box('fopen', $targetFile, 'w', false, stream_context_create(['ftp' => ['overwrite' => true]]))) { + throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing: ', $originFile, $targetFile).self::$lastError, 0, null, $originFile); + } + + $bytesCopied = stream_copy_to_stream($source, $target); + fclose($source); + fclose($target); + unset($source, $target); + + if (!is_file($targetFile)) { + throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile); + } + + if ($originIsLocal) { + // Like `cp`, preserve executable permission bits + self::box('chmod', $targetFile, fileperms($targetFile) | (fileperms($originFile) & 0111)); + + if ($bytesCopied !== $bytesOrigin = filesize($originFile)) { + throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s" (%g of %g bytes copied).', $originFile, $targetFile, $bytesCopied, $bytesOrigin), 0, null, $originFile); + } + } + } + } + + /** + * Creates a directory recursively. + * + * @throws IOException On any directory creation failure + */ + public function mkdir(string|iterable $dirs, int $mode = 0777): void + { + foreach ($this->toIterable($dirs) as $dir) { + if (is_dir($dir)) { + continue; + } + + if (!self::box('mkdir', $dir, $mode, true) && !is_dir($dir)) { + throw new IOException(sprintf('Failed to create "%s": ', $dir).self::$lastError, 0, null, $dir); + } + } + } + + /** + * Checks the existence of files or directories. + */ + public function exists(string|iterable $files): bool + { + $maxPathLength = \PHP_MAXPATHLEN - 2; + + foreach ($this->toIterable($files) as $file) { + if (\strlen($file) > $maxPathLength) { + throw new IOException(sprintf('Could not check if file exist because path length exceeds %d characters.', $maxPathLength), 0, null, $file); + } + + if (!file_exists($file)) { + return false; + } + } + + return true; + } + + /** + * Sets access and modification time of file. + * + * @param int|null $time The touch time as a Unix timestamp, if not supplied the current system time is used + * @param int|null $atime The access time as a Unix timestamp, if not supplied the current system time is used + * + * @throws IOException When touch fails + */ + public function touch(string|iterable $files, int $time = null, int $atime = null): void + { + foreach ($this->toIterable($files) as $file) { + if (!($time ? self::box('touch', $file, $time, $atime) : self::box('touch', $file))) { + throw new IOException(sprintf('Failed to touch "%s": ', $file).self::$lastError, 0, null, $file); + } + } + } + + /** + * Removes files or directories. + * + * @throws IOException When removal fails + */ + public function remove(string|iterable $files): void + { + if ($files instanceof \Traversable) { + $files = iterator_to_array($files, false); + } elseif (!\is_array($files)) { + $files = [$files]; + } + + self::doRemove($files, false); + } + + private static function doRemove(array $files, bool $isRecursive): void + { + $files = array_reverse($files); + foreach ($files as $file) { + if (is_link($file)) { + // See https://bugs.php.net/52176 + if (!(self::box('unlink', $file) || '\\' !== \DIRECTORY_SEPARATOR || self::box('rmdir', $file)) && file_exists($file)) { + throw new IOException(sprintf('Failed to remove symlink "%s": ', $file).self::$lastError); + } + } elseif (is_dir($file)) { + if (!$isRecursive) { + $tmpName = \dirname(realpath($file)).'/.'.strrev(strtr(base64_encode(random_bytes(2)), '/=', '-_')); + + if (file_exists($tmpName)) { + try { + self::doRemove([$tmpName], true); + } catch (IOException) { + } + } + + if (!file_exists($tmpName) && self::box('rename', $file, $tmpName)) { + $origFile = $file; + $file = $tmpName; + } else { + $origFile = null; + } + } + + $filesystemIterator = new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS); + self::doRemove(iterator_to_array($filesystemIterator, true), true); + + if (!self::box('rmdir', $file) && file_exists($file) && !$isRecursive) { + $lastError = self::$lastError; + + if (null !== $origFile && self::box('rename', $file, $origFile)) { + $file = $origFile; + } + + throw new IOException(sprintf('Failed to remove directory "%s": ', $file).$lastError); + } + } elseif (!self::box('unlink', $file) && (str_contains(self::$lastError, 'Permission denied') || file_exists($file))) { + throw new IOException(sprintf('Failed to remove file "%s": ', $file).self::$lastError); + } + } + } + + /** + * Change mode for an array of files or directories. + * + * @param int $mode The new mode (octal) + * @param int $umask The mode mask (octal) + * @param bool $recursive Whether change the mod recursively or not + * + * @throws IOException When the change fails + */ + public function chmod(string|iterable $files, int $mode, int $umask = 0000, bool $recursive = false): void + { + foreach ($this->toIterable($files) as $file) { + if (!self::box('chmod', $file, $mode & ~$umask)) { + throw new IOException(sprintf('Failed to chmod file "%s": ', $file).self::$lastError, 0, null, $file); + } + if ($recursive && is_dir($file) && !is_link($file)) { + $this->chmod(new \FilesystemIterator($file), $mode, $umask, true); + } + } + } + + /** + * Change the owner of an array of files or directories. + * + * @param string|int $user A user name or number + * @param bool $recursive Whether change the owner recursively or not + * + * @throws IOException When the change fails + */ + public function chown(string|iterable $files, string|int $user, bool $recursive = false): void + { + foreach ($this->toIterable($files) as $file) { + if ($recursive && is_dir($file) && !is_link($file)) { + $this->chown(new \FilesystemIterator($file), $user, true); + } + if (is_link($file) && \function_exists('lchown')) { + if (!self::box('lchown', $file, $user)) { + throw new IOException(sprintf('Failed to chown file "%s": ', $file).self::$lastError, 0, null, $file); + } + } else { + if (!self::box('chown', $file, $user)) { + throw new IOException(sprintf('Failed to chown file "%s": ', $file).self::$lastError, 0, null, $file); + } + } + } + } + + /** + * Change the group of an array of files or directories. + * + * @param string|int $group A group name or number + * @param bool $recursive Whether change the group recursively or not + * + * @throws IOException When the change fails + */ + public function chgrp(string|iterable $files, string|int $group, bool $recursive = false): void + { + foreach ($this->toIterable($files) as $file) { + if ($recursive && is_dir($file) && !is_link($file)) { + $this->chgrp(new \FilesystemIterator($file), $group, true); + } + if (is_link($file) && \function_exists('lchgrp')) { + if (!self::box('lchgrp', $file, $group)) { + throw new IOException(sprintf('Failed to chgrp file "%s": ', $file).self::$lastError, 0, null, $file); + } + } else { + if (!self::box('chgrp', $file, $group)) { + throw new IOException(sprintf('Failed to chgrp file "%s": ', $file).self::$lastError, 0, null, $file); + } + } + } + } + + /** + * Renames a file or a directory. + * + * @throws IOException When target file or directory already exists + * @throws IOException When origin cannot be renamed + */ + public function rename(string $origin, string $target, bool $overwrite = false): void + { + // we check that target does not exist + if (!$overwrite && $this->isReadable($target)) { + throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target); + } + + if (!self::box('rename', $origin, $target)) { + if (is_dir($origin)) { + // See https://bugs.php.net/54097 & https://php.net/rename#113943 + $this->mirror($origin, $target, null, ['override' => $overwrite, 'delete' => $overwrite]); + $this->remove($origin); + + return; + } + throw new IOException(sprintf('Cannot rename "%s" to "%s": ', $origin, $target).self::$lastError, 0, null, $target); + } + } + + /** + * Tells whether a file exists and is readable. + * + * @throws IOException When windows path is longer than 258 characters + */ + private function isReadable(string $filename): bool + { + $maxPathLength = \PHP_MAXPATHLEN - 2; + + if (\strlen($filename) > $maxPathLength) { + throw new IOException(sprintf('Could not check if file is readable because path length exceeds %d characters.', $maxPathLength), 0, null, $filename); + } + + return is_readable($filename); + } + + /** + * Creates a symbolic link or copy a directory. + * + * @throws IOException When symlink fails + */ + public function symlink(string $originDir, string $targetDir, bool $copyOnWindows = false): void + { + self::assertFunctionExists('symlink'); + + if ('\\' === \DIRECTORY_SEPARATOR) { + $originDir = strtr($originDir, '/', '\\'); + $targetDir = strtr($targetDir, '/', '\\'); + + if ($copyOnWindows) { + $this->mirror($originDir, $targetDir); + + return; + } + } + + $this->mkdir(\dirname($targetDir)); + + if (is_link($targetDir)) { + if (readlink($targetDir) === $originDir) { + return; + } + $this->remove($targetDir); + } + + if (!self::box('symlink', $originDir, $targetDir)) { + $this->linkException($originDir, $targetDir, 'symbolic'); + } + } + + /** + * Creates a hard link, or several hard links to a file. + * + * @param string|string[] $targetFiles The target file(s) + * + * @throws FileNotFoundException When original file is missing or not a file + * @throws IOException When link fails, including if link already exists + */ + public function hardlink(string $originFile, string|iterable $targetFiles): void + { + self::assertFunctionExists('link'); + + if (!$this->exists($originFile)) { + throw new FileNotFoundException(null, 0, null, $originFile); + } + + if (!is_file($originFile)) { + throw new FileNotFoundException(sprintf('Origin file "%s" is not a file.', $originFile)); + } + + foreach ($this->toIterable($targetFiles) as $targetFile) { + if (is_file($targetFile)) { + if (fileinode($originFile) === fileinode($targetFile)) { + continue; + } + $this->remove($targetFile); + } + + if (!self::box('link', $originFile, $targetFile)) { + $this->linkException($originFile, $targetFile, 'hard'); + } + } + } + + /** + * @param string $linkType Name of the link type, typically 'symbolic' or 'hard' + */ + private function linkException(string $origin, string $target, string $linkType): never + { + if (self::$lastError) { + if ('\\' === \DIRECTORY_SEPARATOR && str_contains(self::$lastError, 'error code(1314)')) { + throw new IOException(sprintf('Unable to create "%s" link due to error code 1314: \'A required privilege is not held by the client\'. Do you have the required Administrator-rights?', $linkType), 0, null, $target); + } + } + throw new IOException(sprintf('Failed to create "%s" link from "%s" to "%s": ', $linkType, $origin, $target).self::$lastError, 0, null, $target); + } + + /** + * Resolves links in paths. + * + * With $canonicalize = false (default) + * - if $path does not exist or is not a link, returns null + * - if $path is a link, returns the next direct target of the link without considering the existence of the target + * + * With $canonicalize = true + * - if $path does not exist, returns null + * - if $path exists, returns its absolute fully resolved final version + */ + public function readlink(string $path, bool $canonicalize = false): ?string + { + if (!$canonicalize && !is_link($path)) { + return null; + } + + if ($canonicalize) { + if (!$this->exists($path)) { + return null; + } + + return realpath($path); + } + + return readlink($path); + } + + /** + * Given an existing path, convert it to a path relative to a given starting path. + */ + public function makePathRelative(string $endPath, string $startPath): string + { + if (!$this->isAbsolutePath($startPath)) { + throw new InvalidArgumentException(sprintf('The start path "%s" is not absolute.', $startPath)); + } + + if (!$this->isAbsolutePath($endPath)) { + throw new InvalidArgumentException(sprintf('The end path "%s" is not absolute.', $endPath)); + } + + // Normalize separators on Windows + if ('\\' === \DIRECTORY_SEPARATOR) { + $endPath = str_replace('\\', '/', $endPath); + $startPath = str_replace('\\', '/', $startPath); + } + + $splitDriveLetter = fn ($path) => (\strlen($path) > 2 && ':' === $path[1] && '/' === $path[2] && ctype_alpha($path[0])) + ? [substr($path, 2), strtoupper($path[0])] + : [$path, null]; + + $splitPath = function ($path) { + $result = []; + + foreach (explode('/', trim($path, '/')) as $segment) { + if ('..' === $segment) { + array_pop($result); + } elseif ('.' !== $segment && '' !== $segment) { + $result[] = $segment; + } + } + + return $result; + }; + + [$endPath, $endDriveLetter] = $splitDriveLetter($endPath); + [$startPath, $startDriveLetter] = $splitDriveLetter($startPath); + + $startPathArr = $splitPath($startPath); + $endPathArr = $splitPath($endPath); + + if ($endDriveLetter && $startDriveLetter && $endDriveLetter != $startDriveLetter) { + // End path is on another drive, so no relative path exists + return $endDriveLetter.':/'.($endPathArr ? implode('/', $endPathArr).'/' : ''); + } + + // Find for which directory the common path stops + $index = 0; + while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) { + ++$index; + } + + // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels) + if (1 === \count($startPathArr) && '' === $startPathArr[0]) { + $depth = 0; + } else { + $depth = \count($startPathArr) - $index; + } + + // Repeated "../" for each level need to reach the common path + $traverser = str_repeat('../', $depth); + + $endPathRemainder = implode('/', \array_slice($endPathArr, $index)); + + // Construct $endPath from traversing to the common path, then to the remaining $endPath + $relativePath = $traverser.('' !== $endPathRemainder ? $endPathRemainder.'/' : ''); + + return '' === $relativePath ? './' : $relativePath; + } + + /** + * Mirrors a directory to another. + * + * Copies files and directories from the origin directory into the target directory. By default: + * + * - existing files in the target directory will be overwritten, except if they are newer (see the `override` option) + * - files in the target directory that do not exist in the source directory will not be deleted (see the `delete` option) + * + * @param \Traversable|null $iterator Iterator that filters which files and directories to copy, if null a recursive iterator is created + * @param array $options An array of boolean options + * Valid options are: + * - $options['override'] If true, target files newer than origin files are overwritten (see copy(), defaults to false) + * - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink(), defaults to false) + * - $options['delete'] Whether to delete files that are not in the source directory (defaults to false) + * + * @throws IOException When file type is unknown + */ + public function mirror(string $originDir, string $targetDir, \Traversable $iterator = null, array $options = []): void + { + $targetDir = rtrim($targetDir, '/\\'); + $originDir = rtrim($originDir, '/\\'); + $originDirLen = \strlen($originDir); + + if (!$this->exists($originDir)) { + throw new IOException(sprintf('The origin directory specified "%s" was not found.', $originDir), 0, null, $originDir); + } + + // Iterate in destination folder to remove obsolete entries + if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) { + $deleteIterator = $iterator; + if (null === $deleteIterator) { + $flags = \FilesystemIterator::SKIP_DOTS; + $deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST); + } + $targetDirLen = \strlen($targetDir); + foreach ($deleteIterator as $file) { + $origin = $originDir.substr($file->getPathname(), $targetDirLen); + if (!$this->exists($origin)) { + $this->remove($file); + } + } + } + + $copyOnWindows = $options['copy_on_windows'] ?? false; + + if (null === $iterator) { + $flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS; + $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST); + } + + $this->mkdir($targetDir); + $filesCreatedWhileMirroring = []; + + foreach ($iterator as $file) { + if ($file->getPathname() === $targetDir || $file->getRealPath() === $targetDir || isset($filesCreatedWhileMirroring[$file->getRealPath()])) { + continue; + } + + $target = $targetDir.substr($file->getPathname(), $originDirLen); + $filesCreatedWhileMirroring[$target] = true; + + if (!$copyOnWindows && is_link($file)) { + $this->symlink($file->getLinkTarget(), $target); + } elseif (is_dir($file)) { + $this->mkdir($target); + } elseif (is_file($file)) { + $this->copy($file, $target, $options['override'] ?? false); + } else { + throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file); + } + } + } + + /** + * Returns whether the file path is an absolute path. + */ + public function isAbsolutePath(string $file): bool + { + return '' !== $file && (strspn($file, '/\\', 0, 1) + || (\strlen($file) > 3 && ctype_alpha($file[0]) + && ':' === $file[1] + && strspn($file, '/\\', 2, 1) + ) + || null !== parse_url($file, \PHP_URL_SCHEME) + ); + } + + /** + * Creates a temporary file with support for custom stream wrappers. + * + * @param string $prefix The prefix of the generated temporary filename + * Note: Windows uses only the first three characters of prefix + * @param string $suffix The suffix of the generated temporary filename + * + * @return string The new temporary filename (with path), or throw an exception on failure + */ + public function tempnam(string $dir, string $prefix, string $suffix = ''): string + { + [$scheme, $hierarchy] = $this->getSchemeAndHierarchy($dir); + + // If no scheme or scheme is "file" or "gs" (Google Cloud) create temp file in local filesystem + if ((null === $scheme || 'file' === $scheme || 'gs' === $scheme) && '' === $suffix) { + // If tempnam failed or no scheme return the filename otherwise prepend the scheme + if ($tmpFile = self::box('tempnam', $hierarchy, $prefix)) { + if (null !== $scheme && 'gs' !== $scheme) { + return $scheme.'://'.$tmpFile; + } + + return $tmpFile; + } + + throw new IOException('A temporary file could not be created: '.self::$lastError); + } + + // Loop until we create a valid temp file or have reached 10 attempts + for ($i = 0; $i < 10; ++$i) { + // Create a unique filename + $tmpFile = $dir.'/'.$prefix.uniqid(mt_rand(), true).$suffix; + + // Use fopen instead of file_exists as some streams do not support stat + // Use mode 'x+' to atomically check existence and create to avoid a TOCTOU vulnerability + if (!$handle = self::box('fopen', $tmpFile, 'x+')) { + continue; + } + + // Close the file if it was successfully opened + self::box('fclose', $handle); + + return $tmpFile; + } + + throw new IOException('A temporary file could not be created: '.self::$lastError); + } + + /** + * Atomically dumps content into a file. + * + * @param string|resource $content The data to write into the file + * + * @throws IOException if the file cannot be written to + */ + public function dumpFile(string $filename, $content): void + { + if (\is_array($content)) { + throw new \TypeError(sprintf('Argument 2 passed to "%s()" must be string or resource, array given.', __METHOD__)); + } + + $dir = \dirname($filename); + + if (is_link($filename) && $linkTarget = $this->readlink($filename)) { + $this->dumpFile(Path::makeAbsolute($linkTarget, $dir), $content); + + return; + } + + if (!is_dir($dir)) { + $this->mkdir($dir); + } + + // Will create a temp file with 0600 access rights + // when the filesystem supports chmod. + $tmpFile = $this->tempnam($dir, basename($filename)); + + try { + if (false === self::box('file_put_contents', $tmpFile, $content)) { + throw new IOException(sprintf('Failed to write file "%s": ', $filename).self::$lastError, 0, null, $filename); + } + + self::box('chmod', $tmpFile, file_exists($filename) ? fileperms($filename) : 0666 & ~umask()); + + $this->rename($tmpFile, $filename, true); + } finally { + if (file_exists($tmpFile)) { + self::box('unlink', $tmpFile); + } + } + } + + /** + * Appends content to an existing file. + * + * @param string|resource $content The content to append + * @param bool $lock Whether the file should be locked when writing to it + * + * @throws IOException If the file is not writable + */ + public function appendToFile(string $filename, $content, bool $lock = false): void + { + if (\is_array($content)) { + throw new \TypeError(sprintf('Argument 2 passed to "%s()" must be string or resource, array given.', __METHOD__)); + } + + $dir = \dirname($filename); + + if (!is_dir($dir)) { + $this->mkdir($dir); + } + + if (false === self::box('file_put_contents', $filename, $content, \FILE_APPEND | ($lock ? \LOCK_EX : 0))) { + throw new IOException(sprintf('Failed to write file "%s": ', $filename).self::$lastError, 0, null, $filename); + } + } + + private function toIterable(string|iterable $files): iterable + { + return is_iterable($files) ? $files : [$files]; + } + + /** + * Gets a 2-tuple of scheme (may be null) and hierarchical part of a filename (e.g. file:///tmp -> [file, tmp]). + */ + private function getSchemeAndHierarchy(string $filename): array + { + $components = explode('://', $filename, 2); + + return 2 === \count($components) ? [$components[0], $components[1]] : [null, $components[0]]; + } + + private static function assertFunctionExists(string $func): void + { + if (!\function_exists($func)) { + throw new IOException(sprintf('Unable to perform filesystem operation because the "%s()" function has been disabled.', $func)); + } + } + + private static function box(string $func, mixed ...$args): mixed + { + self::assertFunctionExists($func); + + self::$lastError = null; + set_error_handler(self::handleError(...)); + try { + return $func(...$args); + } finally { + restore_error_handler(); + } + } + + /** + * @internal + */ + public static function handleError(int $type, string $msg): void + { + self::$lastError = $msg; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/filesystem/LICENSE b/tools/php-cs-fixer/vendor/symfony/filesystem/LICENSE new file mode 100644 index 00000000..0138f8f0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/filesystem/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/filesystem/Path.php b/tools/php-cs-fixer/vendor/symfony/filesystem/Path.php new file mode 100644 index 00000000..66439623 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/filesystem/Path.php @@ -0,0 +1,816 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Filesystem; + +use Symfony\Component\Filesystem\Exception\InvalidArgumentException; +use Symfony\Component\Filesystem\Exception\RuntimeException; + +/** + * Contains utility methods for handling path strings. + * + * The methods in this class are able to deal with both UNIX and Windows paths + * with both forward and backward slashes. All methods return normalized parts + * containing only forward slashes and no excess "." and ".." segments. + * + * @author Bernhard Schussek + * @author Thomas Schulz + * @author Théo Fidry + */ +final class Path +{ + /** + * The number of buffer entries that triggers a cleanup operation. + */ + private const CLEANUP_THRESHOLD = 1250; + + /** + * The buffer size after the cleanup operation. + */ + private const CLEANUP_SIZE = 1000; + + /** + * Buffers input/output of {@link canonicalize()}. + * + * @var array + */ + private static array $buffer = []; + + private static int $bufferSize = 0; + + /** + * Canonicalizes the given path. + * + * During normalization, all slashes are replaced by forward slashes ("/"). + * Furthermore, all "." and ".." segments are removed as far as possible. + * ".." segments at the beginning of relative paths are not removed. + * + * ```php + * echo Path::canonicalize("\symfony\puli\..\css\style.css"); + * // => /symfony/css/style.css + * + * echo Path::canonicalize("../css/./style.css"); + * // => ../css/style.css + * ``` + * + * This method is able to deal with both UNIX and Windows paths. + */ + public static function canonicalize(string $path): string + { + if ('' === $path) { + return ''; + } + + // This method is called by many other methods in this class. Buffer + // the canonicalized paths to make up for the severe performance + // decrease. + if (isset(self::$buffer[$path])) { + return self::$buffer[$path]; + } + + // Replace "~" with user's home directory. + if ('~' === $path[0]) { + $path = self::getHomeDirectory().substr($path, 1); + } + + $path = self::normalize($path); + + [$root, $pathWithoutRoot] = self::split($path); + + $canonicalParts = self::findCanonicalParts($root, $pathWithoutRoot); + + // Add the root directory again + self::$buffer[$path] = $canonicalPath = $root.implode('/', $canonicalParts); + ++self::$bufferSize; + + // Clean up regularly to prevent memory leaks + if (self::$bufferSize > self::CLEANUP_THRESHOLD) { + self::$buffer = \array_slice(self::$buffer, -self::CLEANUP_SIZE, null, true); + self::$bufferSize = self::CLEANUP_SIZE; + } + + return $canonicalPath; + } + + /** + * Normalizes the given path. + * + * During normalization, all slashes are replaced by forward slashes ("/"). + * Contrary to {@link canonicalize()}, this method does not remove invalid + * or dot path segments. Consequently, it is much more efficient and should + * be used whenever the given path is known to be a valid, absolute system + * path. + * + * This method is able to deal with both UNIX and Windows paths. + */ + public static function normalize(string $path): string + { + return str_replace('\\', '/', $path); + } + + /** + * Returns the directory part of the path. + * + * This method is similar to PHP's dirname(), but handles various cases + * where dirname() returns a weird result: + * + * - dirname() does not accept backslashes on UNIX + * - dirname("C:/symfony") returns "C:", not "C:/" + * - dirname("C:/") returns ".", not "C:/" + * - dirname("C:") returns ".", not "C:/" + * - dirname("symfony") returns ".", not "" + * - dirname() does not canonicalize the result + * + * This method fixes these shortcomings and behaves like dirname() + * otherwise. + * + * The result is a canonical path. + * + * @return string The canonical directory part. Returns the root directory + * if the root directory is passed. Returns an empty string + * if a relative path is passed that contains no slashes. + * Returns an empty string if an empty string is passed. + */ + public static function getDirectory(string $path): string + { + if ('' === $path) { + return ''; + } + + $path = self::canonicalize($path); + + // Maintain scheme + if (false !== $schemeSeparatorPosition = strpos($path, '://')) { + $scheme = substr($path, 0, $schemeSeparatorPosition + 3); + $path = substr($path, $schemeSeparatorPosition + 3); + } else { + $scheme = ''; + } + + if (false === $dirSeparatorPosition = strrpos($path, '/')) { + return ''; + } + + // Directory equals root directory "/" + if (0 === $dirSeparatorPosition) { + return $scheme.'/'; + } + + // Directory equals Windows root "C:/" + if (2 === $dirSeparatorPosition && ctype_alpha($path[0]) && ':' === $path[1]) { + return $scheme.substr($path, 0, 3); + } + + return $scheme.substr($path, 0, $dirSeparatorPosition); + } + + /** + * Returns canonical path of the user's home directory. + * + * Supported operating systems: + * + * - UNIX + * - Windows8 and upper + * + * If your operating system or environment isn't supported, an exception is thrown. + * + * The result is a canonical path. + * + * @throws RuntimeException If your operating system or environment isn't supported + */ + public static function getHomeDirectory(): string + { + // For UNIX support + if (getenv('HOME')) { + return self::canonicalize(getenv('HOME')); + } + + // For >= Windows8 support + if (getenv('HOMEDRIVE') && getenv('HOMEPATH')) { + return self::canonicalize(getenv('HOMEDRIVE').getenv('HOMEPATH')); + } + + throw new RuntimeException("Cannot find the home directory path: Your environment or operating system isn't supported."); + } + + /** + * Returns the root directory of a path. + * + * The result is a canonical path. + * + * @return string The canonical root directory. Returns an empty string if + * the given path is relative or empty. + */ + public static function getRoot(string $path): string + { + if ('' === $path) { + return ''; + } + + // Maintain scheme + if (false !== $schemeSeparatorPosition = strpos($path, '://')) { + $scheme = substr($path, 0, $schemeSeparatorPosition + 3); + $path = substr($path, $schemeSeparatorPosition + 3); + } else { + $scheme = ''; + } + + $firstCharacter = $path[0]; + + // UNIX root "/" or "\" (Windows style) + if ('/' === $firstCharacter || '\\' === $firstCharacter) { + return $scheme.'/'; + } + + $length = \strlen($path); + + // Windows root + if ($length > 1 && ':' === $path[1] && ctype_alpha($firstCharacter)) { + // Special case: "C:" + if (2 === $length) { + return $scheme.$path.'/'; + } + + // Normal case: "C:/ or "C:\" + if ('/' === $path[2] || '\\' === $path[2]) { + return $scheme.$firstCharacter.$path[1].'/'; + } + } + + return ''; + } + + /** + * Returns the file name without the extension from a file path. + * + * @param string|null $extension if specified, only that extension is cut + * off (may contain leading dot) + */ + public static function getFilenameWithoutExtension(string $path, string $extension = null): string + { + if ('' === $path) { + return ''; + } + + if (null !== $extension) { + // remove extension and trailing dot + return rtrim(basename($path, $extension), '.'); + } + + return pathinfo($path, \PATHINFO_FILENAME); + } + + /** + * Returns the extension from a file path (without leading dot). + * + * @param bool $forceLowerCase forces the extension to be lower-case + */ + public static function getExtension(string $path, bool $forceLowerCase = false): string + { + if ('' === $path) { + return ''; + } + + $extension = pathinfo($path, \PATHINFO_EXTENSION); + + if ($forceLowerCase) { + $extension = self::toLower($extension); + } + + return $extension; + } + + /** + * Returns whether the path has an (or the specified) extension. + * + * @param string $path the path string + * @param string|string[]|null $extensions if null or not provided, checks if + * an extension exists, otherwise + * checks for the specified extension + * or array of extensions (with or + * without leading dot) + * @param bool $ignoreCase whether to ignore case-sensitivity + */ + public static function hasExtension(string $path, $extensions = null, bool $ignoreCase = false): bool + { + if ('' === $path) { + return false; + } + + $actualExtension = self::getExtension($path, $ignoreCase); + + // Only check if path has any extension + if ([] === $extensions || null === $extensions) { + return '' !== $actualExtension; + } + + if (\is_string($extensions)) { + $extensions = [$extensions]; + } + + foreach ($extensions as $key => $extension) { + if ($ignoreCase) { + $extension = self::toLower($extension); + } + + // remove leading '.' in extensions array + $extensions[$key] = ltrim($extension, '.'); + } + + return \in_array($actualExtension, $extensions, true); + } + + /** + * Changes the extension of a path string. + * + * @param string $path The path string with filename.ext to change. + * @param string $extension new extension (with or without leading dot) + * + * @return string the path string with new file extension + */ + public static function changeExtension(string $path, string $extension): string + { + if ('' === $path) { + return ''; + } + + $actualExtension = self::getExtension($path); + $extension = ltrim($extension, '.'); + + // No extension for paths + if ('/' === substr($path, -1)) { + return $path; + } + + // No actual extension in path + if (empty($actualExtension)) { + return $path.('.' === substr($path, -1) ? '' : '.').$extension; + } + + return substr($path, 0, -\strlen($actualExtension)).$extension; + } + + public static function isAbsolute(string $path): bool + { + if ('' === $path) { + return false; + } + + // Strip scheme + if (false !== $schemeSeparatorPosition = strpos($path, '://')) { + $path = substr($path, $schemeSeparatorPosition + 3); + } + + $firstCharacter = $path[0]; + + // UNIX root "/" or "\" (Windows style) + if ('/' === $firstCharacter || '\\' === $firstCharacter) { + return true; + } + + // Windows root + if (\strlen($path) > 1 && ctype_alpha($firstCharacter) && ':' === $path[1]) { + // Special case: "C:" + if (2 === \strlen($path)) { + return true; + } + + // Normal case: "C:/ or "C:\" + if ('/' === $path[2] || '\\' === $path[2]) { + return true; + } + } + + return false; + } + + public static function isRelative(string $path): bool + { + return !self::isAbsolute($path); + } + + /** + * Turns a relative path into an absolute path in canonical form. + * + * Usually, the relative path is appended to the given base path. Dot + * segments ("." and "..") are removed/collapsed and all slashes turned + * into forward slashes. + * + * ```php + * echo Path::makeAbsolute("../style.css", "/symfony/puli/css"); + * // => /symfony/puli/style.css + * ``` + * + * If an absolute path is passed, that path is returned unless its root + * directory is different than the one of the base path. In that case, an + * exception is thrown. + * + * ```php + * Path::makeAbsolute("/style.css", "/symfony/puli/css"); + * // => /style.css + * + * Path::makeAbsolute("C:/style.css", "C:/symfony/puli/css"); + * // => C:/style.css + * + * Path::makeAbsolute("C:/style.css", "/symfony/puli/css"); + * // InvalidArgumentException + * ``` + * + * If the base path is not an absolute path, an exception is thrown. + * + * The result is a canonical path. + * + * @param string $basePath an absolute base path + * + * @throws InvalidArgumentException if the base path is not absolute or if + * the given path is an absolute path with + * a different root than the base path + */ + public static function makeAbsolute(string $path, string $basePath): string + { + if ('' === $basePath) { + throw new InvalidArgumentException(sprintf('The base path must be a non-empty string. Got: "%s".', $basePath)); + } + + if (!self::isAbsolute($basePath)) { + throw new InvalidArgumentException(sprintf('The base path "%s" is not an absolute path.', $basePath)); + } + + if (self::isAbsolute($path)) { + return self::canonicalize($path); + } + + if (false !== $schemeSeparatorPosition = strpos($basePath, '://')) { + $scheme = substr($basePath, 0, $schemeSeparatorPosition + 3); + $basePath = substr($basePath, $schemeSeparatorPosition + 3); + } else { + $scheme = ''; + } + + return $scheme.self::canonicalize(rtrim($basePath, '/\\').'/'.$path); + } + + /** + * Turns a path into a relative path. + * + * The relative path is created relative to the given base path: + * + * ```php + * echo Path::makeRelative("/symfony/style.css", "/symfony/puli"); + * // => ../style.css + * ``` + * + * If a relative path is passed and the base path is absolute, the relative + * path is returned unchanged: + * + * ```php + * Path::makeRelative("style.css", "/symfony/puli/css"); + * // => style.css + * ``` + * + * If both paths are relative, the relative path is created with the + * assumption that both paths are relative to the same directory: + * + * ```php + * Path::makeRelative("style.css", "symfony/puli/css"); + * // => ../../../style.css + * ``` + * + * If both paths are absolute, their root directory must be the same, + * otherwise an exception is thrown: + * + * ```php + * Path::makeRelative("C:/symfony/style.css", "/symfony/puli"); + * // InvalidArgumentException + * ``` + * + * If the passed path is absolute, but the base path is not, an exception + * is thrown as well: + * + * ```php + * Path::makeRelative("/symfony/style.css", "symfony/puli"); + * // InvalidArgumentException + * ``` + * + * If the base path is not an absolute path, an exception is thrown. + * + * The result is a canonical path. + * + * @throws InvalidArgumentException if the base path is not absolute or if + * the given path has a different root + * than the base path + */ + public static function makeRelative(string $path, string $basePath): string + { + $path = self::canonicalize($path); + $basePath = self::canonicalize($basePath); + + [$root, $relativePath] = self::split($path); + [$baseRoot, $relativeBasePath] = self::split($basePath); + + // If the base path is given as absolute path and the path is already + // relative, consider it to be relative to the given absolute path + // already + if ('' === $root && '' !== $baseRoot) { + // If base path is already in its root + if ('' === $relativeBasePath) { + $relativePath = ltrim($relativePath, './\\'); + } + + return $relativePath; + } + + // If the passed path is absolute, but the base path is not, we + // cannot generate a relative path + if ('' !== $root && '' === $baseRoot) { + throw new InvalidArgumentException(sprintf('The absolute path "%s" cannot be made relative to the relative path "%s". You should provide an absolute base path instead.', $path, $basePath)); + } + + // Fail if the roots of the two paths are different + if ($baseRoot && $root !== $baseRoot) { + throw new InvalidArgumentException(sprintf('The path "%s" cannot be made relative to "%s", because they have different roots ("%s" and "%s").', $path, $basePath, $root, $baseRoot)); + } + + if ('' === $relativeBasePath) { + return $relativePath; + } + + // Build a "../../" prefix with as many "../" parts as necessary + $parts = explode('/', $relativePath); + $baseParts = explode('/', $relativeBasePath); + $dotDotPrefix = ''; + + // Once we found a non-matching part in the prefix, we need to add + // "../" parts for all remaining parts + $match = true; + + foreach ($baseParts as $index => $basePart) { + if ($match && isset($parts[$index]) && $basePart === $parts[$index]) { + unset($parts[$index]); + + continue; + } + + $match = false; + $dotDotPrefix .= '../'; + } + + return rtrim($dotDotPrefix.implode('/', $parts), '/'); + } + + /** + * Returns whether the given path is on the local filesystem. + */ + public static function isLocal(string $path): bool + { + return '' !== $path && !str_contains($path, '://'); + } + + /** + * Returns the longest common base path in canonical form of a set of paths or + * `null` if the paths are on different Windows partitions. + * + * Dot segments ("." and "..") are removed/collapsed and all slashes turned + * into forward slashes. + * + * ```php + * $basePath = Path::getLongestCommonBasePath( + * '/symfony/css/style.css', + * '/symfony/css/..' + * ); + * // => /symfony + * ``` + * + * The root is returned if no common base path can be found: + * + * ```php + * $basePath = Path::getLongestCommonBasePath( + * '/symfony/css/style.css', + * '/puli/css/..' + * ); + * // => / + * ``` + * + * If the paths are located on different Windows partitions, `null` is + * returned. + * + * ```php + * $basePath = Path::getLongestCommonBasePath( + * 'C:/symfony/css/style.css', + * 'D:/symfony/css/..' + * ); + * // => null + * ``` + */ + public static function getLongestCommonBasePath(string ...$paths): ?string + { + [$bpRoot, $basePath] = self::split(self::canonicalize(reset($paths))); + + for (next($paths); null !== key($paths) && '' !== $basePath; next($paths)) { + [$root, $path] = self::split(self::canonicalize(current($paths))); + + // If we deal with different roots (e.g. C:/ vs. D:/), it's time + // to quit + if ($root !== $bpRoot) { + return null; + } + + // Make the base path shorter until it fits into path + while (true) { + if ('.' === $basePath) { + // No more base paths + $basePath = ''; + + // next path + continue 2; + } + + // Prevent false positives for common prefixes + // see isBasePath() + if (str_starts_with($path.'/', $basePath.'/')) { + // next path + continue 2; + } + + $basePath = \dirname($basePath); + } + } + + return $bpRoot.$basePath; + } + + /** + * Joins two or more path strings into a canonical path. + */ + public static function join(string ...$paths): string + { + $finalPath = null; + $wasScheme = false; + + foreach ($paths as $path) { + if ('' === $path) { + continue; + } + + if (null === $finalPath) { + // For first part we keep slashes, like '/top', 'C:\' or 'phar://' + $finalPath = $path; + $wasScheme = str_contains($path, '://'); + continue; + } + + // Only add slash if previous part didn't end with '/' or '\' + if (!\in_array(substr($finalPath, -1), ['/', '\\'])) { + $finalPath .= '/'; + } + + // If first part included a scheme like 'phar://' we allow \current part to start with '/', otherwise trim + $finalPath .= $wasScheme ? $path : ltrim($path, '/'); + $wasScheme = false; + } + + if (null === $finalPath) { + return ''; + } + + return self::canonicalize($finalPath); + } + + /** + * Returns whether a path is a base path of another path. + * + * Dot segments ("." and "..") are removed/collapsed and all slashes turned + * into forward slashes. + * + * ```php + * Path::isBasePath('/symfony', '/symfony/css'); + * // => true + * + * Path::isBasePath('/symfony', '/symfony'); + * // => true + * + * Path::isBasePath('/symfony', '/symfony/..'); + * // => false + * + * Path::isBasePath('/symfony', '/puli'); + * // => false + * ``` + */ + public static function isBasePath(string $basePath, string $ofPath): bool + { + $basePath = self::canonicalize($basePath); + $ofPath = self::canonicalize($ofPath); + + // Append slashes to prevent false positives when two paths have + // a common prefix, for example /base/foo and /base/foobar. + // Don't append a slash for the root "/", because then that root + // won't be discovered as common prefix ("//" is not a prefix of + // "/foobar/"). + return str_starts_with($ofPath.'/', rtrim($basePath, '/').'/'); + } + + /** + * @return string[] + */ + private static function findCanonicalParts(string $root, string $pathWithoutRoot): array + { + $parts = explode('/', $pathWithoutRoot); + + $canonicalParts = []; + + // Collapse "." and "..", if possible + foreach ($parts as $part) { + if ('.' === $part || '' === $part) { + continue; + } + + // Collapse ".." with the previous part, if one exists + // Don't collapse ".." if the previous part is also ".." + if ('..' === $part && \count($canonicalParts) > 0 && '..' !== $canonicalParts[\count($canonicalParts) - 1]) { + array_pop($canonicalParts); + + continue; + } + + // Only add ".." prefixes for relative paths + if ('..' !== $part || '' === $root) { + $canonicalParts[] = $part; + } + } + + return $canonicalParts; + } + + /** + * Splits a canonical path into its root directory and the remainder. + * + * If the path has no root directory, an empty root directory will be + * returned. + * + * If the root directory is a Windows style partition, the resulting root + * will always contain a trailing slash. + * + * list ($root, $path) = Path::split("C:/symfony") + * // => ["C:/", "symfony"] + * + * list ($root, $path) = Path::split("C:") + * // => ["C:/", ""] + * + * @return array{string, string} an array with the root directory and the remaining relative path + */ + private static function split(string $path): array + { + if ('' === $path) { + return ['', '']; + } + + // Remember scheme as part of the root, if any + if (false !== $schemeSeparatorPosition = strpos($path, '://')) { + $root = substr($path, 0, $schemeSeparatorPosition + 3); + $path = substr($path, $schemeSeparatorPosition + 3); + } else { + $root = ''; + } + + $length = \strlen($path); + + // Remove and remember root directory + if (str_starts_with($path, '/')) { + $root .= '/'; + $path = $length > 1 ? substr($path, 1) : ''; + } elseif ($length > 1 && ctype_alpha($path[0]) && ':' === $path[1]) { + if (2 === $length) { + // Windows special case: "C:" + $root .= $path.'/'; + $path = ''; + } elseif ('/' === $path[2]) { + // Windows normal case: "C:/".. + $root .= substr($path, 0, 3); + $path = $length > 3 ? substr($path, 3) : ''; + } + } + + return [$root, $path]; + } + + private static function toLower(string $string): string + { + if (false !== $encoding = mb_detect_encoding($string, null, true)) { + return mb_strtolower($string, $encoding); + } + + return strtolower($string); + } + + private function __construct() + { + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/filesystem/README.md b/tools/php-cs-fixer/vendor/symfony/filesystem/README.md new file mode 100644 index 00000000..f2f6d45f --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/filesystem/README.md @@ -0,0 +1,13 @@ +Filesystem Component +==================== + +The Filesystem component provides basic utilities for the filesystem. + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/filesystem.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/tools/php-cs-fixer/vendor/symfony/filesystem/composer.json b/tools/php-cs-fixer/vendor/symfony/filesystem/composer.json new file mode 100644 index 00000000..1e054b68 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/filesystem/composer.json @@ -0,0 +1,30 @@ +{ + "name": "symfony/filesystem", + "type": "library", + "description": "Provides basic utilities for the filesystem", + "keywords": [], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.2", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-mbstring": "~1.8" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\Filesystem\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/CHANGELOG.md b/tools/php-cs-fixer/vendor/symfony/finder/CHANGELOG.md new file mode 100644 index 00000000..e8383024 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/CHANGELOG.md @@ -0,0 +1,103 @@ +CHANGELOG +========= + +6.4 +--- + + * Add early directory pruning to `Finder::filter()` + +6.2 +--- + + * Add `Finder::sortByExtension()` and `Finder::sortBySize()` + * Add `Finder::sortByCaseInsensitiveName()` to sort by name with case insensitive sorting methods + +6.0 +--- + + * Remove `Comparator::setTarget()` and `Comparator::setOperator()` + +5.4.0 +----- + + * Deprecate `Comparator::setTarget()` and `Comparator::setOperator()` + * Add a constructor to `Comparator` that allows setting target and operator + * Finder's iterator has now `Symfony\Component\Finder\SplFileInfo` inner type specified + * Add recursive .gitignore files support + +5.0.0 +----- + + * added `$useNaturalSort` argument to `Finder::sortByName()` + +4.3.0 +----- + + * added Finder::ignoreVCSIgnored() to ignore files based on rules listed in .gitignore + +4.2.0 +----- + + * added $useNaturalSort option to Finder::sortByName() method + * the `Finder::sortByName()` method will have a new `$useNaturalSort` + argument in version 5.0, not defining it is deprecated + * added `Finder::reverseSorting()` to reverse the sorting + +4.0.0 +----- + + * removed `ExceptionInterface` + * removed `Symfony\Component\Finder\Iterator\FilterIterator` + +3.4.0 +----- + + * deprecated `Symfony\Component\Finder\Iterator\FilterIterator` + * added Finder::hasResults() method to check if any results were found + +3.3.0 +----- + + * added double-star matching to Glob::toRegex() + +3.0.0 +----- + + * removed deprecated classes + +2.8.0 +----- + + * deprecated adapters and related classes + +2.5.0 +----- + * added support for GLOB_BRACE in the paths passed to Finder::in() + +2.3.0 +----- + + * added a way to ignore unreadable directories (via Finder::ignoreUnreadableDirs()) + * unified the way subfolders that are not executable are handled by always throwing an AccessDeniedException exception + +2.2.0 +----- + + * added Finder::path() and Finder::notPath() methods + * added finder adapters to improve performance on specific platforms + * added support for wildcard characters (glob patterns) in the paths passed + to Finder::in() + +2.1.0 +----- + + * added Finder::sortByAccessedTime(), Finder::sortByChangedTime(), and + Finder::sortByModifiedTime() + * added Countable to Finder + * added support for an array of directories as an argument to + Finder::exclude() + * added searching based on the file content via Finder::contains() and + Finder::notContains() + * added support for the != operator in the Comparator + * [BC BREAK] filter expressions (used for file name and content) are no more + considered as regexps but glob patterns when they are enclosed in '*' or '?' diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Comparator/Comparator.php b/tools/php-cs-fixer/vendor/symfony/finder/Comparator/Comparator.php new file mode 100644 index 00000000..bd685834 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Comparator/Comparator.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Comparator; + +/** + * @author Fabien Potencier + */ +class Comparator +{ + private string $target; + private string $operator; + + public function __construct(string $target, string $operator = '==') + { + if (!\in_array($operator, ['>', '<', '>=', '<=', '==', '!='])) { + throw new \InvalidArgumentException(sprintf('Invalid operator "%s".', $operator)); + } + + $this->target = $target; + $this->operator = $operator; + } + + /** + * Gets the target value. + */ + public function getTarget(): string + { + return $this->target; + } + + /** + * Gets the comparison operator. + */ + public function getOperator(): string + { + return $this->operator; + } + + /** + * Tests against the target. + */ + public function test(mixed $test): bool + { + return match ($this->operator) { + '>' => $test > $this->target, + '>=' => $test >= $this->target, + '<' => $test < $this->target, + '<=' => $test <= $this->target, + '!=' => $test != $this->target, + default => $test == $this->target, + }; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Comparator/DateComparator.php b/tools/php-cs-fixer/vendor/symfony/finder/Comparator/DateComparator.php new file mode 100644 index 00000000..e0c523d0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Comparator/DateComparator.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Comparator; + +/** + * DateCompare compiles date comparisons. + * + * @author Fabien Potencier + */ +class DateComparator extends Comparator +{ + /** + * @param string $test A comparison string + * + * @throws \InvalidArgumentException If the test is not understood + */ + public function __construct(string $test) + { + if (!preg_match('#^\s*(==|!=|[<>]=?|after|since|before|until)?\s*(.+?)\s*$#i', $test, $matches)) { + throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a date test.', $test)); + } + + try { + $date = new \DateTimeImmutable($matches[2]); + $target = $date->format('U'); + } catch (\Exception) { + throw new \InvalidArgumentException(sprintf('"%s" is not a valid date.', $matches[2])); + } + + $operator = $matches[1] ?? '=='; + if ('since' === $operator || 'after' === $operator) { + $operator = '>'; + } + + if ('until' === $operator || 'before' === $operator) { + $operator = '<'; + } + + parent::__construct($target, $operator); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Comparator/NumberComparator.php b/tools/php-cs-fixer/vendor/symfony/finder/Comparator/NumberComparator.php new file mode 100644 index 00000000..dd308207 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Comparator/NumberComparator.php @@ -0,0 +1,78 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Comparator; + +/** + * NumberComparator compiles a simple comparison to an anonymous + * subroutine, which you can call with a value to be tested again. + * + * Now this would be very pointless, if NumberCompare didn't understand + * magnitudes. + * + * The target value may use magnitudes of kilobytes (k, ki), + * megabytes (m, mi), or gigabytes (g, gi). Those suffixed + * with an i use the appropriate 2**n version in accordance with the + * IEC standard: http://physics.nist.gov/cuu/Units/binary.html + * + * Based on the Perl Number::Compare module. + * + * @author Fabien Potencier PHP port + * @author Richard Clamp Perl version + * @copyright 2004-2005 Fabien Potencier + * @copyright 2002 Richard Clamp + * + * @see http://physics.nist.gov/cuu/Units/binary.html + */ +class NumberComparator extends Comparator +{ + /** + * @param string|null $test A comparison string or null + * + * @throws \InvalidArgumentException If the test is not understood + */ + public function __construct(?string $test) + { + if (null === $test || !preg_match('#^\s*(==|!=|[<>]=?)?\s*([0-9\.]+)\s*([kmg]i?)?\s*$#i', $test, $matches)) { + throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a number test.', $test ?? 'null')); + } + + $target = $matches[2]; + if (!is_numeric($target)) { + throw new \InvalidArgumentException(sprintf('Invalid number "%s".', $target)); + } + if (isset($matches[3])) { + // magnitude + switch (strtolower($matches[3])) { + case 'k': + $target *= 1000; + break; + case 'ki': + $target *= 1024; + break; + case 'm': + $target *= 1000000; + break; + case 'mi': + $target *= 1024 * 1024; + break; + case 'g': + $target *= 1000000000; + break; + case 'gi': + $target *= 1024 * 1024 * 1024; + break; + } + } + + parent::__construct($target, $matches[1] ?: '=='); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Exception/AccessDeniedException.php b/tools/php-cs-fixer/vendor/symfony/finder/Exception/AccessDeniedException.php new file mode 100644 index 00000000..ee195ea8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Exception/AccessDeniedException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Exception; + +/** + * @author Jean-François Simon + */ +class AccessDeniedException extends \UnexpectedValueException +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Exception/DirectoryNotFoundException.php b/tools/php-cs-fixer/vendor/symfony/finder/Exception/DirectoryNotFoundException.php new file mode 100644 index 00000000..c6cc0f27 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Exception/DirectoryNotFoundException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Exception; + +/** + * @author Andreas Erhard + */ +class DirectoryNotFoundException extends \InvalidArgumentException +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Finder.php b/tools/php-cs-fixer/vendor/symfony/finder/Finder.php new file mode 100644 index 00000000..d062a60a --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Finder.php @@ -0,0 +1,856 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder; + +use Symfony\Component\Finder\Comparator\DateComparator; +use Symfony\Component\Finder\Comparator\NumberComparator; +use Symfony\Component\Finder\Exception\DirectoryNotFoundException; +use Symfony\Component\Finder\Iterator\CustomFilterIterator; +use Symfony\Component\Finder\Iterator\DateRangeFilterIterator; +use Symfony\Component\Finder\Iterator\DepthRangeFilterIterator; +use Symfony\Component\Finder\Iterator\ExcludeDirectoryFilterIterator; +use Symfony\Component\Finder\Iterator\FilecontentFilterIterator; +use Symfony\Component\Finder\Iterator\FilenameFilterIterator; +use Symfony\Component\Finder\Iterator\LazyIterator; +use Symfony\Component\Finder\Iterator\SizeRangeFilterIterator; +use Symfony\Component\Finder\Iterator\SortableIterator; + +/** + * Finder allows to build rules to find files and directories. + * + * It is a thin wrapper around several specialized iterator classes. + * + * All rules may be invoked several times. + * + * All methods return the current Finder object to allow chaining: + * + * $finder = Finder::create()->files()->name('*.php')->in(__DIR__); + * + * @author Fabien Potencier + * + * @implements \IteratorAggregate + */ +class Finder implements \IteratorAggregate, \Countable +{ + public const IGNORE_VCS_FILES = 1; + public const IGNORE_DOT_FILES = 2; + public const IGNORE_VCS_IGNORED_FILES = 4; + + private int $mode = 0; + private array $names = []; + private array $notNames = []; + private array $exclude = []; + private array $filters = []; + private array $pruneFilters = []; + private array $depths = []; + private array $sizes = []; + private bool $followLinks = false; + private bool $reverseSorting = false; + private \Closure|int|false $sort = false; + private int $ignore = 0; + private array $dirs = []; + private array $dates = []; + private array $iterators = []; + private array $contains = []; + private array $notContains = []; + private array $paths = []; + private array $notPaths = []; + private bool $ignoreUnreadableDirs = false; + + private static array $vcsPatterns = ['.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg']; + + public function __construct() + { + $this->ignore = static::IGNORE_VCS_FILES | static::IGNORE_DOT_FILES; + } + + /** + * Creates a new Finder. + */ + public static function create(): static + { + return new static(); + } + + /** + * Restricts the matching to directories only. + * + * @return $this + */ + public function directories(): static + { + $this->mode = Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES; + + return $this; + } + + /** + * Restricts the matching to files only. + * + * @return $this + */ + public function files(): static + { + $this->mode = Iterator\FileTypeFilterIterator::ONLY_FILES; + + return $this; + } + + /** + * Adds tests for the directory depth. + * + * Usage: + * + * $finder->depth('> 1') // the Finder will start matching at level 1. + * $finder->depth('< 3') // the Finder will descend at most 3 levels of directories below the starting point. + * $finder->depth(['>= 1', '< 3']) + * + * @param string|int|string[]|int[] $levels The depth level expression or an array of depth levels + * + * @return $this + * + * @see DepthRangeFilterIterator + * @see NumberComparator + */ + public function depth(string|int|array $levels): static + { + foreach ((array) $levels as $level) { + $this->depths[] = new Comparator\NumberComparator($level); + } + + return $this; + } + + /** + * Adds tests for file dates (last modified). + * + * The date must be something that strtotime() is able to parse: + * + * $finder->date('since yesterday'); + * $finder->date('until 2 days ago'); + * $finder->date('> now - 2 hours'); + * $finder->date('>= 2005-10-15'); + * $finder->date(['>= 2005-10-15', '<= 2006-05-27']); + * + * @param string|string[] $dates A date range string or an array of date ranges + * + * @return $this + * + * @see strtotime + * @see DateRangeFilterIterator + * @see DateComparator + */ + public function date(string|array $dates): static + { + foreach ((array) $dates as $date) { + $this->dates[] = new Comparator\DateComparator($date); + } + + return $this; + } + + /** + * Adds rules that files must match. + * + * You can use patterns (delimited with / sign), globs or simple strings. + * + * $finder->name('/\.php$/') + * $finder->name('*.php') // same as above, without dot files + * $finder->name('test.php') + * $finder->name(['test.py', 'test.php']) + * + * @param string|string[] $patterns A pattern (a regexp, a glob, or a string) or an array of patterns + * + * @return $this + * + * @see FilenameFilterIterator + */ + public function name(string|array $patterns): static + { + $this->names = array_merge($this->names, (array) $patterns); + + return $this; + } + + /** + * Adds rules that files must not match. + * + * @param string|string[] $patterns A pattern (a regexp, a glob, or a string) or an array of patterns + * + * @return $this + * + * @see FilenameFilterIterator + */ + public function notName(string|array $patterns): static + { + $this->notNames = array_merge($this->notNames, (array) $patterns); + + return $this; + } + + /** + * Adds tests that file contents must match. + * + * Strings or PCRE patterns can be used: + * + * $finder->contains('Lorem ipsum') + * $finder->contains('/Lorem ipsum/i') + * $finder->contains(['dolor', '/ipsum/i']) + * + * @param string|string[] $patterns A pattern (string or regexp) or an array of patterns + * + * @return $this + * + * @see FilecontentFilterIterator + */ + public function contains(string|array $patterns): static + { + $this->contains = array_merge($this->contains, (array) $patterns); + + return $this; + } + + /** + * Adds tests that file contents must not match. + * + * Strings or PCRE patterns can be used: + * + * $finder->notContains('Lorem ipsum') + * $finder->notContains('/Lorem ipsum/i') + * $finder->notContains(['lorem', '/dolor/i']) + * + * @param string|string[] $patterns A pattern (string or regexp) or an array of patterns + * + * @return $this + * + * @see FilecontentFilterIterator + */ + public function notContains(string|array $patterns): static + { + $this->notContains = array_merge($this->notContains, (array) $patterns); + + return $this; + } + + /** + * Adds rules that filenames must match. + * + * You can use patterns (delimited with / sign) or simple strings. + * + * $finder->path('some/special/dir') + * $finder->path('/some\/special\/dir/') // same as above + * $finder->path(['some dir', 'another/dir']) + * + * Use only / as dirname separator. + * + * @param string|string[] $patterns A pattern (a regexp or a string) or an array of patterns + * + * @return $this + * + * @see FilenameFilterIterator + */ + public function path(string|array $patterns): static + { + $this->paths = array_merge($this->paths, (array) $patterns); + + return $this; + } + + /** + * Adds rules that filenames must not match. + * + * You can use patterns (delimited with / sign) or simple strings. + * + * $finder->notPath('some/special/dir') + * $finder->notPath('/some\/special\/dir/') // same as above + * $finder->notPath(['some/file.txt', 'another/file.log']) + * + * Use only / as dirname separator. + * + * @param string|string[] $patterns A pattern (a regexp or a string) or an array of patterns + * + * @return $this + * + * @see FilenameFilterIterator + */ + public function notPath(string|array $patterns): static + { + $this->notPaths = array_merge($this->notPaths, (array) $patterns); + + return $this; + } + + /** + * Adds tests for file sizes. + * + * $finder->size('> 10K'); + * $finder->size('<= 1Ki'); + * $finder->size(4); + * $finder->size(['> 10K', '< 20K']) + * + * @param string|int|string[]|int[] $sizes A size range string or an integer or an array of size ranges + * + * @return $this + * + * @see SizeRangeFilterIterator + * @see NumberComparator + */ + public function size(string|int|array $sizes): static + { + foreach ((array) $sizes as $size) { + $this->sizes[] = new Comparator\NumberComparator($size); + } + + return $this; + } + + /** + * Excludes directories. + * + * Directories passed as argument must be relative to the ones defined with the `in()` method. For example: + * + * $finder->in(__DIR__)->exclude('ruby'); + * + * @param string|array $dirs A directory path or an array of directories + * + * @return $this + * + * @see ExcludeDirectoryFilterIterator + */ + public function exclude(string|array $dirs): static + { + $this->exclude = array_merge($this->exclude, (array) $dirs); + + return $this; + } + + /** + * Excludes "hidden" directories and files (starting with a dot). + * + * This option is enabled by default. + * + * @return $this + * + * @see ExcludeDirectoryFilterIterator + */ + public function ignoreDotFiles(bool $ignoreDotFiles): static + { + if ($ignoreDotFiles) { + $this->ignore |= static::IGNORE_DOT_FILES; + } else { + $this->ignore &= ~static::IGNORE_DOT_FILES; + } + + return $this; + } + + /** + * Forces the finder to ignore version control directories. + * + * This option is enabled by default. + * + * @return $this + * + * @see ExcludeDirectoryFilterIterator + */ + public function ignoreVCS(bool $ignoreVCS): static + { + if ($ignoreVCS) { + $this->ignore |= static::IGNORE_VCS_FILES; + } else { + $this->ignore &= ~static::IGNORE_VCS_FILES; + } + + return $this; + } + + /** + * Forces Finder to obey .gitignore and ignore files based on rules listed there. + * + * This option is disabled by default. + * + * @return $this + */ + public function ignoreVCSIgnored(bool $ignoreVCSIgnored): static + { + if ($ignoreVCSIgnored) { + $this->ignore |= static::IGNORE_VCS_IGNORED_FILES; + } else { + $this->ignore &= ~static::IGNORE_VCS_IGNORED_FILES; + } + + return $this; + } + + /** + * Adds VCS patterns. + * + * @see ignoreVCS() + * + * @param string|string[] $pattern VCS patterns to ignore + */ + public static function addVCSPattern(string|array $pattern): void + { + foreach ((array) $pattern as $p) { + self::$vcsPatterns[] = $p; + } + + self::$vcsPatterns = array_unique(self::$vcsPatterns); + } + + /** + * Sorts files and directories by an anonymous function. + * + * The anonymous function receives two \SplFileInfo instances to compare. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sort(\Closure $closure): static + { + $this->sort = $closure; + + return $this; + } + + /** + * Sorts files and directories by extension. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sortByExtension(): static + { + $this->sort = Iterator\SortableIterator::SORT_BY_EXTENSION; + + return $this; + } + + /** + * Sorts files and directories by name. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sortByName(bool $useNaturalSort = false): static + { + $this->sort = $useNaturalSort ? Iterator\SortableIterator::SORT_BY_NAME_NATURAL : Iterator\SortableIterator::SORT_BY_NAME; + + return $this; + } + + /** + * Sorts files and directories by name case insensitive. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sortByCaseInsensitiveName(bool $useNaturalSort = false): static + { + $this->sort = $useNaturalSort ? Iterator\SortableIterator::SORT_BY_NAME_NATURAL_CASE_INSENSITIVE : Iterator\SortableIterator::SORT_BY_NAME_CASE_INSENSITIVE; + + return $this; + } + + /** + * Sorts files and directories by size. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sortBySize(): static + { + $this->sort = Iterator\SortableIterator::SORT_BY_SIZE; + + return $this; + } + + /** + * Sorts files and directories by type (directories before files), then by name. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sortByType(): static + { + $this->sort = Iterator\SortableIterator::SORT_BY_TYPE; + + return $this; + } + + /** + * Sorts files and directories by the last accessed time. + * + * This is the time that the file was last accessed, read or written to. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sortByAccessedTime(): static + { + $this->sort = Iterator\SortableIterator::SORT_BY_ACCESSED_TIME; + + return $this; + } + + /** + * Reverses the sorting. + * + * @return $this + */ + public function reverseSorting(): static + { + $this->reverseSorting = true; + + return $this; + } + + /** + * Sorts files and directories by the last inode changed time. + * + * This is the time that the inode information was last modified (permissions, owner, group or other metadata). + * + * On Windows, since inode is not available, changed time is actually the file creation time. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sortByChangedTime(): static + { + $this->sort = Iterator\SortableIterator::SORT_BY_CHANGED_TIME; + + return $this; + } + + /** + * Sorts files and directories by the last modified time. + * + * This is the last time the actual contents of the file were last modified. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sortByModifiedTime(): static + { + $this->sort = Iterator\SortableIterator::SORT_BY_MODIFIED_TIME; + + return $this; + } + + /** + * Filters the iterator with an anonymous function. + * + * The anonymous function receives a \SplFileInfo and must return false + * to remove files. + * + * @param \Closure(SplFileInfo): bool $closure + * @param bool $prune Whether to skip traversing directories further + * + * @return $this + * + * @see CustomFilterIterator + */ + public function filter(\Closure $closure, bool $prune = false): static + { + $this->filters[] = $closure; + + if ($prune) { + $this->pruneFilters[] = $closure; + } + + return $this; + } + + /** + * Forces the following of symlinks. + * + * @return $this + */ + public function followLinks(): static + { + $this->followLinks = true; + + return $this; + } + + /** + * Tells finder to ignore unreadable directories. + * + * By default, scanning unreadable directories content throws an AccessDeniedException. + * + * @return $this + */ + public function ignoreUnreadableDirs(bool $ignore = true): static + { + $this->ignoreUnreadableDirs = $ignore; + + return $this; + } + + /** + * Searches files and directories which match defined rules. + * + * @param string|string[] $dirs A directory path or an array of directories + * + * @return $this + * + * @throws DirectoryNotFoundException if one of the directories does not exist + */ + public function in(string|array $dirs): static + { + $resolvedDirs = []; + + foreach ((array) $dirs as $dir) { + if (is_dir($dir)) { + $resolvedDirs[] = [$this->normalizeDir($dir)]; + } elseif ($glob = glob($dir, (\defined('GLOB_BRACE') ? \GLOB_BRACE : 0) | \GLOB_ONLYDIR | \GLOB_NOSORT)) { + sort($glob); + $resolvedDirs[] = array_map($this->normalizeDir(...), $glob); + } else { + throw new DirectoryNotFoundException(sprintf('The "%s" directory does not exist.', $dir)); + } + } + + $this->dirs = array_merge($this->dirs, ...$resolvedDirs); + + return $this; + } + + /** + * Returns an Iterator for the current Finder configuration. + * + * This method implements the IteratorAggregate interface. + * + * @return \Iterator + * + * @throws \LogicException if the in() method has not been called + */ + public function getIterator(): \Iterator + { + if (0 === \count($this->dirs) && 0 === \count($this->iterators)) { + throw new \LogicException('You must call one of in() or append() methods before iterating over a Finder.'); + } + + if (1 === \count($this->dirs) && 0 === \count($this->iterators)) { + $iterator = $this->searchInDirectory($this->dirs[0]); + + if ($this->sort || $this->reverseSorting) { + $iterator = (new Iterator\SortableIterator($iterator, $this->sort, $this->reverseSorting))->getIterator(); + } + + return $iterator; + } + + $iterator = new \AppendIterator(); + foreach ($this->dirs as $dir) { + $iterator->append(new \IteratorIterator(new LazyIterator(fn () => $this->searchInDirectory($dir)))); + } + + foreach ($this->iterators as $it) { + $iterator->append($it); + } + + if ($this->sort || $this->reverseSorting) { + $iterator = (new Iterator\SortableIterator($iterator, $this->sort, $this->reverseSorting))->getIterator(); + } + + return $iterator; + } + + /** + * Appends an existing set of files/directories to the finder. + * + * The set can be another Finder, an Iterator, an IteratorAggregate, or even a plain array. + * + * @return $this + * + * @throws \InvalidArgumentException when the given argument is not iterable + */ + public function append(iterable $iterator): static + { + if ($iterator instanceof \IteratorAggregate) { + $this->iterators[] = $iterator->getIterator(); + } elseif ($iterator instanceof \Iterator) { + $this->iterators[] = $iterator; + } elseif (is_iterable($iterator)) { + $it = new \ArrayIterator(); + foreach ($iterator as $file) { + $file = $file instanceof \SplFileInfo ? $file : new \SplFileInfo($file); + $it[$file->getPathname()] = $file; + } + $this->iterators[] = $it; + } else { + throw new \InvalidArgumentException('Finder::append() method wrong argument type.'); + } + + return $this; + } + + /** + * Check if any results were found. + */ + public function hasResults(): bool + { + foreach ($this->getIterator() as $_) { + return true; + } + + return false; + } + + /** + * Counts all the results collected by the iterators. + */ + public function count(): int + { + return iterator_count($this->getIterator()); + } + + private function searchInDirectory(string $dir): \Iterator + { + $exclude = $this->exclude; + $notPaths = $this->notPaths; + + if ($this->pruneFilters) { + $exclude = array_merge($exclude, $this->pruneFilters); + } + + if (static::IGNORE_VCS_FILES === (static::IGNORE_VCS_FILES & $this->ignore)) { + $exclude = array_merge($exclude, self::$vcsPatterns); + } + + if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) { + $notPaths[] = '#(^|/)\..+(/|$)#'; + } + + $minDepth = 0; + $maxDepth = \PHP_INT_MAX; + + foreach ($this->depths as $comparator) { + switch ($comparator->getOperator()) { + case '>': + $minDepth = $comparator->getTarget() + 1; + break; + case '>=': + $minDepth = $comparator->getTarget(); + break; + case '<': + $maxDepth = $comparator->getTarget() - 1; + break; + case '<=': + $maxDepth = $comparator->getTarget(); + break; + default: + $minDepth = $maxDepth = $comparator->getTarget(); + } + } + + $flags = \RecursiveDirectoryIterator::SKIP_DOTS; + + if ($this->followLinks) { + $flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS; + } + + $iterator = new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs); + + if ($exclude) { + $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $exclude); + } + + $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST); + + if ($minDepth > 0 || $maxDepth < \PHP_INT_MAX) { + $iterator = new Iterator\DepthRangeFilterIterator($iterator, $minDepth, $maxDepth); + } + + if ($this->mode) { + $iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode); + } + + if ($this->names || $this->notNames) { + $iterator = new Iterator\FilenameFilterIterator($iterator, $this->names, $this->notNames); + } + + if ($this->contains || $this->notContains) { + $iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains); + } + + if ($this->sizes) { + $iterator = new Iterator\SizeRangeFilterIterator($iterator, $this->sizes); + } + + if ($this->dates) { + $iterator = new Iterator\DateRangeFilterIterator($iterator, $this->dates); + } + + if ($this->filters) { + $iterator = new Iterator\CustomFilterIterator($iterator, $this->filters); + } + + if ($this->paths || $notPaths) { + $iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $notPaths); + } + + if (static::IGNORE_VCS_IGNORED_FILES === (static::IGNORE_VCS_IGNORED_FILES & $this->ignore)) { + $iterator = new Iterator\VcsIgnoredFilterIterator($iterator, $dir); + } + + return $iterator; + } + + /** + * Normalizes given directory names by removing trailing slashes. + * + * Excluding: (s)ftp:// or ssh2.(s)ftp:// wrapper + */ + private function normalizeDir(string $dir): string + { + if ('/' === $dir) { + return $dir; + } + + $dir = rtrim($dir, '/'.\DIRECTORY_SEPARATOR); + + if (preg_match('#^(ssh2\.)?s?ftp://#', $dir)) { + $dir .= '/'; + } + + return $dir; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Gitignore.php b/tools/php-cs-fixer/vendor/symfony/finder/Gitignore.php new file mode 100644 index 00000000..bf05c5b3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Gitignore.php @@ -0,0 +1,91 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder; + +/** + * Gitignore matches against text. + * + * @author Michael Voříšek + * @author Ahmed Abdou + */ +class Gitignore +{ + /** + * Returns a regexp which is the equivalent of the gitignore pattern. + * + * Format specification: https://git-scm.com/docs/gitignore#_pattern_format + */ + public static function toRegex(string $gitignoreFileContent): string + { + return self::buildRegex($gitignoreFileContent, false); + } + + public static function toRegexMatchingNegatedPatterns(string $gitignoreFileContent): string + { + return self::buildRegex($gitignoreFileContent, true); + } + + private static function buildRegex(string $gitignoreFileContent, bool $inverted): string + { + $gitignoreFileContent = preg_replace('~(? '['.('' !== $matches[1] ? '^' : '').str_replace('\\-', '-', $matches[2]).']', $regex); + $regex = preg_replace('~(?:(?:\\\\\*){2,}(/?))+~', '(?:(?:(?!//).(? + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder; + +/** + * Glob matches globbing patterns against text. + * + * if match_glob("foo.*", "foo.bar") echo "matched\n"; + * + * // prints foo.bar and foo.baz + * $regex = glob_to_regex("foo.*"); + * for (['foo.bar', 'foo.baz', 'foo', 'bar'] as $t) + * { + * if (/$regex/) echo "matched: $car\n"; + * } + * + * Glob implements glob(3) style matching that can be used to match + * against text, rather than fetching names from a filesystem. + * + * Based on the Perl Text::Glob module. + * + * @author Fabien Potencier PHP port + * @author Richard Clamp Perl version + * @copyright 2004-2005 Fabien Potencier + * @copyright 2002 Richard Clamp + */ +class Glob +{ + /** + * Returns a regexp which is the equivalent of the glob pattern. + */ + public static function toRegex(string $glob, bool $strictLeadingDot = true, bool $strictWildcardSlash = true, string $delimiter = '#'): string + { + $firstByte = true; + $escaping = false; + $inCurlies = 0; + $regex = ''; + $sizeGlob = \strlen($glob); + for ($i = 0; $i < $sizeGlob; ++$i) { + $car = $glob[$i]; + if ($firstByte && $strictLeadingDot && '.' !== $car) { + $regex .= '(?=[^\.])'; + } + + $firstByte = '/' === $car; + + if ($firstByte && $strictWildcardSlash && isset($glob[$i + 2]) && '**' === $glob[$i + 1].$glob[$i + 2] && (!isset($glob[$i + 3]) || '/' === $glob[$i + 3])) { + $car = '[^/]++/'; + if (!isset($glob[$i + 3])) { + $car .= '?'; + } + + if ($strictLeadingDot) { + $car = '(?=[^\.])'.$car; + } + + $car = '/(?:'.$car.')*'; + $i += 2 + isset($glob[$i + 3]); + + if ('/' === $delimiter) { + $car = str_replace('/', '\\/', $car); + } + } + + if ($delimiter === $car || '.' === $car || '(' === $car || ')' === $car || '|' === $car || '+' === $car || '^' === $car || '$' === $car) { + $regex .= "\\$car"; + } elseif ('*' === $car) { + $regex .= $escaping ? '\\*' : ($strictWildcardSlash ? '[^/]*' : '.*'); + } elseif ('?' === $car) { + $regex .= $escaping ? '\\?' : ($strictWildcardSlash ? '[^/]' : '.'); + } elseif ('{' === $car) { + $regex .= $escaping ? '\\{' : '('; + if (!$escaping) { + ++$inCurlies; + } + } elseif ('}' === $car && $inCurlies) { + $regex .= $escaping ? '}' : ')'; + if (!$escaping) { + --$inCurlies; + } + } elseif (',' === $car && $inCurlies) { + $regex .= $escaping ? ',' : '|'; + } elseif ('\\' === $car) { + if ($escaping) { + $regex .= '\\\\'; + $escaping = false; + } else { + $escaping = true; + } + + continue; + } else { + $regex .= $car; + } + $escaping = false; + } + + return $delimiter.'^'.$regex.'$'.$delimiter; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Iterator/CustomFilterIterator.php b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/CustomFilterIterator.php new file mode 100644 index 00000000..82ee81d8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/CustomFilterIterator.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +/** + * CustomFilterIterator filters files by applying anonymous functions. + * + * The anonymous function receives a \SplFileInfo and must return false + * to remove files. + * + * @author Fabien Potencier + * + * @extends \FilterIterator + */ +class CustomFilterIterator extends \FilterIterator +{ + private array $filters = []; + + /** + * @param \Iterator $iterator The Iterator to filter + * @param callable[] $filters An array of PHP callbacks + * + * @throws \InvalidArgumentException + */ + public function __construct(\Iterator $iterator, array $filters) + { + foreach ($filters as $filter) { + if (!\is_callable($filter)) { + throw new \InvalidArgumentException('Invalid PHP callback.'); + } + } + $this->filters = $filters; + + parent::__construct($iterator); + } + + /** + * Filters the iterator values. + */ + public function accept(): bool + { + $fileinfo = $this->current(); + + foreach ($this->filters as $filter) { + if (false === $filter($fileinfo)) { + return false; + } + } + + return true; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Iterator/DateRangeFilterIterator.php b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/DateRangeFilterIterator.php new file mode 100644 index 00000000..718d42b1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/DateRangeFilterIterator.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +use Symfony\Component\Finder\Comparator\DateComparator; + +/** + * DateRangeFilterIterator filters out files that are not in the given date range (last modified dates). + * + * @author Fabien Potencier + * + * @extends \FilterIterator + */ +class DateRangeFilterIterator extends \FilterIterator +{ + private array $comparators = []; + + /** + * @param \Iterator $iterator + * @param DateComparator[] $comparators + */ + public function __construct(\Iterator $iterator, array $comparators) + { + $this->comparators = $comparators; + + parent::__construct($iterator); + } + + /** + * Filters the iterator values. + */ + public function accept(): bool + { + $fileinfo = $this->current(); + + if (!file_exists($fileinfo->getPathname())) { + return false; + } + + $filedate = $fileinfo->getMTime(); + foreach ($this->comparators as $compare) { + if (!$compare->test($filedate)) { + return false; + } + } + + return true; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Iterator/DepthRangeFilterIterator.php b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/DepthRangeFilterIterator.php new file mode 100644 index 00000000..1cddb5fa --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/DepthRangeFilterIterator.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +/** + * DepthRangeFilterIterator limits the directory depth. + * + * @author Fabien Potencier + * + * @template-covariant TKey + * @template-covariant TValue + * + * @extends \FilterIterator + */ +class DepthRangeFilterIterator extends \FilterIterator +{ + private int $minDepth = 0; + + /** + * @param \RecursiveIteratorIterator<\RecursiveIterator> $iterator The Iterator to filter + * @param int $minDepth The min depth + * @param int $maxDepth The max depth + */ + public function __construct(\RecursiveIteratorIterator $iterator, int $minDepth = 0, int $maxDepth = \PHP_INT_MAX) + { + $this->minDepth = $minDepth; + $iterator->setMaxDepth(\PHP_INT_MAX === $maxDepth ? -1 : $maxDepth); + + parent::__construct($iterator); + } + + /** + * Filters the iterator values. + */ + public function accept(): bool + { + return $this->getInnerIterator()->getDepth() >= $this->minDepth; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php new file mode 100644 index 00000000..ebbc76ec --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php @@ -0,0 +1,110 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +use Symfony\Component\Finder\SplFileInfo; + +/** + * ExcludeDirectoryFilterIterator filters out directories. + * + * @author Fabien Potencier + * + * @extends \FilterIterator + * + * @implements \RecursiveIterator + */ +class ExcludeDirectoryFilterIterator extends \FilterIterator implements \RecursiveIterator +{ + /** @var \Iterator */ + private \Iterator $iterator; + private bool $isRecursive; + /** @var array */ + private array $excludedDirs = []; + private ?string $excludedPattern = null; + /** @var list */ + private array $pruneFilters = []; + + /** + * @param \Iterator $iterator The Iterator to filter + * @param list $directories An array of directories to exclude + */ + public function __construct(\Iterator $iterator, array $directories) + { + $this->iterator = $iterator; + $this->isRecursive = $iterator instanceof \RecursiveIterator; + $patterns = []; + foreach ($directories as $directory) { + if (!\is_string($directory)) { + if (!\is_callable($directory)) { + throw new \InvalidArgumentException('Invalid PHP callback.'); + } + + $this->pruneFilters[] = $directory; + + continue; + } + + $directory = rtrim($directory, '/'); + if (!$this->isRecursive || str_contains($directory, '/')) { + $patterns[] = preg_quote($directory, '#'); + } else { + $this->excludedDirs[$directory] = true; + } + } + if ($patterns) { + $this->excludedPattern = '#(?:^|/)(?:'.implode('|', $patterns).')(?:/|$)#'; + } + + parent::__construct($iterator); + } + + /** + * Filters the iterator values. + */ + public function accept(): bool + { + if ($this->isRecursive && isset($this->excludedDirs[$this->getFilename()]) && $this->isDir()) { + return false; + } + + if ($this->excludedPattern) { + $path = $this->isDir() ? $this->current()->getRelativePathname() : $this->current()->getRelativePath(); + $path = str_replace('\\', '/', $path); + + return !preg_match($this->excludedPattern, $path); + } + + if ($this->pruneFilters && $this->hasChildren()) { + foreach ($this->pruneFilters as $pruneFilter) { + if (!$pruneFilter($this->current())) { + return false; + } + } + } + + return true; + } + + public function hasChildren(): bool + { + return $this->isRecursive && $this->iterator->hasChildren(); + } + + public function getChildren(): self + { + $children = new self($this->iterator->getChildren(), []); + $children->excludedDirs = $this->excludedDirs; + $children->excludedPattern = $this->excludedPattern; + + return $children; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Iterator/FileTypeFilterIterator.php b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/FileTypeFilterIterator.php new file mode 100644 index 00000000..21303781 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/FileTypeFilterIterator.php @@ -0,0 +1,53 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +/** + * FileTypeFilterIterator only keeps files, directories, or both. + * + * @author Fabien Potencier + * + * @extends \FilterIterator + */ +class FileTypeFilterIterator extends \FilterIterator +{ + public const ONLY_FILES = 1; + public const ONLY_DIRECTORIES = 2; + + private int $mode; + + /** + * @param \Iterator $iterator The Iterator to filter + * @param int $mode The mode (self::ONLY_FILES or self::ONLY_DIRECTORIES) + */ + public function __construct(\Iterator $iterator, int $mode) + { + $this->mode = $mode; + + parent::__construct($iterator); + } + + /** + * Filters the iterator values. + */ + public function accept(): bool + { + $fileinfo = $this->current(); + if (self::ONLY_DIRECTORIES === (self::ONLY_DIRECTORIES & $this->mode) && $fileinfo->isFile()) { + return false; + } elseif (self::ONLY_FILES === (self::ONLY_FILES & $this->mode) && $fileinfo->isDir()) { + return false; + } + + return true; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Iterator/FilecontentFilterIterator.php b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/FilecontentFilterIterator.php new file mode 100644 index 00000000..bdc71ffd --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/FilecontentFilterIterator.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +use Symfony\Component\Finder\SplFileInfo; + +/** + * FilecontentFilterIterator filters files by their contents using patterns (regexps or strings). + * + * @author Fabien Potencier + * @author Włodzimierz Gajda + * + * @extends MultiplePcreFilterIterator + */ +class FilecontentFilterIterator extends MultiplePcreFilterIterator +{ + /** + * Filters the iterator values. + */ + public function accept(): bool + { + if (!$this->matchRegexps && !$this->noMatchRegexps) { + return true; + } + + $fileinfo = $this->current(); + + if ($fileinfo->isDir() || !$fileinfo->isReadable()) { + return false; + } + + $content = $fileinfo->getContents(); + if (!$content) { + return false; + } + + return $this->isAccepted($content); + } + + /** + * Converts string to regexp if necessary. + * + * @param string $str Pattern: string or regexp + */ + protected function toRegex(string $str): string + { + return $this->isRegex($str) ? $str : '/'.preg_quote($str, '/').'/'; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Iterator/FilenameFilterIterator.php b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/FilenameFilterIterator.php new file mode 100644 index 00000000..05d95358 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/FilenameFilterIterator.php @@ -0,0 +1,45 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +use Symfony\Component\Finder\Glob; + +/** + * FilenameFilterIterator filters files by patterns (a regexp, a glob, or a string). + * + * @author Fabien Potencier + * + * @extends MultiplePcreFilterIterator + */ +class FilenameFilterIterator extends MultiplePcreFilterIterator +{ + /** + * Filters the iterator values. + */ + public function accept(): bool + { + return $this->isAccepted($this->current()->getFilename()); + } + + /** + * Converts glob to regexp. + * + * PCRE patterns are left unchanged. + * Glob strings are transformed with Glob::toRegex(). + * + * @param string $str Pattern: glob or regexp + */ + protected function toRegex(string $str): string + { + return $this->isRegex($str) ? $str : Glob::toRegex($str); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Iterator/LazyIterator.php b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/LazyIterator.php new file mode 100644 index 00000000..5b5806be --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/LazyIterator.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +/** + * @author Jérémy Derussé + * + * @internal + */ +class LazyIterator implements \IteratorAggregate +{ + private \Closure $iteratorFactory; + + public function __construct(callable $iteratorFactory) + { + $this->iteratorFactory = $iteratorFactory(...); + } + + public function getIterator(): \Traversable + { + yield from ($this->iteratorFactory)(); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Iterator/MultiplePcreFilterIterator.php b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/MultiplePcreFilterIterator.php new file mode 100644 index 00000000..3450c49d --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/MultiplePcreFilterIterator.php @@ -0,0 +1,107 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +/** + * MultiplePcreFilterIterator filters files using patterns (regexps, globs or strings). + * + * @author Fabien Potencier + * + * @template-covariant TKey + * @template-covariant TValue + * + * @extends \FilterIterator + */ +abstract class MultiplePcreFilterIterator extends \FilterIterator +{ + protected array $matchRegexps = []; + protected array $noMatchRegexps = []; + + /** + * @param \Iterator $iterator The Iterator to filter + * @param string[] $matchPatterns An array of patterns that need to match + * @param string[] $noMatchPatterns An array of patterns that need to not match + */ + public function __construct(\Iterator $iterator, array $matchPatterns, array $noMatchPatterns) + { + foreach ($matchPatterns as $pattern) { + $this->matchRegexps[] = $this->toRegex($pattern); + } + + foreach ($noMatchPatterns as $pattern) { + $this->noMatchRegexps[] = $this->toRegex($pattern); + } + + parent::__construct($iterator); + } + + /** + * Checks whether the string is accepted by the regex filters. + * + * If there is no regexps defined in the class, this method will accept the string. + * Such case can be handled by child classes before calling the method if they want to + * apply a different behavior. + */ + protected function isAccepted(string $string): bool + { + // should at least not match one rule to exclude + foreach ($this->noMatchRegexps as $regex) { + if (preg_match($regex, $string)) { + return false; + } + } + + // should at least match one rule + if ($this->matchRegexps) { + foreach ($this->matchRegexps as $regex) { + if (preg_match($regex, $string)) { + return true; + } + } + + return false; + } + + // If there is no match rules, the file is accepted + return true; + } + + /** + * Checks whether the string is a regex. + */ + protected function isRegex(string $str): bool + { + $availableModifiers = 'imsxuADUn'; + + if (preg_match('/^(.{3,}?)['.$availableModifiers.']*$/', $str, $m)) { + $start = substr($m[1], 0, 1); + $end = substr($m[1], -1); + + if ($start === $end) { + return !preg_match('/[*?[:alnum:] \\\\]/', $start); + } + + foreach ([['{', '}'], ['(', ')'], ['[', ']'], ['<', '>']] as $delimiters) { + if ($start === $delimiters[0] && $end === $delimiters[1]) { + return true; + } + } + } + + return false; + } + + /** + * Converts string into regexp. + */ + abstract protected function toRegex(string $str): string; +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Iterator/PathFilterIterator.php b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/PathFilterIterator.php new file mode 100644 index 00000000..c6d58139 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/PathFilterIterator.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +use Symfony\Component\Finder\SplFileInfo; + +/** + * PathFilterIterator filters files by path patterns (e.g. some/special/dir). + * + * @author Fabien Potencier + * @author Włodzimierz Gajda + * + * @extends MultiplePcreFilterIterator + */ +class PathFilterIterator extends MultiplePcreFilterIterator +{ + /** + * Filters the iterator values. + */ + public function accept(): bool + { + $filename = $this->current()->getRelativePathname(); + + if ('\\' === \DIRECTORY_SEPARATOR) { + $filename = str_replace('\\', '/', $filename); + } + + return $this->isAccepted($filename); + } + + /** + * Converts strings to regexp. + * + * PCRE patterns are left unchanged. + * + * Default conversion: + * 'lorem/ipsum/dolor' ==> 'lorem\/ipsum\/dolor/' + * + * Use only / as directory separator (on Windows also). + * + * @param string $str Pattern: regexp or dirname + */ + protected function toRegex(string $str): string + { + return $this->isRegex($str) ? $str : '/'.preg_quote($str, '/').'/'; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Iterator/RecursiveDirectoryIterator.php b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/RecursiveDirectoryIterator.php new file mode 100644 index 00000000..34cced68 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/RecursiveDirectoryIterator.php @@ -0,0 +1,133 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +use Symfony\Component\Finder\Exception\AccessDeniedException; +use Symfony\Component\Finder\SplFileInfo; + +/** + * Extends the \RecursiveDirectoryIterator to support relative paths. + * + * @author Victor Berchet + * + * @extends \RecursiveDirectoryIterator + */ +class RecursiveDirectoryIterator extends \RecursiveDirectoryIterator +{ + private bool $ignoreUnreadableDirs; + private bool $ignoreFirstRewind = true; + + // these 3 properties take part of the performance optimization to avoid redoing the same work in all iterations + private string $rootPath; + private string $subPath; + private string $directorySeparator = '/'; + + /** + * @throws \RuntimeException + */ + public function __construct(string $path, int $flags, bool $ignoreUnreadableDirs = false) + { + if ($flags & (self::CURRENT_AS_PATHNAME | self::CURRENT_AS_SELF)) { + throw new \RuntimeException('This iterator only support returning current as fileinfo.'); + } + + parent::__construct($path, $flags); + $this->ignoreUnreadableDirs = $ignoreUnreadableDirs; + $this->rootPath = $path; + if ('/' !== \DIRECTORY_SEPARATOR && !($flags & self::UNIX_PATHS)) { + $this->directorySeparator = \DIRECTORY_SEPARATOR; + } + } + + /** + * Return an instance of SplFileInfo with support for relative paths. + */ + public function current(): SplFileInfo + { + // the logic here avoids redoing the same work in all iterations + + if (!isset($this->subPath)) { + $this->subPath = $this->getSubPath(); + } + $subPathname = $this->subPath; + if ('' !== $subPathname) { + $subPathname .= $this->directorySeparator; + } + $subPathname .= $this->getFilename(); + + if ('/' !== $basePath = $this->rootPath) { + $basePath .= $this->directorySeparator; + } + + return new SplFileInfo($basePath.$subPathname, $this->subPath, $subPathname); + } + + public function hasChildren(bool $allowLinks = false): bool + { + $hasChildren = parent::hasChildren($allowLinks); + + if (!$hasChildren || !$this->ignoreUnreadableDirs) { + return $hasChildren; + } + + try { + parent::getChildren(); + + return true; + } catch (\UnexpectedValueException) { + // If directory is unreadable and finder is set to ignore it, skip children + return false; + } + } + + /** + * @throws AccessDeniedException + */ + public function getChildren(): \RecursiveDirectoryIterator + { + try { + $children = parent::getChildren(); + + if ($children instanceof self) { + // parent method will call the constructor with default arguments, so unreadable dirs won't be ignored anymore + $children->ignoreUnreadableDirs = $this->ignoreUnreadableDirs; + + // performance optimization to avoid redoing the same work in all children + $children->rootPath = $this->rootPath; + } + + return $children; + } catch (\UnexpectedValueException $e) { + throw new AccessDeniedException($e->getMessage(), $e->getCode(), $e); + } + } + + public function next(): void + { + $this->ignoreFirstRewind = false; + + parent::next(); + } + + public function rewind(): void + { + // some streams like FTP are not rewindable, ignore the first rewind after creation, + // as newly created DirectoryIterator does not need to be rewound + if ($this->ignoreFirstRewind) { + $this->ignoreFirstRewind = false; + + return; + } + + parent::rewind(); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Iterator/SizeRangeFilterIterator.php b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/SizeRangeFilterIterator.php new file mode 100644 index 00000000..925830a2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/SizeRangeFilterIterator.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +use Symfony\Component\Finder\Comparator\NumberComparator; + +/** + * SizeRangeFilterIterator filters out files that are not in the given size range. + * + * @author Fabien Potencier + * + * @extends \FilterIterator + */ +class SizeRangeFilterIterator extends \FilterIterator +{ + private array $comparators = []; + + /** + * @param \Iterator $iterator + * @param NumberComparator[] $comparators + */ + public function __construct(\Iterator $iterator, array $comparators) + { + $this->comparators = $comparators; + + parent::__construct($iterator); + } + + /** + * Filters the iterator values. + */ + public function accept(): bool + { + $fileinfo = $this->current(); + if (!$fileinfo->isFile()) { + return true; + } + + $filesize = $fileinfo->getSize(); + foreach ($this->comparators as $compare) { + if (!$compare->test($filesize)) { + return false; + } + } + + return true; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Iterator/SortableIterator.php b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/SortableIterator.php new file mode 100644 index 00000000..177cd0b6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/SortableIterator.php @@ -0,0 +1,103 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +/** + * SortableIterator applies a sort on a given Iterator. + * + * @author Fabien Potencier + * + * @implements \IteratorAggregate + */ +class SortableIterator implements \IteratorAggregate +{ + public const SORT_BY_NONE = 0; + public const SORT_BY_NAME = 1; + public const SORT_BY_TYPE = 2; + public const SORT_BY_ACCESSED_TIME = 3; + public const SORT_BY_CHANGED_TIME = 4; + public const SORT_BY_MODIFIED_TIME = 5; + public const SORT_BY_NAME_NATURAL = 6; + public const SORT_BY_NAME_CASE_INSENSITIVE = 7; + public const SORT_BY_NAME_NATURAL_CASE_INSENSITIVE = 8; + public const SORT_BY_EXTENSION = 9; + public const SORT_BY_SIZE = 10; + + /** @var \Traversable */ + private \Traversable $iterator; + private \Closure|int $sort; + + /** + * @param \Traversable $iterator + * @param int|callable $sort The sort type (SORT_BY_NAME, SORT_BY_TYPE, or a PHP callback) + * + * @throws \InvalidArgumentException + */ + public function __construct(\Traversable $iterator, int|callable $sort, bool $reverseOrder = false) + { + $this->iterator = $iterator; + $order = $reverseOrder ? -1 : 1; + + if (self::SORT_BY_NAME === $sort) { + $this->sort = static fn (\SplFileInfo $a, \SplFileInfo $b) => $order * strcmp($a->getRealPath() ?: $a->getPathname(), $b->getRealPath() ?: $b->getPathname()); + } elseif (self::SORT_BY_NAME_NATURAL === $sort) { + $this->sort = static fn (\SplFileInfo $a, \SplFileInfo $b) => $order * strnatcmp($a->getRealPath() ?: $a->getPathname(), $b->getRealPath() ?: $b->getPathname()); + } elseif (self::SORT_BY_NAME_CASE_INSENSITIVE === $sort) { + $this->sort = static fn (\SplFileInfo $a, \SplFileInfo $b) => $order * strcasecmp($a->getRealPath() ?: $a->getPathname(), $b->getRealPath() ?: $b->getPathname()); + } elseif (self::SORT_BY_NAME_NATURAL_CASE_INSENSITIVE === $sort) { + $this->sort = static fn (\SplFileInfo $a, \SplFileInfo $b) => $order * strnatcasecmp($a->getRealPath() ?: $a->getPathname(), $b->getRealPath() ?: $b->getPathname()); + } elseif (self::SORT_BY_TYPE === $sort) { + $this->sort = static function (\SplFileInfo $a, \SplFileInfo $b) use ($order) { + if ($a->isDir() && $b->isFile()) { + return -$order; + } elseif ($a->isFile() && $b->isDir()) { + return $order; + } + + return $order * strcmp($a->getRealPath() ?: $a->getPathname(), $b->getRealPath() ?: $b->getPathname()); + }; + } elseif (self::SORT_BY_ACCESSED_TIME === $sort) { + $this->sort = static fn (\SplFileInfo $a, \SplFileInfo $b) => $order * ($a->getATime() - $b->getATime()); + } elseif (self::SORT_BY_CHANGED_TIME === $sort) { + $this->sort = static fn (\SplFileInfo $a, \SplFileInfo $b) => $order * ($a->getCTime() - $b->getCTime()); + } elseif (self::SORT_BY_MODIFIED_TIME === $sort) { + $this->sort = static fn (\SplFileInfo $a, \SplFileInfo $b) => $order * ($a->getMTime() - $b->getMTime()); + } elseif (self::SORT_BY_EXTENSION === $sort) { + $this->sort = static fn (\SplFileInfo $a, \SplFileInfo $b) => $order * strnatcmp($a->getExtension(), $b->getExtension()); + } elseif (self::SORT_BY_SIZE === $sort) { + $this->sort = static fn (\SplFileInfo $a, \SplFileInfo $b) => $order * ($a->getSize() - $b->getSize()); + } elseif (self::SORT_BY_NONE === $sort) { + $this->sort = $order; + } elseif (\is_callable($sort)) { + $this->sort = $reverseOrder ? static fn (\SplFileInfo $a, \SplFileInfo $b) => -$sort($a, $b) : $sort(...); + } else { + throw new \InvalidArgumentException('The SortableIterator takes a PHP callable or a valid built-in sort algorithm as an argument.'); + } + } + + public function getIterator(): \Traversable + { + if (1 === $this->sort) { + return $this->iterator; + } + + $array = iterator_to_array($this->iterator, true); + + if (-1 === $this->sort) { + $array = array_reverse($array); + } else { + uasort($array, $this->sort); + } + + return new \ArrayIterator($array); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/Iterator/VcsIgnoredFilterIterator.php b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/VcsIgnoredFilterIterator.php new file mode 100644 index 00000000..ddd70077 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/Iterator/VcsIgnoredFilterIterator.php @@ -0,0 +1,173 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder\Iterator; + +use Symfony\Component\Finder\Gitignore; + +/** + * @extends \FilterIterator + */ +final class VcsIgnoredFilterIterator extends \FilterIterator +{ + private string $baseDir; + + /** + * @var array + */ + private array $gitignoreFilesCache = []; + + /** + * @var array + */ + private array $ignoredPathsCache = []; + + /** + * @param \Iterator $iterator + */ + public function __construct(\Iterator $iterator, string $baseDir) + { + $this->baseDir = $this->normalizePath($baseDir); + + foreach ($this->parentDirectoriesUpwards($this->baseDir) as $parentDirectory) { + if (@is_dir("{$parentDirectory}/.git")) { + $this->baseDir = $parentDirectory; + break; + } + } + + parent::__construct($iterator); + } + + public function accept(): bool + { + $file = $this->current(); + + $fileRealPath = $this->normalizePath($file->getRealPath()); + + return !$this->isIgnored($fileRealPath); + } + + private function isIgnored(string $fileRealPath): bool + { + if (is_dir($fileRealPath) && !str_ends_with($fileRealPath, '/')) { + $fileRealPath .= '/'; + } + + if (isset($this->ignoredPathsCache[$fileRealPath])) { + return $this->ignoredPathsCache[$fileRealPath]; + } + + $ignored = false; + + foreach ($this->parentDirectoriesDownwards($fileRealPath) as $parentDirectory) { + if ($this->isIgnored($parentDirectory)) { + // rules in ignored directories are ignored, no need to check further. + break; + } + + $fileRelativePath = substr($fileRealPath, \strlen($parentDirectory) + 1); + + if (null === $regexps = $this->readGitignoreFile("{$parentDirectory}/.gitignore")) { + continue; + } + + [$exclusionRegex, $inclusionRegex] = $regexps; + + if (preg_match($exclusionRegex, $fileRelativePath)) { + $ignored = true; + + continue; + } + + if (preg_match($inclusionRegex, $fileRelativePath)) { + $ignored = false; + } + } + + return $this->ignoredPathsCache[$fileRealPath] = $ignored; + } + + /** + * @return list + */ + private function parentDirectoriesUpwards(string $from): array + { + $parentDirectories = []; + + $parentDirectory = $from; + + while (true) { + $newParentDirectory = \dirname($parentDirectory); + + // dirname('/') = '/' + if ($newParentDirectory === $parentDirectory) { + break; + } + + $parentDirectories[] = $parentDirectory = $newParentDirectory; + } + + return $parentDirectories; + } + + private function parentDirectoriesUpTo(string $from, string $upTo): array + { + return array_filter( + $this->parentDirectoriesUpwards($from), + static fn (string $directory): bool => str_starts_with($directory, $upTo) + ); + } + + /** + * @return list + */ + private function parentDirectoriesDownwards(string $fileRealPath): array + { + return array_reverse( + $this->parentDirectoriesUpTo($fileRealPath, $this->baseDir) + ); + } + + /** + * @return array{0: string, 1: string}|null + */ + private function readGitignoreFile(string $path): ?array + { + if (\array_key_exists($path, $this->gitignoreFilesCache)) { + return $this->gitignoreFilesCache[$path]; + } + + if (!file_exists($path)) { + return $this->gitignoreFilesCache[$path] = null; + } + + if (!is_file($path) || !is_readable($path)) { + throw new \RuntimeException("The \"ignoreVCSIgnored\" option cannot be used by the Finder as the \"{$path}\" file is not readable."); + } + + $gitignoreFileContent = file_get_contents($path); + + return $this->gitignoreFilesCache[$path] = [ + Gitignore::toRegex($gitignoreFileContent), + Gitignore::toRegexMatchingNegatedPatterns($gitignoreFileContent), + ]; + } + + private function normalizePath(string $path): string + { + if ('\\' === \DIRECTORY_SEPARATOR) { + return str_replace('\\', '/', $path); + } + + return $path; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/LICENSE b/tools/php-cs-fixer/vendor/symfony/finder/LICENSE new file mode 100644 index 00000000..0138f8f0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/finder/README.md b/tools/php-cs-fixer/vendor/symfony/finder/README.md new file mode 100644 index 00000000..22bdeb9b --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/README.md @@ -0,0 +1,14 @@ +Finder Component +================ + +The Finder component finds files and directories via an intuitive fluent +interface. + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/finder.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/tools/php-cs-fixer/vendor/symfony/finder/SplFileInfo.php b/tools/php-cs-fixer/vendor/symfony/finder/SplFileInfo.php new file mode 100644 index 00000000..867e8e81 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/SplFileInfo.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Finder; + +/** + * Extends \SplFileInfo to support relative paths. + * + * @author Fabien Potencier + */ +class SplFileInfo extends \SplFileInfo +{ + private string $relativePath; + private string $relativePathname; + + /** + * @param string $file The file name + * @param string $relativePath The relative path + * @param string $relativePathname The relative path name + */ + public function __construct(string $file, string $relativePath, string $relativePathname) + { + parent::__construct($file); + $this->relativePath = $relativePath; + $this->relativePathname = $relativePathname; + } + + /** + * Returns the relative path. + * + * This path does not contain the file name. + */ + public function getRelativePath(): string + { + return $this->relativePath; + } + + /** + * Returns the relative path name. + * + * This path contains the file name. + */ + public function getRelativePathname(): string + { + return $this->relativePathname; + } + + public function getFilenameWithoutExtension(): string + { + $filename = $this->getFilename(); + + return pathinfo($filename, \PATHINFO_FILENAME); + } + + /** + * Returns the contents of the file. + * + * @throws \RuntimeException + */ + public function getContents(): string + { + set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; }); + try { + $content = file_get_contents($this->getPathname()); + } finally { + restore_error_handler(); + } + if (false === $content) { + throw new \RuntimeException($error); + } + + return $content; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/finder/composer.json b/tools/php-cs-fixer/vendor/symfony/finder/composer.json new file mode 100644 index 00000000..2b70600d --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/finder/composer.json @@ -0,0 +1,31 @@ +{ + "name": "symfony/finder", + "type": "library", + "description": "Finds files and directories via an intuitive fluent interface", + "keywords": [], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.2" + }, + "require-dev": { + "symfony/filesystem": "^6.4|^7.0" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\Finder\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/CHANGELOG.md b/tools/php-cs-fixer/vendor/symfony/options-resolver/CHANGELOG.md new file mode 100644 index 00000000..f4de6d01 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/CHANGELOG.md @@ -0,0 +1,96 @@ +CHANGELOG +========= + +6.4 +--- + +* Improve message with full path on invalid type in nested option + +6.3 +--- + + * Add `OptionsResolver::setIgnoreUndefined()` and `OptionConfigurator::ignoreUndefined()` to ignore not defined options while resolving + +6.0 +--- + + * Remove `OptionsResolverIntrospector::getDeprecationMessage()` + +5.3 +--- + + * Add prototype definition for nested options + +5.1.0 +----- + + * added fluent configuration of options using `OptionResolver::define()` + * added `setInfo()` and `getInfo()` methods + * updated the signature of method `OptionsResolver::setDeprecated()` to `OptionsResolver::setDeprecation(string $option, string $package, string $version, $message)` + * deprecated `OptionsResolverIntrospector::getDeprecationMessage()`, use `OptionsResolverIntrospector::getDeprecation()` instead + +5.0.0 +----- + + * added argument `$triggerDeprecation` to `OptionsResolver::offsetGet()` + +4.3.0 +----- + + * added `OptionsResolver::addNormalizer` method + +4.2.0 +----- + + * added support for nested options definition + * added `setDeprecated` and `isDeprecated` methods + +3.4.0 +----- + + * added `OptionsResolverIntrospector` to inspect options definitions inside an `OptionsResolver` instance + * added array of types support in allowed types (e.g int[]) + +2.6.0 +----- + + * deprecated OptionsResolverInterface + * [BC BREAK] removed "array" type hint from OptionsResolverInterface methods + setRequired(), setAllowedValues(), addAllowedValues(), setAllowedTypes() and + addAllowedTypes() + * added OptionsResolver::setDefault() + * added OptionsResolver::hasDefault() + * added OptionsResolver::setNormalizer() + * added OptionsResolver::isRequired() + * added OptionsResolver::getRequiredOptions() + * added OptionsResolver::isMissing() + * added OptionsResolver::getMissingOptions() + * added OptionsResolver::setDefined() + * added OptionsResolver::isDefined() + * added OptionsResolver::getDefinedOptions() + * added OptionsResolver::remove() + * added OptionsResolver::clear() + * deprecated OptionsResolver::replaceDefaults() + * deprecated OptionsResolver::setOptional() in favor of setDefined() + * deprecated OptionsResolver::isKnown() in favor of isDefined() + * [BC BREAK] OptionsResolver::isRequired() returns true now if a required + option has a default value set + * [BC BREAK] merged Options into OptionsResolver and turned Options into an + interface + * deprecated Options::overload() (now in OptionsResolver) + * deprecated Options::set() (now in OptionsResolver) + * deprecated Options::get() (now in OptionsResolver) + * deprecated Options::has() (now in OptionsResolver) + * deprecated Options::replace() (now in OptionsResolver) + * [BC BREAK] Options::get() (now in OptionsResolver) can only be used within + lazy option/normalizer closures now + * [BC BREAK] removed Traversable interface from Options since using within + lazy option/normalizer closures resulted in exceptions + * [BC BREAK] removed Options::all() since using within lazy option/normalizer + closures resulted in exceptions + * [BC BREAK] OptionDefinitionException now extends LogicException instead of + RuntimeException + * [BC BREAK] normalizers are not executed anymore for unset options + * normalizers are executed after validating the options now + * [BC BREAK] an UndefinedOptionsException is now thrown instead of an + InvalidOptionsException when non-existing options are passed diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/Debug/OptionsResolverIntrospector.php b/tools/php-cs-fixer/vendor/symfony/options-resolver/Debug/OptionsResolverIntrospector.php new file mode 100644 index 00000000..f55ab147 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/Debug/OptionsResolverIntrospector.php @@ -0,0 +1,104 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\OptionsResolver\Debug; + +use Symfony\Component\OptionsResolver\Exception\NoConfigurationException; +use Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException; +use Symfony\Component\OptionsResolver\OptionsResolver; + +/** + * @author Maxime Steinhausser + * + * @final + */ +class OptionsResolverIntrospector +{ + private \Closure $get; + + public function __construct(OptionsResolver $optionsResolver) + { + $this->get = \Closure::bind(function ($property, $option, $message) { + /** @var OptionsResolver $this */ + if (!$this->isDefined($option)) { + throw new UndefinedOptionsException(sprintf('The option "%s" does not exist.', $option)); + } + + if (!\array_key_exists($option, $this->{$property})) { + throw new NoConfigurationException($message); + } + + return $this->{$property}[$option]; + }, $optionsResolver, $optionsResolver); + } + + /** + * @throws NoConfigurationException on no configured value + */ + public function getDefault(string $option): mixed + { + return ($this->get)('defaults', $option, sprintf('No default value was set for the "%s" option.', $option)); + } + + /** + * @return \Closure[] + * + * @throws NoConfigurationException on no configured closures + */ + public function getLazyClosures(string $option): array + { + return ($this->get)('lazy', $option, sprintf('No lazy closures were set for the "%s" option.', $option)); + } + + /** + * @return string[] + * + * @throws NoConfigurationException on no configured types + */ + public function getAllowedTypes(string $option): array + { + return ($this->get)('allowedTypes', $option, sprintf('No allowed types were set for the "%s" option.', $option)); + } + + /** + * @return mixed[] + * + * @throws NoConfigurationException on no configured values + */ + public function getAllowedValues(string $option): array + { + return ($this->get)('allowedValues', $option, sprintf('No allowed values were set for the "%s" option.', $option)); + } + + /** + * @throws NoConfigurationException on no configured normalizer + */ + public function getNormalizer(string $option): \Closure + { + return current($this->getNormalizers($option)); + } + + /** + * @throws NoConfigurationException when no normalizer is configured + */ + public function getNormalizers(string $option): array + { + return ($this->get)('normalizers', $option, sprintf('No normalizer was set for the "%s" option.', $option)); + } + + /** + * @throws NoConfigurationException on no configured deprecation + */ + public function getDeprecation(string $option): array + { + return ($this->get)('deprecated', $option, sprintf('No deprecation was set for the "%s" option.', $option)); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/AccessException.php b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/AccessException.php new file mode 100644 index 00000000..c12b6806 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/AccessException.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\OptionsResolver\Exception; + +/** + * Thrown when trying to read an option outside of or write it inside of + * {@link \Symfony\Component\OptionsResolver\Options::resolve()}. + * + * @author Bernhard Schussek + */ +class AccessException extends \LogicException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/ExceptionInterface.php b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/ExceptionInterface.php new file mode 100644 index 00000000..ea99d050 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/ExceptionInterface.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\OptionsResolver\Exception; + +/** + * Marker interface for all exceptions thrown by the OptionsResolver component. + * + * @author Bernhard Schussek + */ +interface ExceptionInterface extends \Throwable +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/InvalidArgumentException.php b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/InvalidArgumentException.php new file mode 100644 index 00000000..6d421d68 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/InvalidArgumentException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\OptionsResolver\Exception; + +/** + * Thrown when an argument is invalid. + * + * @author Bernhard Schussek + */ +class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/InvalidOptionsException.php b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/InvalidOptionsException.php new file mode 100644 index 00000000..6fd4f125 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/InvalidOptionsException.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\OptionsResolver\Exception; + +/** + * Thrown when the value of an option does not match its validation rules. + * + * You should make sure a valid value is passed to the option. + * + * @author Bernhard Schussek + */ +class InvalidOptionsException extends InvalidArgumentException +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/MissingOptionsException.php b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/MissingOptionsException.php new file mode 100644 index 00000000..faa487f1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/MissingOptionsException.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\OptionsResolver\Exception; + +/** + * Exception thrown when a required option is missing. + * + * Add the option to the passed options array. + * + * @author Bernhard Schussek + */ +class MissingOptionsException extends InvalidArgumentException +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/NoConfigurationException.php b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/NoConfigurationException.php new file mode 100644 index 00000000..6693ec14 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/NoConfigurationException.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\OptionsResolver\Exception; + +use Symfony\Component\OptionsResolver\Debug\OptionsResolverIntrospector; + +/** + * Thrown when trying to introspect an option definition property + * for which no value was configured inside the OptionsResolver instance. + * + * @see OptionsResolverIntrospector + * + * @author Maxime Steinhausser + */ +class NoConfigurationException extends \RuntimeException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/NoSuchOptionException.php b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/NoSuchOptionException.php new file mode 100644 index 00000000..4c3280f4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/NoSuchOptionException.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\OptionsResolver\Exception; + +/** + * Thrown when trying to read an option that has no value set. + * + * When accessing optional options from within a lazy option or normalizer you should first + * check whether the optional option is set. You can do this with `isset($options['optional'])`. + * In contrast to the {@link UndefinedOptionsException}, this is a runtime exception that can + * occur when evaluating lazy options. + * + * @author Tobias Schultze + */ +class NoSuchOptionException extends \OutOfBoundsException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/OptionDefinitionException.php b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/OptionDefinitionException.php new file mode 100644 index 00000000..e8e339d4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/OptionDefinitionException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\OptionsResolver\Exception; + +/** + * Thrown when two lazy options have a cyclic dependency. + * + * @author Bernhard Schussek + */ +class OptionDefinitionException extends \LogicException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/UndefinedOptionsException.php b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/UndefinedOptionsException.php new file mode 100644 index 00000000..6ca3fce4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/Exception/UndefinedOptionsException.php @@ -0,0 +1,24 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\OptionsResolver\Exception; + +/** + * Exception thrown when an undefined option is passed. + * + * You should remove the options in question from your code or define them + * beforehand. + * + * @author Bernhard Schussek + */ +class UndefinedOptionsException extends InvalidArgumentException +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/LICENSE b/tools/php-cs-fixer/vendor/symfony/options-resolver/LICENSE new file mode 100644 index 00000000..0138f8f0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/OptionConfigurator.php b/tools/php-cs-fixer/vendor/symfony/options-resolver/OptionConfigurator.php new file mode 100644 index 00000000..3aa37288 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/OptionConfigurator.php @@ -0,0 +1,149 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\OptionsResolver; + +use Symfony\Component\OptionsResolver\Exception\AccessException; + +final class OptionConfigurator +{ + private string $name; + private OptionsResolver $resolver; + + public function __construct(string $name, OptionsResolver $resolver) + { + $this->name = $name; + $this->resolver = $resolver; + $this->resolver->setDefined($name); + } + + /** + * Adds allowed types for this option. + * + * @return $this + * + * @throws AccessException If called from a lazy option or normalizer + */ + public function allowedTypes(string ...$types): static + { + $this->resolver->setAllowedTypes($this->name, $types); + + return $this; + } + + /** + * Sets allowed values for this option. + * + * @param mixed ...$values One or more acceptable values/closures + * + * @return $this + * + * @throws AccessException If called from a lazy option or normalizer + */ + public function allowedValues(mixed ...$values): static + { + $this->resolver->setAllowedValues($this->name, $values); + + return $this; + } + + /** + * Sets the default value for this option. + * + * @return $this + * + * @throws AccessException If called from a lazy option or normalizer + */ + public function default(mixed $value): static + { + $this->resolver->setDefault($this->name, $value); + + return $this; + } + + /** + * Defines an option configurator with the given name. + */ + public function define(string $option): self + { + return $this->resolver->define($option); + } + + /** + * Marks this option as deprecated. + * + * @param string $package The name of the composer package that is triggering the deprecation + * @param string $version The version of the package that introduced the deprecation + * @param string|\Closure $message The deprecation message to use + * + * @return $this + */ + public function deprecated(string $package, string $version, string|\Closure $message = 'The option "%name%" is deprecated.'): static + { + $this->resolver->setDeprecated($this->name, $package, $version, $message); + + return $this; + } + + /** + * Sets the normalizer for this option. + * + * @return $this + * + * @throws AccessException If called from a lazy option or normalizer + */ + public function normalize(\Closure $normalizer): static + { + $this->resolver->setNormalizer($this->name, $normalizer); + + return $this; + } + + /** + * Marks this option as required. + * + * @return $this + * + * @throws AccessException If called from a lazy option or normalizer + */ + public function required(): static + { + $this->resolver->setRequired($this->name); + + return $this; + } + + /** + * Sets an info message for an option. + * + * @return $this + * + * @throws AccessException If called from a lazy option or normalizer + */ + public function info(string $info): static + { + $this->resolver->setInfo($this->name, $info); + + return $this; + } + + /** + * Sets whether ignore undefined options. + * + * @return $this + */ + public function ignoreUndefined(bool $ignore = true): static + { + $this->resolver->setIgnoreUndefined($ignore); + + return $this; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/Options.php b/tools/php-cs-fixer/vendor/symfony/options-resolver/Options.php new file mode 100644 index 00000000..d444ec42 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/Options.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\OptionsResolver; + +/** + * Contains resolved option values. + * + * @author Bernhard Schussek + * @author Tobias Schultze + */ +interface Options extends \ArrayAccess, \Countable +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/OptionsResolver.php b/tools/php-cs-fixer/vendor/symfony/options-resolver/OptionsResolver.php new file mode 100644 index 00000000..fc378ce3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/OptionsResolver.php @@ -0,0 +1,1317 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\OptionsResolver; + +use Symfony\Component\OptionsResolver\Exception\AccessException; +use Symfony\Component\OptionsResolver\Exception\InvalidArgumentException; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use Symfony\Component\OptionsResolver\Exception\MissingOptionsException; +use Symfony\Component\OptionsResolver\Exception\NoSuchOptionException; +use Symfony\Component\OptionsResolver\Exception\OptionDefinitionException; +use Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException; + +/** + * Validates options and merges them with default values. + * + * @author Bernhard Schussek + * @author Tobias Schultze + */ +class OptionsResolver implements Options +{ + private const VALIDATION_FUNCTIONS = [ + 'bool' => 'is_bool', + 'boolean' => 'is_bool', + 'int' => 'is_int', + 'integer' => 'is_int', + 'long' => 'is_int', + 'float' => 'is_float', + 'double' => 'is_float', + 'real' => 'is_float', + 'numeric' => 'is_numeric', + 'string' => 'is_string', + 'scalar' => 'is_scalar', + 'array' => 'is_array', + 'iterable' => 'is_iterable', + 'countable' => 'is_countable', + 'callable' => 'is_callable', + 'object' => 'is_object', + 'resource' => 'is_resource', + ]; + + /** + * The names of all defined options. + */ + private array $defined = []; + + /** + * The default option values. + */ + private array $defaults = []; + + /** + * A list of closure for nested options. + * + * @var \Closure[][] + */ + private array $nested = []; + + /** + * The names of required options. + */ + private array $required = []; + + /** + * The resolved option values. + */ + private array $resolved = []; + + /** + * A list of normalizer closures. + * + * @var \Closure[][] + */ + private array $normalizers = []; + + /** + * A list of accepted values for each option. + */ + private array $allowedValues = []; + + /** + * A list of accepted types for each option. + */ + private array $allowedTypes = []; + + /** + * A list of info messages for each option. + */ + private array $info = []; + + /** + * A list of closures for evaluating lazy options. + */ + private array $lazy = []; + + /** + * A list of lazy options whose closure is currently being called. + * + * This list helps detecting circular dependencies between lazy options. + */ + private array $calling = []; + + /** + * A list of deprecated options. + */ + private array $deprecated = []; + + /** + * The list of options provided by the user. + */ + private array $given = []; + + /** + * Whether the instance is locked for reading. + * + * Once locked, the options cannot be changed anymore. This is + * necessary in order to avoid inconsistencies during the resolving + * process. If any option is changed after being read, all evaluated + * lazy options that depend on this option would become invalid. + */ + private bool $locked = false; + + private array $parentsOptions = []; + + /** + * Whether the whole options definition is marked as array prototype. + */ + private ?bool $prototype = null; + + /** + * The prototype array's index that is being read. + */ + private int|string|null $prototypeIndex = null; + + /** + * Whether to ignore undefined options. + */ + private bool $ignoreUndefined = false; + + /** + * Sets the default value of a given option. + * + * If the default value should be set based on other options, you can pass + * a closure with the following signature: + * + * function (Options $options) { + * // ... + * } + * + * The closure will be evaluated when {@link resolve()} is called. The + * closure has access to the resolved values of other options through the + * passed {@link Options} instance: + * + * function (Options $options) { + * if (isset($options['port'])) { + * // ... + * } + * } + * + * If you want to access the previously set default value, add a second + * argument to the closure's signature: + * + * $options->setDefault('name', 'Default Name'); + * + * $options->setDefault('name', function (Options $options, $previousValue) { + * // 'Default Name' === $previousValue + * }); + * + * This is mostly useful if the configuration of the {@link Options} object + * is spread across different locations of your code, such as base and + * sub-classes. + * + * If you want to define nested options, you can pass a closure with the + * following signature: + * + * $options->setDefault('database', function (OptionsResolver $resolver) { + * $resolver->setDefined(['dbname', 'host', 'port', 'user', 'pass']); + * } + * + * To get access to the parent options, add a second argument to the closure's + * signature: + * + * function (OptionsResolver $resolver, Options $parent) { + * // 'default' === $parent['connection'] + * } + * + * @return $this + * + * @throws AccessException If called from a lazy option or normalizer + */ + public function setDefault(string $option, mixed $value): static + { + // Setting is not possible once resolving starts, because then lazy + // options could manipulate the state of the object, leading to + // inconsistent results. + if ($this->locked) { + throw new AccessException('Default values cannot be set from a lazy option or normalizer.'); + } + + // If an option is a closure that should be evaluated lazily, store it + // in the "lazy" property. + if ($value instanceof \Closure) { + $reflClosure = new \ReflectionFunction($value); + $params = $reflClosure->getParameters(); + + if (isset($params[0]) && Options::class === $this->getParameterClassName($params[0])) { + // Initialize the option if no previous value exists + if (!isset($this->defaults[$option])) { + $this->defaults[$option] = null; + } + + // Ignore previous lazy options if the closure has no second parameter + if (!isset($this->lazy[$option]) || !isset($params[1])) { + $this->lazy[$option] = []; + } + + // Store closure for later evaluation + $this->lazy[$option][] = $value; + $this->defined[$option] = true; + + // Make sure the option is processed and is not nested anymore + unset($this->resolved[$option], $this->nested[$option]); + + return $this; + } + + if (isset($params[0]) && null !== ($type = $params[0]->getType()) && self::class === $type->getName() && (!isset($params[1]) || (($type = $params[1]->getType()) instanceof \ReflectionNamedType && Options::class === $type->getName()))) { + // Store closure for later evaluation + $this->nested[$option][] = $value; + $this->defaults[$option] = []; + $this->defined[$option] = true; + + // Make sure the option is processed and is not lazy anymore + unset($this->resolved[$option], $this->lazy[$option]); + + return $this; + } + } + + // This option is not lazy nor nested anymore + unset($this->lazy[$option], $this->nested[$option]); + + // Yet undefined options can be marked as resolved, because we only need + // to resolve options with lazy closures, normalizers or validation + // rules, none of which can exist for undefined options + // If the option was resolved before, update the resolved value + if (!isset($this->defined[$option]) || \array_key_exists($option, $this->resolved)) { + $this->resolved[$option] = $value; + } + + $this->defaults[$option] = $value; + $this->defined[$option] = true; + + return $this; + } + + /** + * @return $this + * + * @throws AccessException If called from a lazy option or normalizer + */ + public function setDefaults(array $defaults): static + { + foreach ($defaults as $option => $value) { + $this->setDefault($option, $value); + } + + return $this; + } + + /** + * Returns whether a default value is set for an option. + * + * Returns true if {@link setDefault()} was called for this option. + * An option is also considered set if it was set to null. + */ + public function hasDefault(string $option): bool + { + return \array_key_exists($option, $this->defaults); + } + + /** + * Marks one or more options as required. + * + * @param string|string[] $optionNames One or more option names + * + * @return $this + * + * @throws AccessException If called from a lazy option or normalizer + */ + public function setRequired(string|array $optionNames): static + { + if ($this->locked) { + throw new AccessException('Options cannot be made required from a lazy option or normalizer.'); + } + + foreach ((array) $optionNames as $option) { + $this->defined[$option] = true; + $this->required[$option] = true; + } + + return $this; + } + + /** + * Returns whether an option is required. + * + * An option is required if it was passed to {@link setRequired()}. + */ + public function isRequired(string $option): bool + { + return isset($this->required[$option]); + } + + /** + * Returns the names of all required options. + * + * @return string[] + * + * @see isRequired() + */ + public function getRequiredOptions(): array + { + return array_keys($this->required); + } + + /** + * Returns whether an option is missing a default value. + * + * An option is missing if it was passed to {@link setRequired()}, but not + * to {@link setDefault()}. This option must be passed explicitly to + * {@link resolve()}, otherwise an exception will be thrown. + */ + public function isMissing(string $option): bool + { + return isset($this->required[$option]) && !\array_key_exists($option, $this->defaults); + } + + /** + * Returns the names of all options missing a default value. + * + * @return string[] + */ + public function getMissingOptions(): array + { + return array_keys(array_diff_key($this->required, $this->defaults)); + } + + /** + * Defines a valid option name. + * + * Defines an option name without setting a default value. The option will + * be accepted when passed to {@link resolve()}. When not passed, the + * option will not be included in the resolved options. + * + * @param string|string[] $optionNames One or more option names + * + * @return $this + * + * @throws AccessException If called from a lazy option or normalizer + */ + public function setDefined(string|array $optionNames): static + { + if ($this->locked) { + throw new AccessException('Options cannot be defined from a lazy option or normalizer.'); + } + + foreach ((array) $optionNames as $option) { + $this->defined[$option] = true; + } + + return $this; + } + + /** + * Returns whether an option is defined. + * + * Returns true for any option passed to {@link setDefault()}, + * {@link setRequired()} or {@link setDefined()}. + */ + public function isDefined(string $option): bool + { + return isset($this->defined[$option]); + } + + /** + * Returns the names of all defined options. + * + * @return string[] + * + * @see isDefined() + */ + public function getDefinedOptions(): array + { + return array_keys($this->defined); + } + + public function isNested(string $option): bool + { + return isset($this->nested[$option]); + } + + /** + * Deprecates an option, allowed types or values. + * + * Instead of passing the message, you may also pass a closure with the + * following signature: + * + * function (Options $options, $value): string { + * // ... + * } + * + * The closure receives the value as argument and should return a string. + * Return an empty string to ignore the option deprecation. + * + * The closure is invoked when {@link resolve()} is called. The parameter + * passed to the closure is the value of the option after validating it + * and before normalizing it. + * + * @param string $package The name of the composer package that is triggering the deprecation + * @param string $version The version of the package that introduced the deprecation + * @param string|\Closure $message The deprecation message to use + * + * @return $this + */ + public function setDeprecated(string $option, string $package, string $version, string|\Closure $message = 'The option "%name%" is deprecated.'): static + { + if ($this->locked) { + throw new AccessException('Options cannot be deprecated from a lazy option or normalizer.'); + } + + if (!isset($this->defined[$option])) { + throw new UndefinedOptionsException(sprintf('The option "%s" does not exist, defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined)))); + } + + if (!\is_string($message) && !$message instanceof \Closure) { + throw new InvalidArgumentException(sprintf('Invalid type for deprecation message argument, expected string or \Closure, but got "%s".', get_debug_type($message))); + } + + // ignore if empty string + if ('' === $message) { + return $this; + } + + $this->deprecated[$option] = [ + 'package' => $package, + 'version' => $version, + 'message' => $message, + ]; + + // Make sure the option is processed + unset($this->resolved[$option]); + + return $this; + } + + public function isDeprecated(string $option): bool + { + return isset($this->deprecated[$option]); + } + + /** + * Sets the normalizer for an option. + * + * The normalizer should be a closure with the following signature: + * + * function (Options $options, $value) { + * // ... + * } + * + * The closure is invoked when {@link resolve()} is called. The closure + * has access to the resolved values of other options through the passed + * {@link Options} instance. + * + * The second parameter passed to the closure is the value of + * the option. + * + * The resolved option value is set to the return value of the closure. + * + * @return $this + * + * @throws UndefinedOptionsException If the option is undefined + * @throws AccessException If called from a lazy option or normalizer + */ + public function setNormalizer(string $option, \Closure $normalizer): static + { + if ($this->locked) { + throw new AccessException('Normalizers cannot be set from a lazy option or normalizer.'); + } + + if (!isset($this->defined[$option])) { + throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined)))); + } + + $this->normalizers[$option] = [$normalizer]; + + // Make sure the option is processed + unset($this->resolved[$option]); + + return $this; + } + + /** + * Adds a normalizer for an option. + * + * The normalizer should be a closure with the following signature: + * + * function (Options $options, $value): mixed { + * // ... + * } + * + * The closure is invoked when {@link resolve()} is called. The closure + * has access to the resolved values of other options through the passed + * {@link Options} instance. + * + * The second parameter passed to the closure is the value of + * the option. + * + * The resolved option value is set to the return value of the closure. + * + * @return $this + * + * @throws UndefinedOptionsException If the option is undefined + * @throws AccessException If called from a lazy option or normalizer + */ + public function addNormalizer(string $option, \Closure $normalizer, bool $forcePrepend = false): static + { + if ($this->locked) { + throw new AccessException('Normalizers cannot be set from a lazy option or normalizer.'); + } + + if (!isset($this->defined[$option])) { + throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined)))); + } + + if ($forcePrepend) { + $this->normalizers[$option] ??= []; + array_unshift($this->normalizers[$option], $normalizer); + } else { + $this->normalizers[$option][] = $normalizer; + } + + // Make sure the option is processed + unset($this->resolved[$option]); + + return $this; + } + + /** + * Sets allowed values for an option. + * + * Instead of passing values, you may also pass a closures with the + * following signature: + * + * function ($value) { + * // return true or false + * } + * + * The closure receives the value as argument and should return true to + * accept the value and false to reject the value. + * + * @param mixed $allowedValues One or more acceptable values/closures + * + * @return $this + * + * @throws UndefinedOptionsException If the option is undefined + * @throws AccessException If called from a lazy option or normalizer + */ + public function setAllowedValues(string $option, mixed $allowedValues): static + { + if ($this->locked) { + throw new AccessException('Allowed values cannot be set from a lazy option or normalizer.'); + } + + if (!isset($this->defined[$option])) { + throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined)))); + } + + $this->allowedValues[$option] = \is_array($allowedValues) ? $allowedValues : [$allowedValues]; + + // Make sure the option is processed + unset($this->resolved[$option]); + + return $this; + } + + /** + * Adds allowed values for an option. + * + * The values are merged with the allowed values defined previously. + * + * Instead of passing values, you may also pass a closures with the + * following signature: + * + * function ($value) { + * // return true or false + * } + * + * The closure receives the value as argument and should return true to + * accept the value and false to reject the value. + * + * @param mixed $allowedValues One or more acceptable values/closures + * + * @return $this + * + * @throws UndefinedOptionsException If the option is undefined + * @throws AccessException If called from a lazy option or normalizer + */ + public function addAllowedValues(string $option, mixed $allowedValues): static + { + if ($this->locked) { + throw new AccessException('Allowed values cannot be added from a lazy option or normalizer.'); + } + + if (!isset($this->defined[$option])) { + throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined)))); + } + + if (!\is_array($allowedValues)) { + $allowedValues = [$allowedValues]; + } + + if (!isset($this->allowedValues[$option])) { + $this->allowedValues[$option] = $allowedValues; + } else { + $this->allowedValues[$option] = array_merge($this->allowedValues[$option], $allowedValues); + } + + // Make sure the option is processed + unset($this->resolved[$option]); + + return $this; + } + + /** + * Sets allowed types for an option. + * + * Any type for which a corresponding is_() function exists is + * acceptable. Additionally, fully-qualified class or interface names may + * be passed. + * + * @param string|string[] $allowedTypes One or more accepted types + * + * @return $this + * + * @throws UndefinedOptionsException If the option is undefined + * @throws AccessException If called from a lazy option or normalizer + */ + public function setAllowedTypes(string $option, string|array $allowedTypes): static + { + if ($this->locked) { + throw new AccessException('Allowed types cannot be set from a lazy option or normalizer.'); + } + + if (!isset($this->defined[$option])) { + throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined)))); + } + + $this->allowedTypes[$option] = (array) $allowedTypes; + + // Make sure the option is processed + unset($this->resolved[$option]); + + return $this; + } + + /** + * Adds allowed types for an option. + * + * The types are merged with the allowed types defined previously. + * + * Any type for which a corresponding is_() function exists is + * acceptable. Additionally, fully-qualified class or interface names may + * be passed. + * + * @param string|string[] $allowedTypes One or more accepted types + * + * @return $this + * + * @throws UndefinedOptionsException If the option is undefined + * @throws AccessException If called from a lazy option or normalizer + */ + public function addAllowedTypes(string $option, string|array $allowedTypes): static + { + if ($this->locked) { + throw new AccessException('Allowed types cannot be added from a lazy option or normalizer.'); + } + + if (!isset($this->defined[$option])) { + throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined)))); + } + + if (!isset($this->allowedTypes[$option])) { + $this->allowedTypes[$option] = (array) $allowedTypes; + } else { + $this->allowedTypes[$option] = array_merge($this->allowedTypes[$option], (array) $allowedTypes); + } + + // Make sure the option is processed + unset($this->resolved[$option]); + + return $this; + } + + /** + * Defines an option configurator with the given name. + */ + public function define(string $option): OptionConfigurator + { + if (isset($this->defined[$option])) { + throw new OptionDefinitionException(sprintf('The option "%s" is already defined.', $option)); + } + + return new OptionConfigurator($option, $this); + } + + /** + * Sets an info message for an option. + * + * @return $this + * + * @throws UndefinedOptionsException If the option is undefined + * @throws AccessException If called from a lazy option or normalizer + */ + public function setInfo(string $option, string $info): static + { + if ($this->locked) { + throw new AccessException('The Info message cannot be set from a lazy option or normalizer.'); + } + + if (!isset($this->defined[$option])) { + throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined)))); + } + + $this->info[$option] = $info; + + return $this; + } + + /** + * Gets the info message for an option. + */ + public function getInfo(string $option): ?string + { + if (!isset($this->defined[$option])) { + throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined)))); + } + + return $this->info[$option] ?? null; + } + + /** + * Marks the whole options definition as array prototype. + * + * @return $this + * + * @throws AccessException If called from a lazy option, a normalizer or a root definition + */ + public function setPrototype(bool $prototype): static + { + if ($this->locked) { + throw new AccessException('The prototype property cannot be set from a lazy option or normalizer.'); + } + + if (null === $this->prototype && $prototype) { + throw new AccessException('The prototype property cannot be set from a root definition.'); + } + + $this->prototype = $prototype; + + return $this; + } + + public function isPrototype(): bool + { + return $this->prototype ?? false; + } + + /** + * Removes the option with the given name. + * + * Undefined options are ignored. + * + * @param string|string[] $optionNames One or more option names + * + * @return $this + * + * @throws AccessException If called from a lazy option or normalizer + */ + public function remove(string|array $optionNames): static + { + if ($this->locked) { + throw new AccessException('Options cannot be removed from a lazy option or normalizer.'); + } + + foreach ((array) $optionNames as $option) { + unset($this->defined[$option], $this->defaults[$option], $this->required[$option], $this->resolved[$option]); + unset($this->lazy[$option], $this->normalizers[$option], $this->allowedTypes[$option], $this->allowedValues[$option], $this->info[$option]); + } + + return $this; + } + + /** + * Removes all options. + * + * @return $this + * + * @throws AccessException If called from a lazy option or normalizer + */ + public function clear(): static + { + if ($this->locked) { + throw new AccessException('Options cannot be cleared from a lazy option or normalizer.'); + } + + $this->defined = []; + $this->defaults = []; + $this->nested = []; + $this->required = []; + $this->resolved = []; + $this->lazy = []; + $this->normalizers = []; + $this->allowedTypes = []; + $this->allowedValues = []; + $this->deprecated = []; + $this->info = []; + + return $this; + } + + /** + * Merges options with the default values stored in the container and + * validates them. + * + * Exceptions are thrown if: + * + * - Undefined options are passed; + * - Required options are missing; + * - Options have invalid types; + * - Options have invalid values. + * + * @throws UndefinedOptionsException If an option name is undefined + * @throws InvalidOptionsException If an option doesn't fulfill the + * specified validation rules + * @throws MissingOptionsException If a required option is missing + * @throws OptionDefinitionException If there is a cyclic dependency between + * lazy options and/or normalizers + * @throws NoSuchOptionException If a lazy option reads an unavailable option + * @throws AccessException If called from a lazy option or normalizer + */ + public function resolve(array $options = []): array + { + if ($this->locked) { + throw new AccessException('Options cannot be resolved from a lazy option or normalizer.'); + } + + // Allow this method to be called multiple times + $clone = clone $this; + + // Make sure that no unknown options are passed + $diff = $this->ignoreUndefined ? [] : array_diff_key($options, $clone->defined); + + if (\count($diff) > 0) { + ksort($clone->defined); + ksort($diff); + + throw new UndefinedOptionsException(sprintf((\count($diff) > 1 ? 'The options "%s" do not exist.' : 'The option "%s" does not exist.').' Defined options are: "%s".', $this->formatOptions(array_keys($diff)), implode('", "', array_keys($clone->defined)))); + } + + // Override options set by the user + foreach ($options as $option => $value) { + if ($this->ignoreUndefined && !isset($clone->defined[$option])) { + continue; + } + + $clone->given[$option] = true; + $clone->defaults[$option] = $value; + unset($clone->resolved[$option], $clone->lazy[$option]); + } + + // Check whether any required option is missing + $diff = array_diff_key($clone->required, $clone->defaults); + + if (\count($diff) > 0) { + ksort($diff); + + throw new MissingOptionsException(sprintf(\count($diff) > 1 ? 'The required options "%s" are missing.' : 'The required option "%s" is missing.', $this->formatOptions(array_keys($diff)))); + } + + // Lock the container + $clone->locked = true; + + // Now process the individual options. Use offsetGet(), which resolves + // the option itself and any options that the option depends on + foreach ($clone->defaults as $option => $_) { + $clone->offsetGet($option); + } + + return $clone->resolved; + } + + /** + * Returns the resolved value of an option. + * + * @param bool $triggerDeprecation Whether to trigger the deprecation or not (true by default) + * + * @throws AccessException If accessing this method outside of + * {@link resolve()} + * @throws NoSuchOptionException If the option is not set + * @throws InvalidOptionsException If the option doesn't fulfill the + * specified validation rules + * @throws OptionDefinitionException If there is a cyclic dependency between + * lazy options and/or normalizers + */ + public function offsetGet(mixed $option, bool $triggerDeprecation = true): mixed + { + if (!$this->locked) { + throw new AccessException('Array access is only supported within closures of lazy options and normalizers.'); + } + + // Shortcut for resolved options + if (isset($this->resolved[$option]) || \array_key_exists($option, $this->resolved)) { + if ($triggerDeprecation && isset($this->deprecated[$option]) && (isset($this->given[$option]) || $this->calling) && \is_string($this->deprecated[$option]['message'])) { + trigger_deprecation($this->deprecated[$option]['package'], $this->deprecated[$option]['version'], strtr($this->deprecated[$option]['message'], ['%name%' => $option])); + } + + return $this->resolved[$option]; + } + + // Check whether the option is set at all + if (!isset($this->defaults[$option]) && !\array_key_exists($option, $this->defaults)) { + if (!isset($this->defined[$option])) { + throw new NoSuchOptionException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined)))); + } + + throw new NoSuchOptionException(sprintf('The optional option "%s" has no value set. You should make sure it is set with "isset" before reading it.', $this->formatOptions([$option]))); + } + + $value = $this->defaults[$option]; + + // Resolve the option if it is a nested definition + if (isset($this->nested[$option])) { + // If the closure is already being called, we have a cyclic dependency + if (isset($this->calling[$option])) { + throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', $this->formatOptions(array_keys($this->calling)))); + } + + if (!\is_array($value)) { + throw new InvalidOptionsException(sprintf('The nested option "%s" with value %s is expected to be of type array, but is of type "%s".', $this->formatOptions([$option]), $this->formatValue($value), get_debug_type($value))); + } + + // The following section must be protected from cyclic calls. + $this->calling[$option] = true; + try { + $resolver = new self(); + $resolver->prototype = false; + $resolver->parentsOptions = $this->parentsOptions; + $resolver->parentsOptions[] = $option; + foreach ($this->nested[$option] as $closure) { + $closure($resolver, $this); + } + + if ($resolver->prototype) { + $values = []; + foreach ($value as $index => $prototypeValue) { + if (!\is_array($prototypeValue)) { + throw new InvalidOptionsException(sprintf('The value of the option "%s" is expected to be of type array of array, but is of type array of "%s".', $this->formatOptions([$option]), get_debug_type($prototypeValue))); + } + + $resolver->prototypeIndex = $index; + $values[$index] = $resolver->resolve($prototypeValue); + } + $value = $values; + } else { + $value = $resolver->resolve($value); + } + } finally { + $resolver->prototypeIndex = null; + unset($this->calling[$option]); + } + } + + // Resolve the option if the default value is lazily evaluated + if (isset($this->lazy[$option])) { + // If the closure is already being called, we have a cyclic + // dependency + if (isset($this->calling[$option])) { + throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', $this->formatOptions(array_keys($this->calling)))); + } + + // The following section must be protected from cyclic + // calls. Set $calling for the current $option to detect a cyclic + // dependency + // BEGIN + $this->calling[$option] = true; + try { + foreach ($this->lazy[$option] as $closure) { + $value = $closure($this, $value); + } + } finally { + unset($this->calling[$option]); + } + // END + } + + // Validate the type of the resolved option + if (isset($this->allowedTypes[$option])) { + $valid = true; + $invalidTypes = []; + + foreach ($this->allowedTypes[$option] as $type) { + if ($valid = $this->verifyTypes($type, $value, $invalidTypes)) { + break; + } + } + + if (!$valid) { + $fmtActualValue = $this->formatValue($value); + $fmtAllowedTypes = implode('" or "', $this->allowedTypes[$option]); + $fmtProvidedTypes = implode('|', array_keys($invalidTypes)); + $allowedContainsArrayType = \count(array_filter($this->allowedTypes[$option], static fn ($item) => str_ends_with($item, '[]'))) > 0; + + if (\is_array($value) && $allowedContainsArrayType) { + throw new InvalidOptionsException(sprintf('The option "%s" with value %s is expected to be of type "%s", but one of the elements is of type "%s".', $this->formatOptions([$option]), $fmtActualValue, $fmtAllowedTypes, $fmtProvidedTypes)); + } + + throw new InvalidOptionsException(sprintf('The option "%s" with value %s is expected to be of type "%s", but is of type "%s".', $this->formatOptions([$option]), $fmtActualValue, $fmtAllowedTypes, $fmtProvidedTypes)); + } + } + + // Validate the value of the resolved option + if (isset($this->allowedValues[$option])) { + $success = false; + $printableAllowedValues = []; + + foreach ($this->allowedValues[$option] as $allowedValue) { + if ($allowedValue instanceof \Closure) { + if ($allowedValue($value)) { + $success = true; + break; + } + + // Don't include closures in the exception message + continue; + } + + if ($value === $allowedValue) { + $success = true; + break; + } + + $printableAllowedValues[] = $allowedValue; + } + + if (!$success) { + $message = sprintf( + 'The option "%s" with value %s is invalid.', + $this->formatOptions([$option]), + $this->formatValue($value) + ); + + if (\count($printableAllowedValues) > 0) { + $message .= sprintf( + ' Accepted values are: %s.', + $this->formatValues($printableAllowedValues) + ); + } + + if (isset($this->info[$option])) { + $message .= sprintf(' Info: %s.', $this->info[$option]); + } + + throw new InvalidOptionsException($message); + } + } + + // Check whether the option is deprecated + // and it is provided by the user or is being called from a lazy evaluation + if ($triggerDeprecation && isset($this->deprecated[$option]) && (isset($this->given[$option]) || ($this->calling && \is_string($this->deprecated[$option]['message'])))) { + $deprecation = $this->deprecated[$option]; + $message = $this->deprecated[$option]['message']; + + if ($message instanceof \Closure) { + // If the closure is already being called, we have a cyclic dependency + if (isset($this->calling[$option])) { + throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', $this->formatOptions(array_keys($this->calling)))); + } + + $this->calling[$option] = true; + try { + if (!\is_string($message = $message($this, $value))) { + throw new InvalidOptionsException(sprintf('Invalid type for deprecation message, expected string but got "%s", return an empty string to ignore.', get_debug_type($message))); + } + } finally { + unset($this->calling[$option]); + } + } + + if ('' !== $message) { + trigger_deprecation($deprecation['package'], $deprecation['version'], strtr($message, ['%name%' => $option])); + } + } + + // Normalize the validated option + if (isset($this->normalizers[$option])) { + // If the closure is already being called, we have a cyclic + // dependency + if (isset($this->calling[$option])) { + throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', $this->formatOptions(array_keys($this->calling)))); + } + + // The following section must be protected from cyclic + // calls. Set $calling for the current $option to detect a cyclic + // dependency + // BEGIN + $this->calling[$option] = true; + try { + foreach ($this->normalizers[$option] as $normalizer) { + $value = $normalizer($this, $value); + } + } finally { + unset($this->calling[$option]); + } + // END + } + + // Mark as resolved + $this->resolved[$option] = $value; + + return $value; + } + + private function verifyTypes(string $type, mixed $value, array &$invalidTypes, int $level = 0): bool + { + if (\is_array($value) && str_ends_with($type, '[]')) { + $type = substr($type, 0, -2); + $valid = true; + + foreach ($value as $val) { + if (!$this->verifyTypes($type, $val, $invalidTypes, $level + 1)) { + $valid = false; + } + } + + return $valid; + } + + if (('null' === $type && null === $value) || (isset(self::VALIDATION_FUNCTIONS[$type]) ? self::VALIDATION_FUNCTIONS[$type]($value) : $value instanceof $type)) { + return true; + } + + if (!$invalidTypes || $level > 0) { + $invalidTypes[get_debug_type($value)] = true; + } + + return false; + } + + /** + * Returns whether a resolved option with the given name exists. + * + * @throws AccessException If accessing this method outside of {@link resolve()} + * + * @see \ArrayAccess::offsetExists() + */ + public function offsetExists(mixed $option): bool + { + if (!$this->locked) { + throw new AccessException('Array access is only supported within closures of lazy options and normalizers.'); + } + + return \array_key_exists($option, $this->defaults); + } + + /** + * Not supported. + * + * @throws AccessException + */ + public function offsetSet(mixed $option, mixed $value): void + { + throw new AccessException('Setting options via array access is not supported. Use setDefault() instead.'); + } + + /** + * Not supported. + * + * @throws AccessException + */ + public function offsetUnset(mixed $option): void + { + throw new AccessException('Removing options via array access is not supported. Use remove() instead.'); + } + + /** + * Returns the number of set options. + * + * This may be only a subset of the defined options. + * + * @throws AccessException If accessing this method outside of {@link resolve()} + * + * @see \Countable::count() + */ + public function count(): int + { + if (!$this->locked) { + throw new AccessException('Counting is only supported within closures of lazy options and normalizers.'); + } + + return \count($this->defaults); + } + + /** + * Sets whether ignore undefined options. + * + * @return $this + */ + public function setIgnoreUndefined(bool $ignore = true): static + { + $this->ignoreUndefined = $ignore; + + return $this; + } + + /** + * Returns a string representation of the value. + * + * This method returns the equivalent PHP tokens for most scalar types + * (i.e. "false" for false, "1" for 1 etc.). Strings are always wrapped + * in double quotes ("). + */ + private function formatValue(mixed $value): string + { + if (\is_object($value)) { + return $value::class; + } + + if (\is_array($value)) { + return 'array'; + } + + if (\is_string($value)) { + return '"'.$value.'"'; + } + + if (\is_resource($value)) { + return 'resource'; + } + + if (null === $value) { + return 'null'; + } + + if (false === $value) { + return 'false'; + } + + if (true === $value) { + return 'true'; + } + + return (string) $value; + } + + /** + * Returns a string representation of a list of values. + * + * Each of the values is converted to a string using + * {@link formatValue()}. The values are then concatenated with commas. + * + * @see formatValue() + */ + private function formatValues(array $values): string + { + foreach ($values as $key => $value) { + $values[$key] = $this->formatValue($value); + } + + return implode(', ', $values); + } + + private function formatOptions(array $options): string + { + if ($this->parentsOptions) { + $prefix = array_shift($this->parentsOptions); + if ($this->parentsOptions) { + $prefix .= sprintf('[%s]', implode('][', $this->parentsOptions)); + } + + if ($this->prototype && null !== $this->prototypeIndex) { + $prefix .= sprintf('[%s]', $this->prototypeIndex); + } + + $options = array_map(static fn (string $option): string => sprintf('%s[%s]', $prefix, $option), $options); + } + + return implode('", "', $options); + } + + private function getParameterClassName(\ReflectionParameter $parameter): ?string + { + if (!($type = $parameter->getType()) instanceof \ReflectionNamedType || $type->isBuiltin()) { + return null; + } + + return $type->getName(); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/README.md b/tools/php-cs-fixer/vendor/symfony/options-resolver/README.md new file mode 100644 index 00000000..c63b9005 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/README.md @@ -0,0 +1,15 @@ +OptionsResolver Component +========================= + +The OptionsResolver component is `array_replace` on steroids. It allows you to +create an options system with required options, defaults, validation (type, +value), normalization and more. + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/options_resolver.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/tools/php-cs-fixer/vendor/symfony/options-resolver/composer.json b/tools/php-cs-fixer/vendor/symfony/options-resolver/composer.json new file mode 100644 index 00000000..e70640d6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/options-resolver/composer.json @@ -0,0 +1,29 @@ +{ + "name": "symfony/options-resolver", + "type": "library", + "description": "Provides an improved replacement for the array_replace PHP function", + "keywords": ["options", "config", "configuration"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.2", + "symfony/deprecation-contracts": "^2.5|^3" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\OptionsResolver\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/Ctype.php b/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/Ctype.php new file mode 100644 index 00000000..ba75a2c9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/Ctype.php @@ -0,0 +1,232 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Ctype; + +/** + * Ctype implementation through regex. + * + * @internal + * + * @author Gert de Pagter + */ +final class Ctype +{ + /** + * Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise. + * + * @see https://php.net/ctype-alnum + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_alnum($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z0-9]/', $text); + } + + /** + * Returns TRUE if every character in text is a letter, FALSE otherwise. + * + * @see https://php.net/ctype-alpha + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_alpha($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z]/', $text); + } + + /** + * Returns TRUE if every character in text is a control character from the current locale, FALSE otherwise. + * + * @see https://php.net/ctype-cntrl + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_cntrl($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^\x00-\x1f\x7f]/', $text); + } + + /** + * Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise. + * + * @see https://php.net/ctype-digit + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_digit($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^0-9]/', $text); + } + + /** + * Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise. + * + * @see https://php.net/ctype-graph + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_graph($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^!-~]/', $text); + } + + /** + * Returns TRUE if every character in text is a lowercase letter. + * + * @see https://php.net/ctype-lower + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_lower($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^a-z]/', $text); + } + + /** + * Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all. + * + * @see https://php.net/ctype-print + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_print($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^ -~]/', $text); + } + + /** + * Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise. + * + * @see https://php.net/ctype-punct + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_punct($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^!-\/\:-@\[-`\{-~]/', $text); + } + + /** + * Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters. + * + * @see https://php.net/ctype-space + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_space($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^\s]/', $text); + } + + /** + * Returns TRUE if every character in text is an uppercase letter. + * + * @see https://php.net/ctype-upper + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_upper($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Z]/', $text); + } + + /** + * Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise. + * + * @see https://php.net/ctype-xdigit + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_xdigit($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Fa-f0-9]/', $text); + } + + /** + * Converts integers to their char versions according to normal ctype behaviour, if needed. + * + * If an integer between -128 and 255 inclusive is provided, + * it is interpreted as the ASCII value of a single character + * (negative values have 256 added in order to allow characters in the Extended ASCII range). + * Any other integer is interpreted as a string containing the decimal digits of the integer. + * + * @param mixed $int + * @param string $function + * + * @return mixed + */ + private static function convert_int_to_char_for_ctype($int, $function) + { + if (!\is_int($int)) { + return $int; + } + + if ($int < -128 || $int > 255) { + return (string) $int; + } + + if (\PHP_VERSION_ID >= 80100) { + @trigger_error($function.'(): Argument of type int will be interpreted as string in the future', \E_USER_DEPRECATED); + } + + if ($int < 0) { + $int += 256; + } + + return \chr($int); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/LICENSE b/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/LICENSE new file mode 100644 index 00000000..7536caea --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2018-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/README.md b/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/README.md new file mode 100644 index 00000000..b144d03c --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/README.md @@ -0,0 +1,12 @@ +Symfony Polyfill / Ctype +======================== + +This component provides `ctype_*` functions to users who run php versions without the ctype extension. + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/bootstrap.php b/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/bootstrap.php new file mode 100644 index 00000000..d54524b3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/bootstrap.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Ctype as p; + +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + +if (!function_exists('ctype_alnum')) { + function ctype_alnum($text) { return p\Ctype::ctype_alnum($text); } +} +if (!function_exists('ctype_alpha')) { + function ctype_alpha($text) { return p\Ctype::ctype_alpha($text); } +} +if (!function_exists('ctype_cntrl')) { + function ctype_cntrl($text) { return p\Ctype::ctype_cntrl($text); } +} +if (!function_exists('ctype_digit')) { + function ctype_digit($text) { return p\Ctype::ctype_digit($text); } +} +if (!function_exists('ctype_graph')) { + function ctype_graph($text) { return p\Ctype::ctype_graph($text); } +} +if (!function_exists('ctype_lower')) { + function ctype_lower($text) { return p\Ctype::ctype_lower($text); } +} +if (!function_exists('ctype_print')) { + function ctype_print($text) { return p\Ctype::ctype_print($text); } +} +if (!function_exists('ctype_punct')) { + function ctype_punct($text) { return p\Ctype::ctype_punct($text); } +} +if (!function_exists('ctype_space')) { + function ctype_space($text) { return p\Ctype::ctype_space($text); } +} +if (!function_exists('ctype_upper')) { + function ctype_upper($text) { return p\Ctype::ctype_upper($text); } +} +if (!function_exists('ctype_xdigit')) { + function ctype_xdigit($text) { return p\Ctype::ctype_xdigit($text); } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/bootstrap80.php b/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/bootstrap80.php new file mode 100644 index 00000000..ab2f8611 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/bootstrap80.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Ctype as p; + +if (!function_exists('ctype_alnum')) { + function ctype_alnum(mixed $text): bool { return p\Ctype::ctype_alnum($text); } +} +if (!function_exists('ctype_alpha')) { + function ctype_alpha(mixed $text): bool { return p\Ctype::ctype_alpha($text); } +} +if (!function_exists('ctype_cntrl')) { + function ctype_cntrl(mixed $text): bool { return p\Ctype::ctype_cntrl($text); } +} +if (!function_exists('ctype_digit')) { + function ctype_digit(mixed $text): bool { return p\Ctype::ctype_digit($text); } +} +if (!function_exists('ctype_graph')) { + function ctype_graph(mixed $text): bool { return p\Ctype::ctype_graph($text); } +} +if (!function_exists('ctype_lower')) { + function ctype_lower(mixed $text): bool { return p\Ctype::ctype_lower($text); } +} +if (!function_exists('ctype_print')) { + function ctype_print(mixed $text): bool { return p\Ctype::ctype_print($text); } +} +if (!function_exists('ctype_punct')) { + function ctype_punct(mixed $text): bool { return p\Ctype::ctype_punct($text); } +} +if (!function_exists('ctype_space')) { + function ctype_space(mixed $text): bool { return p\Ctype::ctype_space($text); } +} +if (!function_exists('ctype_upper')) { + function ctype_upper(mixed $text): bool { return p\Ctype::ctype_upper($text); } +} +if (!function_exists('ctype_xdigit')) { + function ctype_xdigit(mixed $text): bool { return p\Ctype::ctype_xdigit($text); } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/composer.json b/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/composer.json new file mode 100644 index 00000000..e5c978f1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-ctype/composer.json @@ -0,0 +1,41 @@ +{ + "name": "symfony/polyfill-ctype", + "type": "library", + "description": "Symfony polyfill for ctype functions", + "keywords": ["polyfill", "compatibility", "portable", "ctype"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-ctype": "*" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Ctype\\": "" }, + "files": [ "bootstrap.php" ] + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/Grapheme.php b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/Grapheme.php new file mode 100644 index 00000000..5373f168 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/Grapheme.php @@ -0,0 +1,247 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Intl\Grapheme; + +\define('SYMFONY_GRAPHEME_CLUSTER_RX', ((float) \PCRE_VERSION < 10 ? (float) \PCRE_VERSION >= 8.32 : (float) \PCRE_VERSION >= 10.39) ? '\X' : Grapheme::GRAPHEME_CLUSTER_RX); + +/** + * Partial intl implementation in pure PHP. + * + * Implemented: + * - grapheme_extract - Extract a sequence of grapheme clusters from a text buffer, which must be encoded in UTF-8 + * - grapheme_stripos - Find position (in grapheme units) of first occurrence of a case-insensitive string + * - grapheme_stristr - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack + * - grapheme_strlen - Get string length in grapheme units + * - grapheme_strpos - Find position (in grapheme units) of first occurrence of a string + * - grapheme_strripos - Find position (in grapheme units) of last occurrence of a case-insensitive string + * - grapheme_strrpos - Find position (in grapheme units) of last occurrence of a string + * - grapheme_strstr - Returns part of haystack string from the first occurrence of needle to the end of haystack + * - grapheme_substr - Return part of a string + * + * @author Nicolas Grekas + * + * @internal + */ +final class Grapheme +{ + // (CRLF|([ZWNJ-ZWJ]|T+|L*(LV?V+|LV|LVT)T*|L+|[^Control])[Extend]*|[Control]) + // This regular expression is a work around for http://bugs.exim.org/1279 + public const GRAPHEME_CLUSTER_RX = '(?:\r\n|(?:[ -~\x{200C}\x{200D}]|[ᆨ-ᇹ]+|[ᄀ-ᅟ]*(?:[가개갸걔거게겨계고과괘괴교구궈궤귀규그긔기까깨꺄꺠꺼께껴꼐꼬꽈꽤꾀꾜꾸꿔꿰뀌뀨끄끠끼나내냐냬너네녀녜노놔놰뇌뇨누눠눼뉘뉴느늬니다대댜댸더데뎌뎨도돠돼되됴두둬뒈뒤듀드듸디따때땨떄떠떼뗘뗴또똬뙈뙤뚀뚜뚸뛔뛰뜌뜨띄띠라래랴럐러레려례로롸뢔뢰료루뤄뤠뤼류르릐리마매먀먜머메며몌모뫄뫠뫼묘무뭐뭬뮈뮤므믜미바배뱌뱨버베벼볘보봐봬뵈뵤부붜붸뷔뷰브븨비빠빼뺘뺴뻐뻬뼈뼤뽀뽜뽸뾔뾰뿌뿨쀄쀠쀼쁘쁴삐사새샤섀서세셔셰소솨쇄쇠쇼수숴쉐쉬슈스싀시싸쌔쌰썌써쎄쎠쎼쏘쏴쐐쐬쑈쑤쒀쒜쒸쓔쓰씌씨아애야얘어에여예오와왜외요우워웨위유으의이자재쟈쟤저제져졔조좌좨죄죠주줘줴쥐쥬즈즤지짜째쨔쨰쩌쩨쪄쪠쪼쫘쫴쬐쬬쭈쭤쮀쮜쮸쯔쯰찌차채챠챼처체쳐쳬초촤쵀최쵸추춰췌취츄츠츼치카캐캬컈커케켜켸코콰쾌쾨쿄쿠쿼퀘퀴큐크킈키타태탸턔터테텨톄토톼퇘퇴툐투퉈퉤튀튜트틔티파패퍄퍠퍼페펴폐포퐈퐤푀표푸풔풰퓌퓨프픠피하해햐햬허헤혀혜호화홰회효후훠훼휘휴흐희히]?[ᅠ-ᆢ]+|[가-힣])[ᆨ-ᇹ]*|[ᄀ-ᅟ]+|[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}])[\p{Mn}\p{Me}\x{09BE}\x{09D7}\x{0B3E}\x{0B57}\x{0BBE}\x{0BD7}\x{0CC2}\x{0CD5}\x{0CD6}\x{0D3E}\x{0D57}\x{0DCF}\x{0DDF}\x{200C}\x{200D}\x{1D165}\x{1D16E}-\x{1D172}]*|[\p{Cc}\p{Cf}\p{Zl}\p{Zp}])'; + + private const CASE_FOLD = [ + ['µ', 'ſ', "\xCD\x85", 'ς', "\xCF\x90", "\xCF\x91", "\xCF\x95", "\xCF\x96", "\xCF\xB0", "\xCF\xB1", "\xCF\xB5", "\xE1\xBA\x9B", "\xE1\xBE\xBE"], + ['μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', "\xE1\xB9\xA1", 'ι'], + ]; + + public static function grapheme_extract($s, $size, $type = \GRAPHEME_EXTR_COUNT, $start = 0, &$next = 0) + { + if (0 > $start) { + $start = \strlen($s) + $start; + } + + if (!\is_scalar($s)) { + $hasError = false; + set_error_handler(function () use (&$hasError) { $hasError = true; }); + $next = substr($s, $start); + restore_error_handler(); + if ($hasError) { + substr($s, $start); + $s = ''; + } else { + $s = $next; + } + } else { + $s = substr($s, $start); + } + $size = (int) $size; + $type = (int) $type; + $start = (int) $start; + + if (\GRAPHEME_EXTR_COUNT !== $type && \GRAPHEME_EXTR_MAXBYTES !== $type && \GRAPHEME_EXTR_MAXCHARS !== $type) { + if (80000 > \PHP_VERSION_ID) { + return false; + } + + throw new \ValueError('grapheme_extract(): Argument #3 ($type) must be one of GRAPHEME_EXTR_COUNT, GRAPHEME_EXTR_MAXBYTES, or GRAPHEME_EXTR_MAXCHARS'); + } + + if (!isset($s[0]) || 0 > $size || 0 > $start) { + return false; + } + if (0 === $size) { + return ''; + } + + $next = $start; + + $s = preg_split('/('.SYMFONY_GRAPHEME_CLUSTER_RX.')/u', "\r\n".$s, $size + 1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE); + + if (!isset($s[1])) { + return false; + } + + $i = 1; + $ret = ''; + + do { + if (\GRAPHEME_EXTR_COUNT === $type) { + --$size; + } elseif (\GRAPHEME_EXTR_MAXBYTES === $type) { + $size -= \strlen($s[$i]); + } else { + $size -= iconv_strlen($s[$i], 'UTF-8//IGNORE'); + } + + if ($size >= 0) { + $ret .= $s[$i]; + } + } while (isset($s[++$i]) && $size > 0); + + $next += \strlen($ret); + + return $ret; + } + + public static function grapheme_strlen($s) + { + preg_replace('/'.SYMFONY_GRAPHEME_CLUSTER_RX.'/u', '', $s, -1, $len); + + return 0 === $len && '' !== $s ? null : $len; + } + + public static function grapheme_substr($s, $start, $len = null) + { + if (null === $len) { + $len = 2147483647; + } + + preg_match_all('/'.SYMFONY_GRAPHEME_CLUSTER_RX.'/u', $s, $s); + + $slen = \count($s[0]); + $start = (int) $start; + + if (0 > $start) { + $start += $slen; + } + if (0 > $start) { + if (\PHP_VERSION_ID < 80000) { + return false; + } + + $start = 0; + } + if ($start >= $slen) { + return \PHP_VERSION_ID >= 80000 ? '' : false; + } + + $rem = $slen - $start; + + if (0 > $len) { + $len += $rem; + } + if (0 === $len) { + return ''; + } + if (0 > $len) { + return \PHP_VERSION_ID >= 80000 ? '' : false; + } + if ($len > $rem) { + $len = $rem; + } + + return implode('', \array_slice($s[0], $start, $len)); + } + + public static function grapheme_strpos($s, $needle, $offset = 0) + { + return self::grapheme_position($s, $needle, $offset, 0); + } + + public static function grapheme_stripos($s, $needle, $offset = 0) + { + return self::grapheme_position($s, $needle, $offset, 1); + } + + public static function grapheme_strrpos($s, $needle, $offset = 0) + { + return self::grapheme_position($s, $needle, $offset, 2); + } + + public static function grapheme_strripos($s, $needle, $offset = 0) + { + return self::grapheme_position($s, $needle, $offset, 3); + } + + public static function grapheme_stristr($s, $needle, $beforeNeedle = false) + { + return mb_stristr($s, $needle, $beforeNeedle, 'UTF-8'); + } + + public static function grapheme_strstr($s, $needle, $beforeNeedle = false) + { + return mb_strstr($s, $needle, $beforeNeedle, 'UTF-8'); + } + + private static function grapheme_position($s, $needle, $offset, $mode) + { + $needle = (string) $needle; + if (80000 > \PHP_VERSION_ID && !preg_match('/./us', $needle)) { + return false; + } + $s = (string) $s; + if (!preg_match('/./us', $s)) { + return false; + } + if ($offset > 0) { + $s = self::grapheme_substr($s, $offset); + } elseif ($offset < 0) { + if (2 > $mode) { + $offset += self::grapheme_strlen($s); + $s = self::grapheme_substr($s, $offset); + if (0 > $offset) { + $offset = 0; + } + } elseif (0 > $offset += self::grapheme_strlen($needle)) { + $s = self::grapheme_substr($s, 0, $offset); + $offset = 0; + } else { + $offset = 0; + } + } + + // As UTF-8 is self-synchronizing, and we have ensured the strings are valid UTF-8, + // we can use normal binary string functions here. For case-insensitive searches, + // case fold the strings first. + $caseInsensitive = $mode & 1; + $reverse = $mode & 2; + if ($caseInsensitive) { + // Use the same case folding mode as mbstring does for mb_stripos(). + // Stick to SIMPLE case folding to avoid changing the length of the string, which + // might result in offsets being shifted. + $mode = \defined('MB_CASE_FOLD_SIMPLE') ? \MB_CASE_FOLD_SIMPLE : \MB_CASE_LOWER; + $s = mb_convert_case($s, $mode, 'UTF-8'); + $needle = mb_convert_case($needle, $mode, 'UTF-8'); + + if (!\defined('MB_CASE_FOLD_SIMPLE')) { + $s = str_replace(self::CASE_FOLD[0], self::CASE_FOLD[1], $s); + $needle = str_replace(self::CASE_FOLD[0], self::CASE_FOLD[1], $needle); + } + } + if ($reverse) { + $needlePos = strrpos($s, $needle); + } else { + $needlePos = strpos($s, $needle); + } + + return false !== $needlePos ? self::grapheme_strlen(substr($s, 0, $needlePos)) + $offset : false; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/LICENSE b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/LICENSE new file mode 100644 index 00000000..6e3afce6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/README.md b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/README.md new file mode 100644 index 00000000..f55d92c5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/README.md @@ -0,0 +1,31 @@ +Symfony Polyfill / Intl: Grapheme +================================= + +This component provides a partial, native PHP implementation of the +[Grapheme functions](https://php.net/intl.grapheme) from the +[Intl](https://php.net/intl) extension. + +- [`grapheme_extract`](https://php.net/grapheme_extract): Extract a sequence of grapheme + clusters from a text buffer, which must be encoded in UTF-8 +- [`grapheme_stripos`](https://php.net/grapheme_stripos): Find position (in grapheme units) + of first occurrence of a case-insensitive string +- [`grapheme_stristr`](https://php.net/grapheme_stristr): Returns part of haystack string + from the first occurrence of case-insensitive needle to the end of haystack +- [`grapheme_strlen`](https://php.net/grapheme_strlen): Get string length in grapheme units +- [`grapheme_strpos`](https://php.net/grapheme_strpos): Find position (in grapheme units) + of first occurrence of a string +- [`grapheme_strripos`](https://php.net/grapheme_strripos): Find position (in grapheme units) + of last occurrence of a case-insensitive string +- [`grapheme_strrpos`](https://php.net/grapheme_strrpos): Find position (in grapheme units) + of last occurrence of a string +- [`grapheme_strstr`](https://php.net/grapheme_strstr): Returns part of haystack string from + the first occurrence of needle to the end of haystack +- [`grapheme_substr`](https://php.net/grapheme_substr): Return part of a string + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/bootstrap.php b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/bootstrap.php new file mode 100644 index 00000000..a9ea03c7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/bootstrap.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Intl\Grapheme as p; + +if (extension_loaded('intl')) { + return; +} + +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + +if (!defined('GRAPHEME_EXTR_COUNT')) { + define('GRAPHEME_EXTR_COUNT', 0); +} +if (!defined('GRAPHEME_EXTR_MAXBYTES')) { + define('GRAPHEME_EXTR_MAXBYTES', 1); +} +if (!defined('GRAPHEME_EXTR_MAXCHARS')) { + define('GRAPHEME_EXTR_MAXCHARS', 2); +} + +if (!function_exists('grapheme_extract')) { + function grapheme_extract($haystack, $size, $type = 0, $start = 0, &$next = 0) { return p\Grapheme::grapheme_extract($haystack, $size, $type, $start, $next); } +} +if (!function_exists('grapheme_stripos')) { + function grapheme_stripos($haystack, $needle, $offset = 0) { return p\Grapheme::grapheme_stripos($haystack, $needle, $offset); } +} +if (!function_exists('grapheme_stristr')) { + function grapheme_stristr($haystack, $needle, $beforeNeedle = false) { return p\Grapheme::grapheme_stristr($haystack, $needle, $beforeNeedle); } +} +if (!function_exists('grapheme_strlen')) { + function grapheme_strlen($input) { return p\Grapheme::grapheme_strlen($input); } +} +if (!function_exists('grapheme_strpos')) { + function grapheme_strpos($haystack, $needle, $offset = 0) { return p\Grapheme::grapheme_strpos($haystack, $needle, $offset); } +} +if (!function_exists('grapheme_strripos')) { + function grapheme_strripos($haystack, $needle, $offset = 0) { return p\Grapheme::grapheme_strripos($haystack, $needle, $offset); } +} +if (!function_exists('grapheme_strrpos')) { + function grapheme_strrpos($haystack, $needle, $offset = 0) { return p\Grapheme::grapheme_strrpos($haystack, $needle, $offset); } +} +if (!function_exists('grapheme_strstr')) { + function grapheme_strstr($haystack, $needle, $beforeNeedle = false) { return p\Grapheme::grapheme_strstr($haystack, $needle, $beforeNeedle); } +} +if (!function_exists('grapheme_substr')) { + function grapheme_substr($string, $offset, $length = null) { return p\Grapheme::grapheme_substr($string, $offset, $length); } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/bootstrap80.php b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/bootstrap80.php new file mode 100644 index 00000000..b8c07867 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/bootstrap80.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Intl\Grapheme as p; + +if (!defined('GRAPHEME_EXTR_COUNT')) { + define('GRAPHEME_EXTR_COUNT', 0); +} +if (!defined('GRAPHEME_EXTR_MAXBYTES')) { + define('GRAPHEME_EXTR_MAXBYTES', 1); +} +if (!defined('GRAPHEME_EXTR_MAXCHARS')) { + define('GRAPHEME_EXTR_MAXCHARS', 2); +} + +if (!function_exists('grapheme_extract')) { + function grapheme_extract(?string $haystack, ?int $size, ?int $type = GRAPHEME_EXTR_COUNT, ?int $offset = 0, &$next = null): string|false { return p\Grapheme::grapheme_extract((string) $haystack, (int) $size, (int) $type, (int) $offset, $next); } +} +if (!function_exists('grapheme_stripos')) { + function grapheme_stripos(?string $haystack, ?string $needle, ?int $offset = 0): int|false { return p\Grapheme::grapheme_stripos((string) $haystack, (string) $needle, (int) $offset); } +} +if (!function_exists('grapheme_stristr')) { + function grapheme_stristr(?string $haystack, ?string $needle, ?bool $beforeNeedle = false): string|false { return p\Grapheme::grapheme_stristr((string) $haystack, (string) $needle, (bool) $beforeNeedle); } +} +if (!function_exists('grapheme_strlen')) { + function grapheme_strlen(?string $string): int|false|null { return p\Grapheme::grapheme_strlen((string) $string); } +} +if (!function_exists('grapheme_strpos')) { + function grapheme_strpos(?string $haystack, ?string $needle, ?int $offset = 0): int|false { return p\Grapheme::grapheme_strpos((string) $haystack, (string) $needle, (int) $offset); } +} +if (!function_exists('grapheme_strripos')) { + function grapheme_strripos(?string $haystack, ?string $needle, ?int $offset = 0): int|false { return p\Grapheme::grapheme_strripos((string) $haystack, (string) $needle, (int) $offset); } +} +if (!function_exists('grapheme_strrpos')) { + function grapheme_strrpos(?string $haystack, ?string $needle, ?int $offset = 0): int|false { return p\Grapheme::grapheme_strrpos((string) $haystack, (string) $needle, (int) $offset); } +} +if (!function_exists('grapheme_strstr')) { + function grapheme_strstr(?string $haystack, ?string $needle, ?bool $beforeNeedle = false): string|false { return p\Grapheme::grapheme_strstr((string) $haystack, (string) $needle, (bool) $beforeNeedle); } +} +if (!function_exists('grapheme_substr')) { + function grapheme_substr(?string $string, ?int $offset, ?int $length = null): string|false { return p\Grapheme::grapheme_substr((string) $string, (int) $offset, $length); } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/composer.json b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/composer.json new file mode 100644 index 00000000..c00d4e9e --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-grapheme/composer.json @@ -0,0 +1,38 @@ +{ + "name": "symfony/polyfill-intl-grapheme", + "type": "library", + "description": "Symfony polyfill for intl's grapheme_* functions", + "keywords": ["polyfill", "shim", "compatibility", "portable", "intl", "grapheme"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Intl\\Grapheme\\": "" }, + "files": [ "bootstrap.php" ] + }, + "suggest": { + "ext-intl": "For best performance" + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/LICENSE b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/LICENSE new file mode 100644 index 00000000..6e3afce6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/Normalizer.php b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/Normalizer.php new file mode 100644 index 00000000..81704ab3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/Normalizer.php @@ -0,0 +1,310 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Intl\Normalizer; + +/** + * Normalizer is a PHP fallback implementation of the Normalizer class provided by the intl extension. + * + * It has been validated with Unicode 6.3 Normalization Conformance Test. + * See http://www.unicode.org/reports/tr15/ for detailed info about Unicode normalizations. + * + * @author Nicolas Grekas + * + * @internal + */ +class Normalizer +{ + public const FORM_D = \Normalizer::FORM_D; + public const FORM_KD = \Normalizer::FORM_KD; + public const FORM_C = \Normalizer::FORM_C; + public const FORM_KC = \Normalizer::FORM_KC; + public const NFD = \Normalizer::NFD; + public const NFKD = \Normalizer::NFKD; + public const NFC = \Normalizer::NFC; + public const NFKC = \Normalizer::NFKC; + + private static $C; + private static $D; + private static $KD; + private static $cC; + private static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4]; + private static $ASCII = "\x20\x65\x69\x61\x73\x6E\x74\x72\x6F\x6C\x75\x64\x5D\x5B\x63\x6D\x70\x27\x0A\x67\x7C\x68\x76\x2E\x66\x62\x2C\x3A\x3D\x2D\x71\x31\x30\x43\x32\x2A\x79\x78\x29\x28\x4C\x39\x41\x53\x2F\x50\x22\x45\x6A\x4D\x49\x6B\x33\x3E\x35\x54\x3C\x44\x34\x7D\x42\x7B\x38\x46\x77\x52\x36\x37\x55\x47\x4E\x3B\x4A\x7A\x56\x23\x48\x4F\x57\x5F\x26\x21\x4B\x3F\x58\x51\x25\x59\x5C\x09\x5A\x2B\x7E\x5E\x24\x40\x60\x7F\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"; + + public static function isNormalized(string $s, int $form = self::FORM_C) + { + if (!\in_array($form, [self::NFD, self::NFKD, self::NFC, self::NFKC])) { + return false; + } + if (!isset($s[strspn($s, self::$ASCII)])) { + return true; + } + if (self::NFC == $form && preg_match('//u', $s) && !preg_match('/[^\x00-\x{2FF}]/u', $s)) { + return true; + } + + return self::normalize($s, $form) === $s; + } + + public static function normalize(string $s, int $form = self::FORM_C) + { + if (!preg_match('//u', $s)) { + return false; + } + + switch ($form) { + case self::NFC: $C = true; $K = false; break; + case self::NFD: $C = false; $K = false; break; + case self::NFKC: $C = true; $K = true; break; + case self::NFKD: $C = false; $K = true; break; + default: + if (\defined('Normalizer::NONE') && \Normalizer::NONE == $form) { + return $s; + } + + if (80000 > \PHP_VERSION_ID) { + return false; + } + + throw new \ValueError('normalizer_normalize(): Argument #2 ($form) must be a a valid normalization form'); + } + + if ('' === $s) { + return ''; + } + + if ($K && null === self::$KD) { + self::$KD = self::getData('compatibilityDecomposition'); + } + + if (null === self::$D) { + self::$D = self::getData('canonicalDecomposition'); + self::$cC = self::getData('combiningClass'); + } + + if (null !== $mbEncoding = (2 /* MB_OVERLOAD_STRING */ & (int) \ini_get('mbstring.func_overload')) ? mb_internal_encoding() : null) { + mb_internal_encoding('8bit'); + } + + $r = self::decompose($s, $K); + + if ($C) { + if (null === self::$C) { + self::$C = self::getData('canonicalComposition'); + } + + $r = self::recompose($r); + } + if (null !== $mbEncoding) { + mb_internal_encoding($mbEncoding); + } + + return $r; + } + + private static function recompose($s) + { + $ASCII = self::$ASCII; + $compMap = self::$C; + $combClass = self::$cC; + $ulenMask = self::$ulenMask; + + $result = $tail = ''; + + $i = $s[0] < "\x80" ? 1 : $ulenMask[$s[0] & "\xF0"]; + $len = \strlen($s); + + $lastUchr = substr($s, 0, $i); + $lastUcls = isset($combClass[$lastUchr]) ? 256 : 0; + + while ($i < $len) { + if ($s[$i] < "\x80") { + // ASCII chars + + if ($tail) { + $lastUchr .= $tail; + $tail = ''; + } + + if ($j = strspn($s, $ASCII, $i + 1)) { + $lastUchr .= substr($s, $i, $j); + $i += $j; + } + + $result .= $lastUchr; + $lastUchr = $s[$i]; + $lastUcls = 0; + ++$i; + continue; + } + + $ulen = $ulenMask[$s[$i] & "\xF0"]; + $uchr = substr($s, $i, $ulen); + + if ($lastUchr < "\xE1\x84\x80" || "\xE1\x84\x92" < $lastUchr + || $uchr < "\xE1\x85\xA1" || "\xE1\x85\xB5" < $uchr + || $lastUcls) { + // Table lookup and combining chars composition + + $ucls = $combClass[$uchr] ?? 0; + + if (isset($compMap[$lastUchr.$uchr]) && (!$lastUcls || $lastUcls < $ucls)) { + $lastUchr = $compMap[$lastUchr.$uchr]; + } elseif ($lastUcls = $ucls) { + $tail .= $uchr; + } else { + if ($tail) { + $lastUchr .= $tail; + $tail = ''; + } + + $result .= $lastUchr; + $lastUchr = $uchr; + } + } else { + // Hangul chars + + $L = \ord($lastUchr[2]) - 0x80; + $V = \ord($uchr[2]) - 0xA1; + $T = 0; + + $uchr = substr($s, $i + $ulen, 3); + + if ("\xE1\x86\xA7" <= $uchr && $uchr <= "\xE1\x87\x82") { + $T = \ord($uchr[2]) - 0xA7; + 0 > $T && $T += 0x40; + $ulen += 3; + } + + $L = 0xAC00 + ($L * 21 + $V) * 28 + $T; + $lastUchr = \chr(0xE0 | $L >> 12).\chr(0x80 | $L >> 6 & 0x3F).\chr(0x80 | $L & 0x3F); + } + + $i += $ulen; + } + + return $result.$lastUchr.$tail; + } + + private static function decompose($s, $c) + { + $result = ''; + + $ASCII = self::$ASCII; + $decompMap = self::$D; + $combClass = self::$cC; + $ulenMask = self::$ulenMask; + if ($c) { + $compatMap = self::$KD; + } + + $c = []; + $i = 0; + $len = \strlen($s); + + while ($i < $len) { + if ($s[$i] < "\x80") { + // ASCII chars + + if ($c) { + ksort($c); + $result .= implode('', $c); + $c = []; + } + + $j = 1 + strspn($s, $ASCII, $i + 1); + $result .= substr($s, $i, $j); + $i += $j; + continue; + } + + $ulen = $ulenMask[$s[$i] & "\xF0"]; + $uchr = substr($s, $i, $ulen); + $i += $ulen; + + if ($uchr < "\xEA\xB0\x80" || "\xED\x9E\xA3" < $uchr) { + // Table lookup + + if ($uchr !== $j = $compatMap[$uchr] ?? ($decompMap[$uchr] ?? $uchr)) { + $uchr = $j; + + $j = \strlen($uchr); + $ulen = $uchr[0] < "\x80" ? 1 : $ulenMask[$uchr[0] & "\xF0"]; + + if ($ulen != $j) { + // Put trailing chars in $s + + $j -= $ulen; + $i -= $j; + + if (0 > $i) { + $s = str_repeat(' ', -$i).$s; + $len -= $i; + $i = 0; + } + + while ($j--) { + $s[$i + $j] = $uchr[$ulen + $j]; + } + + $uchr = substr($uchr, 0, $ulen); + } + } + if (isset($combClass[$uchr])) { + // Combining chars, for sorting + + if (!isset($c[$combClass[$uchr]])) { + $c[$combClass[$uchr]] = ''; + } + $c[$combClass[$uchr]] .= $uchr; + continue; + } + } else { + // Hangul chars + + $uchr = unpack('C*', $uchr); + $j = (($uchr[1] - 224) << 12) + (($uchr[2] - 128) << 6) + $uchr[3] - 0xAC80; + + $uchr = "\xE1\x84".\chr(0x80 + (int) ($j / 588)) + ."\xE1\x85".\chr(0xA1 + (int) (($j % 588) / 28)); + + if ($j %= 28) { + $uchr .= $j < 25 + ? ("\xE1\x86".\chr(0xA7 + $j)) + : ("\xE1\x87".\chr(0x67 + $j)); + } + } + if ($c) { + ksort($c); + $result .= implode('', $c); + $c = []; + } + + $result .= $uchr; + } + + if ($c) { + ksort($c); + $result .= implode('', $c); + } + + return $result; + } + + private static function getData($file) + { + if (file_exists($file = __DIR__.'/Resources/unidata/'.$file.'.php')) { + return require $file; + } + + return false; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/README.md b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/README.md new file mode 100644 index 00000000..b9b762e8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/README.md @@ -0,0 +1,14 @@ +Symfony Polyfill / Intl: Normalizer +=================================== + +This component provides a fallback implementation for the +[`Normalizer`](https://php.net/Normalizer) class provided +by the [Intl](https://php.net/intl) extension. + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php new file mode 100644 index 00000000..0fdfc890 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php @@ -0,0 +1,17 @@ + 'À', + 'Á' => 'Á', + 'Â' => 'Â', + 'Ã' => 'Ã', + 'Ä' => 'Ä', + 'Å' => 'Å', + 'Ç' => 'Ç', + 'È' => 'È', + 'É' => 'É', + 'Ê' => 'Ê', + 'Ë' => 'Ë', + 'Ì' => 'Ì', + 'Í' => 'Í', + 'Î' => 'Î', + 'Ï' => 'Ï', + 'Ñ' => 'Ñ', + 'Ò' => 'Ò', + 'Ó' => 'Ó', + 'Ô' => 'Ô', + 'Õ' => 'Õ', + 'Ö' => 'Ö', + 'Ù' => 'Ù', + 'Ú' => 'Ú', + 'Û' => 'Û', + 'Ü' => 'Ü', + 'Ý' => 'Ý', + 'à' => 'à', + 'á' => 'á', + 'â' => 'â', + 'ã' => 'ã', + 'ä' => 'ä', + 'å' => 'å', + 'ç' => 'ç', + 'è' => 'è', + 'é' => 'é', + 'ê' => 'ê', + 'ë' => 'ë', + 'ì' => 'ì', + 'í' => 'í', + 'î' => 'î', + 'ï' => 'ï', + 'ñ' => 'ñ', + 'ò' => 'ò', + 'ó' => 'ó', + 'ô' => 'ô', + 'õ' => 'õ', + 'ö' => 'ö', + 'ù' => 'ù', + 'ú' => 'ú', + 'û' => 'û', + 'ü' => 'ü', + 'ý' => 'ý', + 'ÿ' => 'ÿ', + 'Ā' => 'Ā', + 'ā' => 'ā', + 'Ă' => 'Ă', + 'ă' => 'ă', + 'Ą' => 'Ą', + 'ą' => 'ą', + 'Ć' => 'Ć', + 'ć' => 'ć', + 'Ĉ' => 'Ĉ', + 'ĉ' => 'ĉ', + 'Ċ' => 'Ċ', + 'ċ' => 'ċ', + 'Č' => 'Č', + 'č' => 'č', + 'Ď' => 'Ď', + 'ď' => 'ď', + 'Ē' => 'Ē', + 'ē' => 'ē', + 'Ĕ' => 'Ĕ', + 'ĕ' => 'ĕ', + 'Ė' => 'Ė', + 'ė' => 'ė', + 'Ę' => 'Ę', + 'ę' => 'ę', + 'Ě' => 'Ě', + 'ě' => 'ě', + 'Ĝ' => 'Ĝ', + 'ĝ' => 'ĝ', + 'Ğ' => 'Ğ', + 'ğ' => 'ğ', + 'Ġ' => 'Ġ', + 'ġ' => 'ġ', + 'Ģ' => 'Ģ', + 'ģ' => 'ģ', + 'Ĥ' => 'Ĥ', + 'ĥ' => 'ĥ', + 'Ĩ' => 'Ĩ', + 'ĩ' => 'ĩ', + 'Ī' => 'Ī', + 'ī' => 'ī', + 'Ĭ' => 'Ĭ', + 'ĭ' => 'ĭ', + 'Į' => 'Į', + 'į' => 'į', + 'İ' => 'İ', + 'Ĵ' => 'Ĵ', + 'ĵ' => 'ĵ', + 'Ķ' => 'Ķ', + 'ķ' => 'ķ', + 'Ĺ' => 'Ĺ', + 'ĺ' => 'ĺ', + 'Ļ' => 'Ļ', + 'ļ' => 'ļ', + 'Ľ' => 'Ľ', + 'ľ' => 'ľ', + 'Ń' => 'Ń', + 'ń' => 'ń', + 'Ņ' => 'Ņ', + 'ņ' => 'ņ', + 'Ň' => 'Ň', + 'ň' => 'ň', + 'Ō' => 'Ō', + 'ō' => 'ō', + 'Ŏ' => 'Ŏ', + 'ŏ' => 'ŏ', + 'Ő' => 'Ő', + 'ő' => 'ő', + 'Ŕ' => 'Ŕ', + 'ŕ' => 'ŕ', + 'Ŗ' => 'Ŗ', + 'ŗ' => 'ŗ', + 'Ř' => 'Ř', + 'ř' => 'ř', + 'Ś' => 'Ś', + 'ś' => 'ś', + 'Ŝ' => 'Ŝ', + 'ŝ' => 'ŝ', + 'Ş' => 'Ş', + 'ş' => 'ş', + 'Š' => 'Š', + 'š' => 'š', + 'Ţ' => 'Ţ', + 'ţ' => 'ţ', + 'Ť' => 'Ť', + 'ť' => 'ť', + 'Ũ' => 'Ũ', + 'ũ' => 'ũ', + 'Ū' => 'Ū', + 'ū' => 'ū', + 'Ŭ' => 'Ŭ', + 'ŭ' => 'ŭ', + 'Ů' => 'Ů', + 'ů' => 'ů', + 'Ű' => 'Ű', + 'ű' => 'ű', + 'Ų' => 'Ų', + 'ų' => 'ų', + 'Ŵ' => 'Ŵ', + 'ŵ' => 'ŵ', + 'Ŷ' => 'Ŷ', + 'ŷ' => 'ŷ', + 'Ÿ' => 'Ÿ', + 'Ź' => 'Ź', + 'ź' => 'ź', + 'Ż' => 'Ż', + 'ż' => 'ż', + 'Ž' => 'Ž', + 'ž' => 'ž', + 'Ơ' => 'Ơ', + 'ơ' => 'ơ', + 'Ư' => 'Ư', + 'ư' => 'ư', + 'Ǎ' => 'Ǎ', + 'ǎ' => 'ǎ', + 'Ǐ' => 'Ǐ', + 'ǐ' => 'ǐ', + 'Ǒ' => 'Ǒ', + 'ǒ' => 'ǒ', + 'Ǔ' => 'Ǔ', + 'ǔ' => 'ǔ', + 'Ǖ' => 'Ǖ', + 'ǖ' => 'ǖ', + 'Ǘ' => 'Ǘ', + 'ǘ' => 'ǘ', + 'Ǚ' => 'Ǚ', + 'ǚ' => 'ǚ', + 'Ǜ' => 'Ǜ', + 'ǜ' => 'ǜ', + 'Ǟ' => 'Ǟ', + 'ǟ' => 'ǟ', + 'Ǡ' => 'Ǡ', + 'ǡ' => 'ǡ', + 'Ǣ' => 'Ǣ', + 'ǣ' => 'ǣ', + 'Ǧ' => 'Ǧ', + 'ǧ' => 'ǧ', + 'Ǩ' => 'Ǩ', + 'ǩ' => 'ǩ', + 'Ǫ' => 'Ǫ', + 'ǫ' => 'ǫ', + 'Ǭ' => 'Ǭ', + 'ǭ' => 'ǭ', + 'Ǯ' => 'Ǯ', + 'ǯ' => 'ǯ', + 'ǰ' => 'ǰ', + 'Ǵ' => 'Ǵ', + 'ǵ' => 'ǵ', + 'Ǹ' => 'Ǹ', + 'ǹ' => 'ǹ', + 'Ǻ' => 'Ǻ', + 'ǻ' => 'ǻ', + 'Ǽ' => 'Ǽ', + 'ǽ' => 'ǽ', + 'Ǿ' => 'Ǿ', + 'ǿ' => 'ǿ', + 'Ȁ' => 'Ȁ', + 'ȁ' => 'ȁ', + 'Ȃ' => 'Ȃ', + 'ȃ' => 'ȃ', + 'Ȅ' => 'Ȅ', + 'ȅ' => 'ȅ', + 'Ȇ' => 'Ȇ', + 'ȇ' => 'ȇ', + 'Ȉ' => 'Ȉ', + 'ȉ' => 'ȉ', + 'Ȋ' => 'Ȋ', + 'ȋ' => 'ȋ', + 'Ȍ' => 'Ȍ', + 'ȍ' => 'ȍ', + 'Ȏ' => 'Ȏ', + 'ȏ' => 'ȏ', + 'Ȑ' => 'Ȑ', + 'ȑ' => 'ȑ', + 'Ȓ' => 'Ȓ', + 'ȓ' => 'ȓ', + 'Ȕ' => 'Ȕ', + 'ȕ' => 'ȕ', + 'Ȗ' => 'Ȗ', + 'ȗ' => 'ȗ', + 'Ș' => 'Ș', + 'ș' => 'ș', + 'Ț' => 'Ț', + 'ț' => 'ț', + 'Ȟ' => 'Ȟ', + 'ȟ' => 'ȟ', + 'Ȧ' => 'Ȧ', + 'ȧ' => 'ȧ', + 'Ȩ' => 'Ȩ', + 'ȩ' => 'ȩ', + 'Ȫ' => 'Ȫ', + 'ȫ' => 'ȫ', + 'Ȭ' => 'Ȭ', + 'ȭ' => 'ȭ', + 'Ȯ' => 'Ȯ', + 'ȯ' => 'ȯ', + 'Ȱ' => 'Ȱ', + 'ȱ' => 'ȱ', + 'Ȳ' => 'Ȳ', + 'ȳ' => 'ȳ', + '΅' => '΅', + 'Ά' => 'Ά', + 'Έ' => 'Έ', + 'Ή' => 'Ή', + 'Ί' => 'Ί', + 'Ό' => 'Ό', + 'Ύ' => 'Ύ', + 'Ώ' => 'Ώ', + 'ΐ' => 'ΐ', + 'Ϊ' => 'Ϊ', + 'Ϋ' => 'Ϋ', + 'ά' => 'ά', + 'έ' => 'έ', + 'ή' => 'ή', + 'ί' => 'ί', + 'ΰ' => 'ΰ', + 'ϊ' => 'ϊ', + 'ϋ' => 'ϋ', + 'ό' => 'ό', + 'ύ' => 'ύ', + 'ώ' => 'ώ', + 'ϓ' => 'ϓ', + 'ϔ' => 'ϔ', + 'Ѐ' => 'Ѐ', + 'Ё' => 'Ё', + 'Ѓ' => 'Ѓ', + 'Ї' => 'Ї', + 'Ќ' => 'Ќ', + 'Ѝ' => 'Ѝ', + 'Ў' => 'Ў', + 'Й' => 'Й', + 'й' => 'й', + 'ѐ' => 'ѐ', + 'ё' => 'ё', + 'ѓ' => 'ѓ', + 'ї' => 'ї', + 'ќ' => 'ќ', + 'ѝ' => 'ѝ', + 'ў' => 'ў', + 'Ѷ' => 'Ѷ', + 'ѷ' => 'ѷ', + 'Ӂ' => 'Ӂ', + 'ӂ' => 'ӂ', + 'Ӑ' => 'Ӑ', + 'ӑ' => 'ӑ', + 'Ӓ' => 'Ӓ', + 'ӓ' => 'ӓ', + 'Ӗ' => 'Ӗ', + 'ӗ' => 'ӗ', + 'Ӛ' => 'Ӛ', + 'ӛ' => 'ӛ', + 'Ӝ' => 'Ӝ', + 'ӝ' => 'ӝ', + 'Ӟ' => 'Ӟ', + 'ӟ' => 'ӟ', + 'Ӣ' => 'Ӣ', + 'ӣ' => 'ӣ', + 'Ӥ' => 'Ӥ', + 'ӥ' => 'ӥ', + 'Ӧ' => 'Ӧ', + 'ӧ' => 'ӧ', + 'Ӫ' => 'Ӫ', + 'ӫ' => 'ӫ', + 'Ӭ' => 'Ӭ', + 'ӭ' => 'ӭ', + 'Ӯ' => 'Ӯ', + 'ӯ' => 'ӯ', + 'Ӱ' => 'Ӱ', + 'ӱ' => 'ӱ', + 'Ӳ' => 'Ӳ', + 'ӳ' => 'ӳ', + 'Ӵ' => 'Ӵ', + 'ӵ' => 'ӵ', + 'Ӹ' => 'Ӹ', + 'ӹ' => 'ӹ', + 'آ' => 'آ', + 'أ' => 'أ', + 'ؤ' => 'ؤ', + 'إ' => 'إ', + 'ئ' => 'ئ', + 'ۀ' => 'ۀ', + 'ۂ' => 'ۂ', + 'ۓ' => 'ۓ', + 'ऩ' => 'ऩ', + 'ऱ' => 'ऱ', + 'ऴ' => 'ऴ', + 'ো' => 'ো', + 'ৌ' => 'ৌ', + 'ୈ' => 'ୈ', + 'ୋ' => 'ୋ', + 'ୌ' => 'ୌ', + 'ஔ' => 'ஔ', + 'ொ' => 'ொ', + 'ோ' => 'ோ', + 'ௌ' => 'ௌ', + 'ై' => 'ై', + 'ೀ' => 'ೀ', + 'ೇ' => 'ೇ', + 'ೈ' => 'ೈ', + 'ೊ' => 'ೊ', + 'ೋ' => 'ೋ', + 'ൊ' => 'ൊ', + 'ോ' => 'ോ', + 'ൌ' => 'ൌ', + 'ේ' => 'ේ', + 'ො' => 'ො', + 'ෝ' => 'ෝ', + 'ෞ' => 'ෞ', + 'ဦ' => 'ဦ', + 'ᬆ' => 'ᬆ', + 'ᬈ' => 'ᬈ', + 'ᬊ' => 'ᬊ', + 'ᬌ' => 'ᬌ', + 'ᬎ' => 'ᬎ', + 'ᬒ' => 'ᬒ', + 'ᬻ' => 'ᬻ', + 'ᬽ' => 'ᬽ', + 'ᭀ' => 'ᭀ', + 'ᭁ' => 'ᭁ', + 'ᭃ' => 'ᭃ', + 'Ḁ' => 'Ḁ', + 'ḁ' => 'ḁ', + 'Ḃ' => 'Ḃ', + 'ḃ' => 'ḃ', + 'Ḅ' => 'Ḅ', + 'ḅ' => 'ḅ', + 'Ḇ' => 'Ḇ', + 'ḇ' => 'ḇ', + 'Ḉ' => 'Ḉ', + 'ḉ' => 'ḉ', + 'Ḋ' => 'Ḋ', + 'ḋ' => 'ḋ', + 'Ḍ' => 'Ḍ', + 'ḍ' => 'ḍ', + 'Ḏ' => 'Ḏ', + 'ḏ' => 'ḏ', + 'Ḑ' => 'Ḑ', + 'ḑ' => 'ḑ', + 'Ḓ' => 'Ḓ', + 'ḓ' => 'ḓ', + 'Ḕ' => 'Ḕ', + 'ḕ' => 'ḕ', + 'Ḗ' => 'Ḗ', + 'ḗ' => 'ḗ', + 'Ḙ' => 'Ḙ', + 'ḙ' => 'ḙ', + 'Ḛ' => 'Ḛ', + 'ḛ' => 'ḛ', + 'Ḝ' => 'Ḝ', + 'ḝ' => 'ḝ', + 'Ḟ' => 'Ḟ', + 'ḟ' => 'ḟ', + 'Ḡ' => 'Ḡ', + 'ḡ' => 'ḡ', + 'Ḣ' => 'Ḣ', + 'ḣ' => 'ḣ', + 'Ḥ' => 'Ḥ', + 'ḥ' => 'ḥ', + 'Ḧ' => 'Ḧ', + 'ḧ' => 'ḧ', + 'Ḩ' => 'Ḩ', + 'ḩ' => 'ḩ', + 'Ḫ' => 'Ḫ', + 'ḫ' => 'ḫ', + 'Ḭ' => 'Ḭ', + 'ḭ' => 'ḭ', + 'Ḯ' => 'Ḯ', + 'ḯ' => 'ḯ', + 'Ḱ' => 'Ḱ', + 'ḱ' => 'ḱ', + 'Ḳ' => 'Ḳ', + 'ḳ' => 'ḳ', + 'Ḵ' => 'Ḵ', + 'ḵ' => 'ḵ', + 'Ḷ' => 'Ḷ', + 'ḷ' => 'ḷ', + 'Ḹ' => 'Ḹ', + 'ḹ' => 'ḹ', + 'Ḻ' => 'Ḻ', + 'ḻ' => 'ḻ', + 'Ḽ' => 'Ḽ', + 'ḽ' => 'ḽ', + 'Ḿ' => 'Ḿ', + 'ḿ' => 'ḿ', + 'Ṁ' => 'Ṁ', + 'ṁ' => 'ṁ', + 'Ṃ' => 'Ṃ', + 'ṃ' => 'ṃ', + 'Ṅ' => 'Ṅ', + 'ṅ' => 'ṅ', + 'Ṇ' => 'Ṇ', + 'ṇ' => 'ṇ', + 'Ṉ' => 'Ṉ', + 'ṉ' => 'ṉ', + 'Ṋ' => 'Ṋ', + 'ṋ' => 'ṋ', + 'Ṍ' => 'Ṍ', + 'ṍ' => 'ṍ', + 'Ṏ' => 'Ṏ', + 'ṏ' => 'ṏ', + 'Ṑ' => 'Ṑ', + 'ṑ' => 'ṑ', + 'Ṓ' => 'Ṓ', + 'ṓ' => 'ṓ', + 'Ṕ' => 'Ṕ', + 'ṕ' => 'ṕ', + 'Ṗ' => 'Ṗ', + 'ṗ' => 'ṗ', + 'Ṙ' => 'Ṙ', + 'ṙ' => 'ṙ', + 'Ṛ' => 'Ṛ', + 'ṛ' => 'ṛ', + 'Ṝ' => 'Ṝ', + 'ṝ' => 'ṝ', + 'Ṟ' => 'Ṟ', + 'ṟ' => 'ṟ', + 'Ṡ' => 'Ṡ', + 'ṡ' => 'ṡ', + 'Ṣ' => 'Ṣ', + 'ṣ' => 'ṣ', + 'Ṥ' => 'Ṥ', + 'ṥ' => 'ṥ', + 'Ṧ' => 'Ṧ', + 'ṧ' => 'ṧ', + 'Ṩ' => 'Ṩ', + 'ṩ' => 'ṩ', + 'Ṫ' => 'Ṫ', + 'ṫ' => 'ṫ', + 'Ṭ' => 'Ṭ', + 'ṭ' => 'ṭ', + 'Ṯ' => 'Ṯ', + 'ṯ' => 'ṯ', + 'Ṱ' => 'Ṱ', + 'ṱ' => 'ṱ', + 'Ṳ' => 'Ṳ', + 'ṳ' => 'ṳ', + 'Ṵ' => 'Ṵ', + 'ṵ' => 'ṵ', + 'Ṷ' => 'Ṷ', + 'ṷ' => 'ṷ', + 'Ṹ' => 'Ṹ', + 'ṹ' => 'ṹ', + 'Ṻ' => 'Ṻ', + 'ṻ' => 'ṻ', + 'Ṽ' => 'Ṽ', + 'ṽ' => 'ṽ', + 'Ṿ' => 'Ṿ', + 'ṿ' => 'ṿ', + 'Ẁ' => 'Ẁ', + 'ẁ' => 'ẁ', + 'Ẃ' => 'Ẃ', + 'ẃ' => 'ẃ', + 'Ẅ' => 'Ẅ', + 'ẅ' => 'ẅ', + 'Ẇ' => 'Ẇ', + 'ẇ' => 'ẇ', + 'Ẉ' => 'Ẉ', + 'ẉ' => 'ẉ', + 'Ẋ' => 'Ẋ', + 'ẋ' => 'ẋ', + 'Ẍ' => 'Ẍ', + 'ẍ' => 'ẍ', + 'Ẏ' => 'Ẏ', + 'ẏ' => 'ẏ', + 'Ẑ' => 'Ẑ', + 'ẑ' => 'ẑ', + 'Ẓ' => 'Ẓ', + 'ẓ' => 'ẓ', + 'Ẕ' => 'Ẕ', + 'ẕ' => 'ẕ', + 'ẖ' => 'ẖ', + 'ẗ' => 'ẗ', + 'ẘ' => 'ẘ', + 'ẙ' => 'ẙ', + 'ẛ' => 'ẛ', + 'Ạ' => 'Ạ', + 'ạ' => 'ạ', + 'Ả' => 'Ả', + 'ả' => 'ả', + 'Ấ' => 'Ấ', + 'ấ' => 'ấ', + 'Ầ' => 'Ầ', + 'ầ' => 'ầ', + 'Ẩ' => 'Ẩ', + 'ẩ' => 'ẩ', + 'Ẫ' => 'Ẫ', + 'ẫ' => 'ẫ', + 'Ậ' => 'Ậ', + 'ậ' => 'ậ', + 'Ắ' => 'Ắ', + 'ắ' => 'ắ', + 'Ằ' => 'Ằ', + 'ằ' => 'ằ', + 'Ẳ' => 'Ẳ', + 'ẳ' => 'ẳ', + 'Ẵ' => 'Ẵ', + 'ẵ' => 'ẵ', + 'Ặ' => 'Ặ', + 'ặ' => 'ặ', + 'Ẹ' => 'Ẹ', + 'ẹ' => 'ẹ', + 'Ẻ' => 'Ẻ', + 'ẻ' => 'ẻ', + 'Ẽ' => 'Ẽ', + 'ẽ' => 'ẽ', + 'Ế' => 'Ế', + 'ế' => 'ế', + 'Ề' => 'Ề', + 'ề' => 'ề', + 'Ể' => 'Ể', + 'ể' => 'ể', + 'Ễ' => 'Ễ', + 'ễ' => 'ễ', + 'Ệ' => 'Ệ', + 'ệ' => 'ệ', + 'Ỉ' => 'Ỉ', + 'ỉ' => 'ỉ', + 'Ị' => 'Ị', + 'ị' => 'ị', + 'Ọ' => 'Ọ', + 'ọ' => 'ọ', + 'Ỏ' => 'Ỏ', + 'ỏ' => 'ỏ', + 'Ố' => 'Ố', + 'ố' => 'ố', + 'Ồ' => 'Ồ', + 'ồ' => 'ồ', + 'Ổ' => 'Ổ', + 'ổ' => 'ổ', + 'Ỗ' => 'Ỗ', + 'ỗ' => 'ỗ', + 'Ộ' => 'Ộ', + 'ộ' => 'ộ', + 'Ớ' => 'Ớ', + 'ớ' => 'ớ', + 'Ờ' => 'Ờ', + 'ờ' => 'ờ', + 'Ở' => 'Ở', + 'ở' => 'ở', + 'Ỡ' => 'Ỡ', + 'ỡ' => 'ỡ', + 'Ợ' => 'Ợ', + 'ợ' => 'ợ', + 'Ụ' => 'Ụ', + 'ụ' => 'ụ', + 'Ủ' => 'Ủ', + 'ủ' => 'ủ', + 'Ứ' => 'Ứ', + 'ứ' => 'ứ', + 'Ừ' => 'Ừ', + 'ừ' => 'ừ', + 'Ử' => 'Ử', + 'ử' => 'ử', + 'Ữ' => 'Ữ', + 'ữ' => 'ữ', + 'Ự' => 'Ự', + 'ự' => 'ự', + 'Ỳ' => 'Ỳ', + 'ỳ' => 'ỳ', + 'Ỵ' => 'Ỵ', + 'ỵ' => 'ỵ', + 'Ỷ' => 'Ỷ', + 'ỷ' => 'ỷ', + 'Ỹ' => 'Ỹ', + 'ỹ' => 'ỹ', + 'ἀ' => 'ἀ', + 'ἁ' => 'ἁ', + 'ἂ' => 'ἂ', + 'ἃ' => 'ἃ', + 'ἄ' => 'ἄ', + 'ἅ' => 'ἅ', + 'ἆ' => 'ἆ', + 'ἇ' => 'ἇ', + 'Ἀ' => 'Ἀ', + 'Ἁ' => 'Ἁ', + 'Ἂ' => 'Ἂ', + 'Ἃ' => 'Ἃ', + 'Ἄ' => 'Ἄ', + 'Ἅ' => 'Ἅ', + 'Ἆ' => 'Ἆ', + 'Ἇ' => 'Ἇ', + 'ἐ' => 'ἐ', + 'ἑ' => 'ἑ', + 'ἒ' => 'ἒ', + 'ἓ' => 'ἓ', + 'ἔ' => 'ἔ', + 'ἕ' => 'ἕ', + 'Ἐ' => 'Ἐ', + 'Ἑ' => 'Ἑ', + 'Ἒ' => 'Ἒ', + 'Ἓ' => 'Ἓ', + 'Ἔ' => 'Ἔ', + 'Ἕ' => 'Ἕ', + 'ἠ' => 'ἠ', + 'ἡ' => 'ἡ', + 'ἢ' => 'ἢ', + 'ἣ' => 'ἣ', + 'ἤ' => 'ἤ', + 'ἥ' => 'ἥ', + 'ἦ' => 'ἦ', + 'ἧ' => 'ἧ', + 'Ἠ' => 'Ἠ', + 'Ἡ' => 'Ἡ', + 'Ἢ' => 'Ἢ', + 'Ἣ' => 'Ἣ', + 'Ἤ' => 'Ἤ', + 'Ἥ' => 'Ἥ', + 'Ἦ' => 'Ἦ', + 'Ἧ' => 'Ἧ', + 'ἰ' => 'ἰ', + 'ἱ' => 'ἱ', + 'ἲ' => 'ἲ', + 'ἳ' => 'ἳ', + 'ἴ' => 'ἴ', + 'ἵ' => 'ἵ', + 'ἶ' => 'ἶ', + 'ἷ' => 'ἷ', + 'Ἰ' => 'Ἰ', + 'Ἱ' => 'Ἱ', + 'Ἲ' => 'Ἲ', + 'Ἳ' => 'Ἳ', + 'Ἴ' => 'Ἴ', + 'Ἵ' => 'Ἵ', + 'Ἶ' => 'Ἶ', + 'Ἷ' => 'Ἷ', + 'ὀ' => 'ὀ', + 'ὁ' => 'ὁ', + 'ὂ' => 'ὂ', + 'ὃ' => 'ὃ', + 'ὄ' => 'ὄ', + 'ὅ' => 'ὅ', + 'Ὀ' => 'Ὀ', + 'Ὁ' => 'Ὁ', + 'Ὂ' => 'Ὂ', + 'Ὃ' => 'Ὃ', + 'Ὄ' => 'Ὄ', + 'Ὅ' => 'Ὅ', + 'ὐ' => 'ὐ', + 'ὑ' => 'ὑ', + 'ὒ' => 'ὒ', + 'ὓ' => 'ὓ', + 'ὔ' => 'ὔ', + 'ὕ' => 'ὕ', + 'ὖ' => 'ὖ', + 'ὗ' => 'ὗ', + 'Ὑ' => 'Ὑ', + 'Ὓ' => 'Ὓ', + 'Ὕ' => 'Ὕ', + 'Ὗ' => 'Ὗ', + 'ὠ' => 'ὠ', + 'ὡ' => 'ὡ', + 'ὢ' => 'ὢ', + 'ὣ' => 'ὣ', + 'ὤ' => 'ὤ', + 'ὥ' => 'ὥ', + 'ὦ' => 'ὦ', + 'ὧ' => 'ὧ', + 'Ὠ' => 'Ὠ', + 'Ὡ' => 'Ὡ', + 'Ὢ' => 'Ὢ', + 'Ὣ' => 'Ὣ', + 'Ὤ' => 'Ὤ', + 'Ὥ' => 'Ὥ', + 'Ὦ' => 'Ὦ', + 'Ὧ' => 'Ὧ', + 'ὰ' => 'ὰ', + 'ὲ' => 'ὲ', + 'ὴ' => 'ὴ', + 'ὶ' => 'ὶ', + 'ὸ' => 'ὸ', + 'ὺ' => 'ὺ', + 'ὼ' => 'ὼ', + 'ᾀ' => 'ᾀ', + 'ᾁ' => 'ᾁ', + 'ᾂ' => 'ᾂ', + 'ᾃ' => 'ᾃ', + 'ᾄ' => 'ᾄ', + 'ᾅ' => 'ᾅ', + 'ᾆ' => 'ᾆ', + 'ᾇ' => 'ᾇ', + 'ᾈ' => 'ᾈ', + 'ᾉ' => 'ᾉ', + 'ᾊ' => 'ᾊ', + 'ᾋ' => 'ᾋ', + 'ᾌ' => 'ᾌ', + 'ᾍ' => 'ᾍ', + 'ᾎ' => 'ᾎ', + 'ᾏ' => 'ᾏ', + 'ᾐ' => 'ᾐ', + 'ᾑ' => 'ᾑ', + 'ᾒ' => 'ᾒ', + 'ᾓ' => 'ᾓ', + 'ᾔ' => 'ᾔ', + 'ᾕ' => 'ᾕ', + 'ᾖ' => 'ᾖ', + 'ᾗ' => 'ᾗ', + 'ᾘ' => 'ᾘ', + 'ᾙ' => 'ᾙ', + 'ᾚ' => 'ᾚ', + 'ᾛ' => 'ᾛ', + 'ᾜ' => 'ᾜ', + 'ᾝ' => 'ᾝ', + 'ᾞ' => 'ᾞ', + 'ᾟ' => 'ᾟ', + 'ᾠ' => 'ᾠ', + 'ᾡ' => 'ᾡ', + 'ᾢ' => 'ᾢ', + 'ᾣ' => 'ᾣ', + 'ᾤ' => 'ᾤ', + 'ᾥ' => 'ᾥ', + 'ᾦ' => 'ᾦ', + 'ᾧ' => 'ᾧ', + 'ᾨ' => 'ᾨ', + 'ᾩ' => 'ᾩ', + 'ᾪ' => 'ᾪ', + 'ᾫ' => 'ᾫ', + 'ᾬ' => 'ᾬ', + 'ᾭ' => 'ᾭ', + 'ᾮ' => 'ᾮ', + 'ᾯ' => 'ᾯ', + 'ᾰ' => 'ᾰ', + 'ᾱ' => 'ᾱ', + 'ᾲ' => 'ᾲ', + 'ᾳ' => 'ᾳ', + 'ᾴ' => 'ᾴ', + 'ᾶ' => 'ᾶ', + 'ᾷ' => 'ᾷ', + 'Ᾰ' => 'Ᾰ', + 'Ᾱ' => 'Ᾱ', + 'Ὰ' => 'Ὰ', + 'ᾼ' => 'ᾼ', + '῁' => '῁', + 'ῂ' => 'ῂ', + 'ῃ' => 'ῃ', + 'ῄ' => 'ῄ', + 'ῆ' => 'ῆ', + 'ῇ' => 'ῇ', + 'Ὲ' => 'Ὲ', + 'Ὴ' => 'Ὴ', + 'ῌ' => 'ῌ', + '῍' => '῍', + '῎' => '῎', + '῏' => '῏', + 'ῐ' => 'ῐ', + 'ῑ' => 'ῑ', + 'ῒ' => 'ῒ', + 'ῖ' => 'ῖ', + 'ῗ' => 'ῗ', + 'Ῐ' => 'Ῐ', + 'Ῑ' => 'Ῑ', + 'Ὶ' => 'Ὶ', + '῝' => '῝', + '῞' => '῞', + '῟' => '῟', + 'ῠ' => 'ῠ', + 'ῡ' => 'ῡ', + 'ῢ' => 'ῢ', + 'ῤ' => 'ῤ', + 'ῥ' => 'ῥ', + 'ῦ' => 'ῦ', + 'ῧ' => 'ῧ', + 'Ῠ' => 'Ῠ', + 'Ῡ' => 'Ῡ', + 'Ὺ' => 'Ὺ', + 'Ῥ' => 'Ῥ', + '῭' => '῭', + 'ῲ' => 'ῲ', + 'ῳ' => 'ῳ', + 'ῴ' => 'ῴ', + 'ῶ' => 'ῶ', + 'ῷ' => 'ῷ', + 'Ὸ' => 'Ὸ', + 'Ὼ' => 'Ὼ', + 'ῼ' => 'ῼ', + '↚' => '↚', + '↛' => '↛', + '↮' => '↮', + '⇍' => '⇍', + '⇎' => '⇎', + '⇏' => '⇏', + '∄' => '∄', + '∉' => '∉', + '∌' => '∌', + '∤' => '∤', + '∦' => '∦', + '≁' => '≁', + '≄' => '≄', + '≇' => '≇', + '≉' => '≉', + '≠' => '≠', + '≢' => '≢', + '≭' => '≭', + '≮' => '≮', + '≯' => '≯', + '≰' => '≰', + '≱' => '≱', + '≴' => '≴', + '≵' => '≵', + '≸' => '≸', + '≹' => '≹', + '⊀' => '⊀', + '⊁' => '⊁', + '⊄' => '⊄', + '⊅' => '⊅', + '⊈' => '⊈', + '⊉' => '⊉', + '⊬' => '⊬', + '⊭' => '⊭', + '⊮' => '⊮', + '⊯' => '⊯', + '⋠' => '⋠', + '⋡' => '⋡', + '⋢' => '⋢', + '⋣' => '⋣', + '⋪' => '⋪', + '⋫' => '⋫', + '⋬' => '⋬', + '⋭' => '⋭', + 'が' => 'が', + 'ぎ' => 'ぎ', + 'ぐ' => 'ぐ', + 'げ' => 'げ', + 'ご' => 'ご', + 'ざ' => 'ざ', + 'じ' => 'じ', + 'ず' => 'ず', + 'ぜ' => 'ぜ', + 'ぞ' => 'ぞ', + 'だ' => 'だ', + 'ぢ' => 'ぢ', + 'づ' => 'づ', + 'で' => 'で', + 'ど' => 'ど', + 'ば' => 'ば', + 'ぱ' => 'ぱ', + 'び' => 'び', + 'ぴ' => 'ぴ', + 'ぶ' => 'ぶ', + 'ぷ' => 'ぷ', + 'べ' => 'べ', + 'ぺ' => 'ぺ', + 'ぼ' => 'ぼ', + 'ぽ' => 'ぽ', + 'ゔ' => 'ゔ', + 'ゞ' => 'ゞ', + 'ガ' => 'ガ', + 'ギ' => 'ギ', + 'グ' => 'グ', + 'ゲ' => 'ゲ', + 'ゴ' => 'ゴ', + 'ザ' => 'ザ', + 'ジ' => 'ジ', + 'ズ' => 'ズ', + 'ゼ' => 'ゼ', + 'ゾ' => 'ゾ', + 'ダ' => 'ダ', + 'ヂ' => 'ヂ', + 'ヅ' => 'ヅ', + 'デ' => 'デ', + 'ド' => 'ド', + 'バ' => 'バ', + 'パ' => 'パ', + 'ビ' => 'ビ', + 'ピ' => 'ピ', + 'ブ' => 'ブ', + 'プ' => 'プ', + 'ベ' => 'ベ', + 'ペ' => 'ペ', + 'ボ' => 'ボ', + 'ポ' => 'ポ', + 'ヴ' => 'ヴ', + 'ヷ' => 'ヷ', + 'ヸ' => 'ヸ', + 'ヹ' => 'ヹ', + 'ヺ' => 'ヺ', + 'ヾ' => 'ヾ', + '𑂚' => '𑂚', + '𑂜' => '𑂜', + '𑂫' => '𑂫', + '𑄮' => '𑄮', + '𑄯' => '𑄯', + '𑍋' => '𑍋', + '𑍌' => '𑍌', + '𑒻' => '𑒻', + '𑒼' => '𑒼', + '𑒾' => '𑒾', + '𑖺' => '𑖺', + '𑖻' => '𑖻', + '𑤸' => '𑤸', +); diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/canonicalDecomposition.php b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/canonicalDecomposition.php new file mode 100644 index 00000000..5a3e8e09 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/canonicalDecomposition.php @@ -0,0 +1,2065 @@ + 'À', + 'Á' => 'Á', + 'Â' => 'Â', + 'Ã' => 'Ã', + 'Ä' => 'Ä', + 'Å' => 'Å', + 'Ç' => 'Ç', + 'È' => 'È', + 'É' => 'É', + 'Ê' => 'Ê', + 'Ë' => 'Ë', + 'Ì' => 'Ì', + 'Í' => 'Í', + 'Î' => 'Î', + 'Ï' => 'Ï', + 'Ñ' => 'Ñ', + 'Ò' => 'Ò', + 'Ó' => 'Ó', + 'Ô' => 'Ô', + 'Õ' => 'Õ', + 'Ö' => 'Ö', + 'Ù' => 'Ù', + 'Ú' => 'Ú', + 'Û' => 'Û', + 'Ü' => 'Ü', + 'Ý' => 'Ý', + 'à' => 'à', + 'á' => 'á', + 'â' => 'â', + 'ã' => 'ã', + 'ä' => 'ä', + 'å' => 'å', + 'ç' => 'ç', + 'è' => 'è', + 'é' => 'é', + 'ê' => 'ê', + 'ë' => 'ë', + 'ì' => 'ì', + 'í' => 'í', + 'î' => 'î', + 'ï' => 'ï', + 'ñ' => 'ñ', + 'ò' => 'ò', + 'ó' => 'ó', + 'ô' => 'ô', + 'õ' => 'õ', + 'ö' => 'ö', + 'ù' => 'ù', + 'ú' => 'ú', + 'û' => 'û', + 'ü' => 'ü', + 'ý' => 'ý', + 'ÿ' => 'ÿ', + 'Ā' => 'Ā', + 'ā' => 'ā', + 'Ă' => 'Ă', + 'ă' => 'ă', + 'Ą' => 'Ą', + 'ą' => 'ą', + 'Ć' => 'Ć', + 'ć' => 'ć', + 'Ĉ' => 'Ĉ', + 'ĉ' => 'ĉ', + 'Ċ' => 'Ċ', + 'ċ' => 'ċ', + 'Č' => 'Č', + 'č' => 'č', + 'Ď' => 'Ď', + 'ď' => 'ď', + 'Ē' => 'Ē', + 'ē' => 'ē', + 'Ĕ' => 'Ĕ', + 'ĕ' => 'ĕ', + 'Ė' => 'Ė', + 'ė' => 'ė', + 'Ę' => 'Ę', + 'ę' => 'ę', + 'Ě' => 'Ě', + 'ě' => 'ě', + 'Ĝ' => 'Ĝ', + 'ĝ' => 'ĝ', + 'Ğ' => 'Ğ', + 'ğ' => 'ğ', + 'Ġ' => 'Ġ', + 'ġ' => 'ġ', + 'Ģ' => 'Ģ', + 'ģ' => 'ģ', + 'Ĥ' => 'Ĥ', + 'ĥ' => 'ĥ', + 'Ĩ' => 'Ĩ', + 'ĩ' => 'ĩ', + 'Ī' => 'Ī', + 'ī' => 'ī', + 'Ĭ' => 'Ĭ', + 'ĭ' => 'ĭ', + 'Į' => 'Į', + 'į' => 'į', + 'İ' => 'İ', + 'Ĵ' => 'Ĵ', + 'ĵ' => 'ĵ', + 'Ķ' => 'Ķ', + 'ķ' => 'ķ', + 'Ĺ' => 'Ĺ', + 'ĺ' => 'ĺ', + 'Ļ' => 'Ļ', + 'ļ' => 'ļ', + 'Ľ' => 'Ľ', + 'ľ' => 'ľ', + 'Ń' => 'Ń', + 'ń' => 'ń', + 'Ņ' => 'Ņ', + 'ņ' => 'ņ', + 'Ň' => 'Ň', + 'ň' => 'ň', + 'Ō' => 'Ō', + 'ō' => 'ō', + 'Ŏ' => 'Ŏ', + 'ŏ' => 'ŏ', + 'Ő' => 'Ő', + 'ő' => 'ő', + 'Ŕ' => 'Ŕ', + 'ŕ' => 'ŕ', + 'Ŗ' => 'Ŗ', + 'ŗ' => 'ŗ', + 'Ř' => 'Ř', + 'ř' => 'ř', + 'Ś' => 'Ś', + 'ś' => 'ś', + 'Ŝ' => 'Ŝ', + 'ŝ' => 'ŝ', + 'Ş' => 'Ş', + 'ş' => 'ş', + 'Š' => 'Š', + 'š' => 'š', + 'Ţ' => 'Ţ', + 'ţ' => 'ţ', + 'Ť' => 'Ť', + 'ť' => 'ť', + 'Ũ' => 'Ũ', + 'ũ' => 'ũ', + 'Ū' => 'Ū', + 'ū' => 'ū', + 'Ŭ' => 'Ŭ', + 'ŭ' => 'ŭ', + 'Ů' => 'Ů', + 'ů' => 'ů', + 'Ű' => 'Ű', + 'ű' => 'ű', + 'Ų' => 'Ų', + 'ų' => 'ų', + 'Ŵ' => 'Ŵ', + 'ŵ' => 'ŵ', + 'Ŷ' => 'Ŷ', + 'ŷ' => 'ŷ', + 'Ÿ' => 'Ÿ', + 'Ź' => 'Ź', + 'ź' => 'ź', + 'Ż' => 'Ż', + 'ż' => 'ż', + 'Ž' => 'Ž', + 'ž' => 'ž', + 'Ơ' => 'Ơ', + 'ơ' => 'ơ', + 'Ư' => 'Ư', + 'ư' => 'ư', + 'Ǎ' => 'Ǎ', + 'ǎ' => 'ǎ', + 'Ǐ' => 'Ǐ', + 'ǐ' => 'ǐ', + 'Ǒ' => 'Ǒ', + 'ǒ' => 'ǒ', + 'Ǔ' => 'Ǔ', + 'ǔ' => 'ǔ', + 'Ǖ' => 'Ǖ', + 'ǖ' => 'ǖ', + 'Ǘ' => 'Ǘ', + 'ǘ' => 'ǘ', + 'Ǚ' => 'Ǚ', + 'ǚ' => 'ǚ', + 'Ǜ' => 'Ǜ', + 'ǜ' => 'ǜ', + 'Ǟ' => 'Ǟ', + 'ǟ' => 'ǟ', + 'Ǡ' => 'Ǡ', + 'ǡ' => 'ǡ', + 'Ǣ' => 'Ǣ', + 'ǣ' => 'ǣ', + 'Ǧ' => 'Ǧ', + 'ǧ' => 'ǧ', + 'Ǩ' => 'Ǩ', + 'ǩ' => 'ǩ', + 'Ǫ' => 'Ǫ', + 'ǫ' => 'ǫ', + 'Ǭ' => 'Ǭ', + 'ǭ' => 'ǭ', + 'Ǯ' => 'Ǯ', + 'ǯ' => 'ǯ', + 'ǰ' => 'ǰ', + 'Ǵ' => 'Ǵ', + 'ǵ' => 'ǵ', + 'Ǹ' => 'Ǹ', + 'ǹ' => 'ǹ', + 'Ǻ' => 'Ǻ', + 'ǻ' => 'ǻ', + 'Ǽ' => 'Ǽ', + 'ǽ' => 'ǽ', + 'Ǿ' => 'Ǿ', + 'ǿ' => 'ǿ', + 'Ȁ' => 'Ȁ', + 'ȁ' => 'ȁ', + 'Ȃ' => 'Ȃ', + 'ȃ' => 'ȃ', + 'Ȅ' => 'Ȅ', + 'ȅ' => 'ȅ', + 'Ȇ' => 'Ȇ', + 'ȇ' => 'ȇ', + 'Ȉ' => 'Ȉ', + 'ȉ' => 'ȉ', + 'Ȋ' => 'Ȋ', + 'ȋ' => 'ȋ', + 'Ȍ' => 'Ȍ', + 'ȍ' => 'ȍ', + 'Ȏ' => 'Ȏ', + 'ȏ' => 'ȏ', + 'Ȑ' => 'Ȑ', + 'ȑ' => 'ȑ', + 'Ȓ' => 'Ȓ', + 'ȓ' => 'ȓ', + 'Ȕ' => 'Ȕ', + 'ȕ' => 'ȕ', + 'Ȗ' => 'Ȗ', + 'ȗ' => 'ȗ', + 'Ș' => 'Ș', + 'ș' => 'ș', + 'Ț' => 'Ț', + 'ț' => 'ț', + 'Ȟ' => 'Ȟ', + 'ȟ' => 'ȟ', + 'Ȧ' => 'Ȧ', + 'ȧ' => 'ȧ', + 'Ȩ' => 'Ȩ', + 'ȩ' => 'ȩ', + 'Ȫ' => 'Ȫ', + 'ȫ' => 'ȫ', + 'Ȭ' => 'Ȭ', + 'ȭ' => 'ȭ', + 'Ȯ' => 'Ȯ', + 'ȯ' => 'ȯ', + 'Ȱ' => 'Ȱ', + 'ȱ' => 'ȱ', + 'Ȳ' => 'Ȳ', + 'ȳ' => 'ȳ', + '̀' => '̀', + '́' => '́', + '̓' => '̓', + '̈́' => '̈́', + 'ʹ' => 'ʹ', + ';' => ';', + '΅' => '΅', + 'Ά' => 'Ά', + '·' => '·', + 'Έ' => 'Έ', + 'Ή' => 'Ή', + 'Ί' => 'Ί', + 'Ό' => 'Ό', + 'Ύ' => 'Ύ', + 'Ώ' => 'Ώ', + 'ΐ' => 'ΐ', + 'Ϊ' => 'Ϊ', + 'Ϋ' => 'Ϋ', + 'ά' => 'ά', + 'έ' => 'έ', + 'ή' => 'ή', + 'ί' => 'ί', + 'ΰ' => 'ΰ', + 'ϊ' => 'ϊ', + 'ϋ' => 'ϋ', + 'ό' => 'ό', + 'ύ' => 'ύ', + 'ώ' => 'ώ', + 'ϓ' => 'ϓ', + 'ϔ' => 'ϔ', + 'Ѐ' => 'Ѐ', + 'Ё' => 'Ё', + 'Ѓ' => 'Ѓ', + 'Ї' => 'Ї', + 'Ќ' => 'Ќ', + 'Ѝ' => 'Ѝ', + 'Ў' => 'Ў', + 'Й' => 'Й', + 'й' => 'й', + 'ѐ' => 'ѐ', + 'ё' => 'ё', + 'ѓ' => 'ѓ', + 'ї' => 'ї', + 'ќ' => 'ќ', + 'ѝ' => 'ѝ', + 'ў' => 'ў', + 'Ѷ' => 'Ѷ', + 'ѷ' => 'ѷ', + 'Ӂ' => 'Ӂ', + 'ӂ' => 'ӂ', + 'Ӑ' => 'Ӑ', + 'ӑ' => 'ӑ', + 'Ӓ' => 'Ӓ', + 'ӓ' => 'ӓ', + 'Ӗ' => 'Ӗ', + 'ӗ' => 'ӗ', + 'Ӛ' => 'Ӛ', + 'ӛ' => 'ӛ', + 'Ӝ' => 'Ӝ', + 'ӝ' => 'ӝ', + 'Ӟ' => 'Ӟ', + 'ӟ' => 'ӟ', + 'Ӣ' => 'Ӣ', + 'ӣ' => 'ӣ', + 'Ӥ' => 'Ӥ', + 'ӥ' => 'ӥ', + 'Ӧ' => 'Ӧ', + 'ӧ' => 'ӧ', + 'Ӫ' => 'Ӫ', + 'ӫ' => 'ӫ', + 'Ӭ' => 'Ӭ', + 'ӭ' => 'ӭ', + 'Ӯ' => 'Ӯ', + 'ӯ' => 'ӯ', + 'Ӱ' => 'Ӱ', + 'ӱ' => 'ӱ', + 'Ӳ' => 'Ӳ', + 'ӳ' => 'ӳ', + 'Ӵ' => 'Ӵ', + 'ӵ' => 'ӵ', + 'Ӹ' => 'Ӹ', + 'ӹ' => 'ӹ', + 'آ' => 'آ', + 'أ' => 'أ', + 'ؤ' => 'ؤ', + 'إ' => 'إ', + 'ئ' => 'ئ', + 'ۀ' => 'ۀ', + 'ۂ' => 'ۂ', + 'ۓ' => 'ۓ', + 'ऩ' => 'ऩ', + 'ऱ' => 'ऱ', + 'ऴ' => 'ऴ', + 'क़' => 'क़', + 'ख़' => 'ख़', + 'ग़' => 'ग़', + 'ज़' => 'ज़', + 'ड़' => 'ड़', + 'ढ़' => 'ढ़', + 'फ़' => 'फ़', + 'य़' => 'य़', + 'ো' => 'ো', + 'ৌ' => 'ৌ', + 'ড়' => 'ড়', + 'ঢ়' => 'ঢ়', + 'য়' => 'য়', + 'ਲ਼' => 'ਲ਼', + 'ਸ਼' => 'ਸ਼', + 'ਖ਼' => 'ਖ਼', + 'ਗ਼' => 'ਗ਼', + 'ਜ਼' => 'ਜ਼', + 'ਫ਼' => 'ਫ਼', + 'ୈ' => 'ୈ', + 'ୋ' => 'ୋ', + 'ୌ' => 'ୌ', + 'ଡ଼' => 'ଡ଼', + 'ଢ଼' => 'ଢ଼', + 'ஔ' => 'ஔ', + 'ொ' => 'ொ', + 'ோ' => 'ோ', + 'ௌ' => 'ௌ', + 'ై' => 'ై', + 'ೀ' => 'ೀ', + 'ೇ' => 'ೇ', + 'ೈ' => 'ೈ', + 'ೊ' => 'ೊ', + 'ೋ' => 'ೋ', + 'ൊ' => 'ൊ', + 'ോ' => 'ോ', + 'ൌ' => 'ൌ', + 'ේ' => 'ේ', + 'ො' => 'ො', + 'ෝ' => 'ෝ', + 'ෞ' => 'ෞ', + 'གྷ' => 'གྷ', + 'ཌྷ' => 'ཌྷ', + 'དྷ' => 'དྷ', + 'བྷ' => 'བྷ', + 'ཛྷ' => 'ཛྷ', + 'ཀྵ' => 'ཀྵ', + 'ཱི' => 'ཱི', + 'ཱུ' => 'ཱུ', + 'ྲྀ' => 'ྲྀ', + 'ླྀ' => 'ླྀ', + 'ཱྀ' => 'ཱྀ', + 'ྒྷ' => 'ྒྷ', + 'ྜྷ' => 'ྜྷ', + 'ྡྷ' => 'ྡྷ', + 'ྦྷ' => 'ྦྷ', + 'ྫྷ' => 'ྫྷ', + 'ྐྵ' => 'ྐྵ', + 'ဦ' => 'ဦ', + 'ᬆ' => 'ᬆ', + 'ᬈ' => 'ᬈ', + 'ᬊ' => 'ᬊ', + 'ᬌ' => 'ᬌ', + 'ᬎ' => 'ᬎ', + 'ᬒ' => 'ᬒ', + 'ᬻ' => 'ᬻ', + 'ᬽ' => 'ᬽ', + 'ᭀ' => 'ᭀ', + 'ᭁ' => 'ᭁ', + 'ᭃ' => 'ᭃ', + 'Ḁ' => 'Ḁ', + 'ḁ' => 'ḁ', + 'Ḃ' => 'Ḃ', + 'ḃ' => 'ḃ', + 'Ḅ' => 'Ḅ', + 'ḅ' => 'ḅ', + 'Ḇ' => 'Ḇ', + 'ḇ' => 'ḇ', + 'Ḉ' => 'Ḉ', + 'ḉ' => 'ḉ', + 'Ḋ' => 'Ḋ', + 'ḋ' => 'ḋ', + 'Ḍ' => 'Ḍ', + 'ḍ' => 'ḍ', + 'Ḏ' => 'Ḏ', + 'ḏ' => 'ḏ', + 'Ḑ' => 'Ḑ', + 'ḑ' => 'ḑ', + 'Ḓ' => 'Ḓ', + 'ḓ' => 'ḓ', + 'Ḕ' => 'Ḕ', + 'ḕ' => 'ḕ', + 'Ḗ' => 'Ḗ', + 'ḗ' => 'ḗ', + 'Ḙ' => 'Ḙ', + 'ḙ' => 'ḙ', + 'Ḛ' => 'Ḛ', + 'ḛ' => 'ḛ', + 'Ḝ' => 'Ḝ', + 'ḝ' => 'ḝ', + 'Ḟ' => 'Ḟ', + 'ḟ' => 'ḟ', + 'Ḡ' => 'Ḡ', + 'ḡ' => 'ḡ', + 'Ḣ' => 'Ḣ', + 'ḣ' => 'ḣ', + 'Ḥ' => 'Ḥ', + 'ḥ' => 'ḥ', + 'Ḧ' => 'Ḧ', + 'ḧ' => 'ḧ', + 'Ḩ' => 'Ḩ', + 'ḩ' => 'ḩ', + 'Ḫ' => 'Ḫ', + 'ḫ' => 'ḫ', + 'Ḭ' => 'Ḭ', + 'ḭ' => 'ḭ', + 'Ḯ' => 'Ḯ', + 'ḯ' => 'ḯ', + 'Ḱ' => 'Ḱ', + 'ḱ' => 'ḱ', + 'Ḳ' => 'Ḳ', + 'ḳ' => 'ḳ', + 'Ḵ' => 'Ḵ', + 'ḵ' => 'ḵ', + 'Ḷ' => 'Ḷ', + 'ḷ' => 'ḷ', + 'Ḹ' => 'Ḹ', + 'ḹ' => 'ḹ', + 'Ḻ' => 'Ḻ', + 'ḻ' => 'ḻ', + 'Ḽ' => 'Ḽ', + 'ḽ' => 'ḽ', + 'Ḿ' => 'Ḿ', + 'ḿ' => 'ḿ', + 'Ṁ' => 'Ṁ', + 'ṁ' => 'ṁ', + 'Ṃ' => 'Ṃ', + 'ṃ' => 'ṃ', + 'Ṅ' => 'Ṅ', + 'ṅ' => 'ṅ', + 'Ṇ' => 'Ṇ', + 'ṇ' => 'ṇ', + 'Ṉ' => 'Ṉ', + 'ṉ' => 'ṉ', + 'Ṋ' => 'Ṋ', + 'ṋ' => 'ṋ', + 'Ṍ' => 'Ṍ', + 'ṍ' => 'ṍ', + 'Ṏ' => 'Ṏ', + 'ṏ' => 'ṏ', + 'Ṑ' => 'Ṑ', + 'ṑ' => 'ṑ', + 'Ṓ' => 'Ṓ', + 'ṓ' => 'ṓ', + 'Ṕ' => 'Ṕ', + 'ṕ' => 'ṕ', + 'Ṗ' => 'Ṗ', + 'ṗ' => 'ṗ', + 'Ṙ' => 'Ṙ', + 'ṙ' => 'ṙ', + 'Ṛ' => 'Ṛ', + 'ṛ' => 'ṛ', + 'Ṝ' => 'Ṝ', + 'ṝ' => 'ṝ', + 'Ṟ' => 'Ṟ', + 'ṟ' => 'ṟ', + 'Ṡ' => 'Ṡ', + 'ṡ' => 'ṡ', + 'Ṣ' => 'Ṣ', + 'ṣ' => 'ṣ', + 'Ṥ' => 'Ṥ', + 'ṥ' => 'ṥ', + 'Ṧ' => 'Ṧ', + 'ṧ' => 'ṧ', + 'Ṩ' => 'Ṩ', + 'ṩ' => 'ṩ', + 'Ṫ' => 'Ṫ', + 'ṫ' => 'ṫ', + 'Ṭ' => 'Ṭ', + 'ṭ' => 'ṭ', + 'Ṯ' => 'Ṯ', + 'ṯ' => 'ṯ', + 'Ṱ' => 'Ṱ', + 'ṱ' => 'ṱ', + 'Ṳ' => 'Ṳ', + 'ṳ' => 'ṳ', + 'Ṵ' => 'Ṵ', + 'ṵ' => 'ṵ', + 'Ṷ' => 'Ṷ', + 'ṷ' => 'ṷ', + 'Ṹ' => 'Ṹ', + 'ṹ' => 'ṹ', + 'Ṻ' => 'Ṻ', + 'ṻ' => 'ṻ', + 'Ṽ' => 'Ṽ', + 'ṽ' => 'ṽ', + 'Ṿ' => 'Ṿ', + 'ṿ' => 'ṿ', + 'Ẁ' => 'Ẁ', + 'ẁ' => 'ẁ', + 'Ẃ' => 'Ẃ', + 'ẃ' => 'ẃ', + 'Ẅ' => 'Ẅ', + 'ẅ' => 'ẅ', + 'Ẇ' => 'Ẇ', + 'ẇ' => 'ẇ', + 'Ẉ' => 'Ẉ', + 'ẉ' => 'ẉ', + 'Ẋ' => 'Ẋ', + 'ẋ' => 'ẋ', + 'Ẍ' => 'Ẍ', + 'ẍ' => 'ẍ', + 'Ẏ' => 'Ẏ', + 'ẏ' => 'ẏ', + 'Ẑ' => 'Ẑ', + 'ẑ' => 'ẑ', + 'Ẓ' => 'Ẓ', + 'ẓ' => 'ẓ', + 'Ẕ' => 'Ẕ', + 'ẕ' => 'ẕ', + 'ẖ' => 'ẖ', + 'ẗ' => 'ẗ', + 'ẘ' => 'ẘ', + 'ẙ' => 'ẙ', + 'ẛ' => 'ẛ', + 'Ạ' => 'Ạ', + 'ạ' => 'ạ', + 'Ả' => 'Ả', + 'ả' => 'ả', + 'Ấ' => 'Ấ', + 'ấ' => 'ấ', + 'Ầ' => 'Ầ', + 'ầ' => 'ầ', + 'Ẩ' => 'Ẩ', + 'ẩ' => 'ẩ', + 'Ẫ' => 'Ẫ', + 'ẫ' => 'ẫ', + 'Ậ' => 'Ậ', + 'ậ' => 'ậ', + 'Ắ' => 'Ắ', + 'ắ' => 'ắ', + 'Ằ' => 'Ằ', + 'ằ' => 'ằ', + 'Ẳ' => 'Ẳ', + 'ẳ' => 'ẳ', + 'Ẵ' => 'Ẵ', + 'ẵ' => 'ẵ', + 'Ặ' => 'Ặ', + 'ặ' => 'ặ', + 'Ẹ' => 'Ẹ', + 'ẹ' => 'ẹ', + 'Ẻ' => 'Ẻ', + 'ẻ' => 'ẻ', + 'Ẽ' => 'Ẽ', + 'ẽ' => 'ẽ', + 'Ế' => 'Ế', + 'ế' => 'ế', + 'Ề' => 'Ề', + 'ề' => 'ề', + 'Ể' => 'Ể', + 'ể' => 'ể', + 'Ễ' => 'Ễ', + 'ễ' => 'ễ', + 'Ệ' => 'Ệ', + 'ệ' => 'ệ', + 'Ỉ' => 'Ỉ', + 'ỉ' => 'ỉ', + 'Ị' => 'Ị', + 'ị' => 'ị', + 'Ọ' => 'Ọ', + 'ọ' => 'ọ', + 'Ỏ' => 'Ỏ', + 'ỏ' => 'ỏ', + 'Ố' => 'Ố', + 'ố' => 'ố', + 'Ồ' => 'Ồ', + 'ồ' => 'ồ', + 'Ổ' => 'Ổ', + 'ổ' => 'ổ', + 'Ỗ' => 'Ỗ', + 'ỗ' => 'ỗ', + 'Ộ' => 'Ộ', + 'ộ' => 'ộ', + 'Ớ' => 'Ớ', + 'ớ' => 'ớ', + 'Ờ' => 'Ờ', + 'ờ' => 'ờ', + 'Ở' => 'Ở', + 'ở' => 'ở', + 'Ỡ' => 'Ỡ', + 'ỡ' => 'ỡ', + 'Ợ' => 'Ợ', + 'ợ' => 'ợ', + 'Ụ' => 'Ụ', + 'ụ' => 'ụ', + 'Ủ' => 'Ủ', + 'ủ' => 'ủ', + 'Ứ' => 'Ứ', + 'ứ' => 'ứ', + 'Ừ' => 'Ừ', + 'ừ' => 'ừ', + 'Ử' => 'Ử', + 'ử' => 'ử', + 'Ữ' => 'Ữ', + 'ữ' => 'ữ', + 'Ự' => 'Ự', + 'ự' => 'ự', + 'Ỳ' => 'Ỳ', + 'ỳ' => 'ỳ', + 'Ỵ' => 'Ỵ', + 'ỵ' => 'ỵ', + 'Ỷ' => 'Ỷ', + 'ỷ' => 'ỷ', + 'Ỹ' => 'Ỹ', + 'ỹ' => 'ỹ', + 'ἀ' => 'ἀ', + 'ἁ' => 'ἁ', + 'ἂ' => 'ἂ', + 'ἃ' => 'ἃ', + 'ἄ' => 'ἄ', + 'ἅ' => 'ἅ', + 'ἆ' => 'ἆ', + 'ἇ' => 'ἇ', + 'Ἀ' => 'Ἀ', + 'Ἁ' => 'Ἁ', + 'Ἂ' => 'Ἂ', + 'Ἃ' => 'Ἃ', + 'Ἄ' => 'Ἄ', + 'Ἅ' => 'Ἅ', + 'Ἆ' => 'Ἆ', + 'Ἇ' => 'Ἇ', + 'ἐ' => 'ἐ', + 'ἑ' => 'ἑ', + 'ἒ' => 'ἒ', + 'ἓ' => 'ἓ', + 'ἔ' => 'ἔ', + 'ἕ' => 'ἕ', + 'Ἐ' => 'Ἐ', + 'Ἑ' => 'Ἑ', + 'Ἒ' => 'Ἒ', + 'Ἓ' => 'Ἓ', + 'Ἔ' => 'Ἔ', + 'Ἕ' => 'Ἕ', + 'ἠ' => 'ἠ', + 'ἡ' => 'ἡ', + 'ἢ' => 'ἢ', + 'ἣ' => 'ἣ', + 'ἤ' => 'ἤ', + 'ἥ' => 'ἥ', + 'ἦ' => 'ἦ', + 'ἧ' => 'ἧ', + 'Ἠ' => 'Ἠ', + 'Ἡ' => 'Ἡ', + 'Ἢ' => 'Ἢ', + 'Ἣ' => 'Ἣ', + 'Ἤ' => 'Ἤ', + 'Ἥ' => 'Ἥ', + 'Ἦ' => 'Ἦ', + 'Ἧ' => 'Ἧ', + 'ἰ' => 'ἰ', + 'ἱ' => 'ἱ', + 'ἲ' => 'ἲ', + 'ἳ' => 'ἳ', + 'ἴ' => 'ἴ', + 'ἵ' => 'ἵ', + 'ἶ' => 'ἶ', + 'ἷ' => 'ἷ', + 'Ἰ' => 'Ἰ', + 'Ἱ' => 'Ἱ', + 'Ἲ' => 'Ἲ', + 'Ἳ' => 'Ἳ', + 'Ἴ' => 'Ἴ', + 'Ἵ' => 'Ἵ', + 'Ἶ' => 'Ἶ', + 'Ἷ' => 'Ἷ', + 'ὀ' => 'ὀ', + 'ὁ' => 'ὁ', + 'ὂ' => 'ὂ', + 'ὃ' => 'ὃ', + 'ὄ' => 'ὄ', + 'ὅ' => 'ὅ', + 'Ὀ' => 'Ὀ', + 'Ὁ' => 'Ὁ', + 'Ὂ' => 'Ὂ', + 'Ὃ' => 'Ὃ', + 'Ὄ' => 'Ὄ', + 'Ὅ' => 'Ὅ', + 'ὐ' => 'ὐ', + 'ὑ' => 'ὑ', + 'ὒ' => 'ὒ', + 'ὓ' => 'ὓ', + 'ὔ' => 'ὔ', + 'ὕ' => 'ὕ', + 'ὖ' => 'ὖ', + 'ὗ' => 'ὗ', + 'Ὑ' => 'Ὑ', + 'Ὓ' => 'Ὓ', + 'Ὕ' => 'Ὕ', + 'Ὗ' => 'Ὗ', + 'ὠ' => 'ὠ', + 'ὡ' => 'ὡ', + 'ὢ' => 'ὢ', + 'ὣ' => 'ὣ', + 'ὤ' => 'ὤ', + 'ὥ' => 'ὥ', + 'ὦ' => 'ὦ', + 'ὧ' => 'ὧ', + 'Ὠ' => 'Ὠ', + 'Ὡ' => 'Ὡ', + 'Ὢ' => 'Ὢ', + 'Ὣ' => 'Ὣ', + 'Ὤ' => 'Ὤ', + 'Ὥ' => 'Ὥ', + 'Ὦ' => 'Ὦ', + 'Ὧ' => 'Ὧ', + 'ὰ' => 'ὰ', + 'ά' => 'ά', + 'ὲ' => 'ὲ', + 'έ' => 'έ', + 'ὴ' => 'ὴ', + 'ή' => 'ή', + 'ὶ' => 'ὶ', + 'ί' => 'ί', + 'ὸ' => 'ὸ', + 'ό' => 'ό', + 'ὺ' => 'ὺ', + 'ύ' => 'ύ', + 'ὼ' => 'ὼ', + 'ώ' => 'ώ', + 'ᾀ' => 'ᾀ', + 'ᾁ' => 'ᾁ', + 'ᾂ' => 'ᾂ', + 'ᾃ' => 'ᾃ', + 'ᾄ' => 'ᾄ', + 'ᾅ' => 'ᾅ', + 'ᾆ' => 'ᾆ', + 'ᾇ' => 'ᾇ', + 'ᾈ' => 'ᾈ', + 'ᾉ' => 'ᾉ', + 'ᾊ' => 'ᾊ', + 'ᾋ' => 'ᾋ', + 'ᾌ' => 'ᾌ', + 'ᾍ' => 'ᾍ', + 'ᾎ' => 'ᾎ', + 'ᾏ' => 'ᾏ', + 'ᾐ' => 'ᾐ', + 'ᾑ' => 'ᾑ', + 'ᾒ' => 'ᾒ', + 'ᾓ' => 'ᾓ', + 'ᾔ' => 'ᾔ', + 'ᾕ' => 'ᾕ', + 'ᾖ' => 'ᾖ', + 'ᾗ' => 'ᾗ', + 'ᾘ' => 'ᾘ', + 'ᾙ' => 'ᾙ', + 'ᾚ' => 'ᾚ', + 'ᾛ' => 'ᾛ', + 'ᾜ' => 'ᾜ', + 'ᾝ' => 'ᾝ', + 'ᾞ' => 'ᾞ', + 'ᾟ' => 'ᾟ', + 'ᾠ' => 'ᾠ', + 'ᾡ' => 'ᾡ', + 'ᾢ' => 'ᾢ', + 'ᾣ' => 'ᾣ', + 'ᾤ' => 'ᾤ', + 'ᾥ' => 'ᾥ', + 'ᾦ' => 'ᾦ', + 'ᾧ' => 'ᾧ', + 'ᾨ' => 'ᾨ', + 'ᾩ' => 'ᾩ', + 'ᾪ' => 'ᾪ', + 'ᾫ' => 'ᾫ', + 'ᾬ' => 'ᾬ', + 'ᾭ' => 'ᾭ', + 'ᾮ' => 'ᾮ', + 'ᾯ' => 'ᾯ', + 'ᾰ' => 'ᾰ', + 'ᾱ' => 'ᾱ', + 'ᾲ' => 'ᾲ', + 'ᾳ' => 'ᾳ', + 'ᾴ' => 'ᾴ', + 'ᾶ' => 'ᾶ', + 'ᾷ' => 'ᾷ', + 'Ᾰ' => 'Ᾰ', + 'Ᾱ' => 'Ᾱ', + 'Ὰ' => 'Ὰ', + 'Ά' => 'Ά', + 'ᾼ' => 'ᾼ', + 'ι' => 'ι', + '῁' => '῁', + 'ῂ' => 'ῂ', + 'ῃ' => 'ῃ', + 'ῄ' => 'ῄ', + 'ῆ' => 'ῆ', + 'ῇ' => 'ῇ', + 'Ὲ' => 'Ὲ', + 'Έ' => 'Έ', + 'Ὴ' => 'Ὴ', + 'Ή' => 'Ή', + 'ῌ' => 'ῌ', + '῍' => '῍', + '῎' => '῎', + '῏' => '῏', + 'ῐ' => 'ῐ', + 'ῑ' => 'ῑ', + 'ῒ' => 'ῒ', + 'ΐ' => 'ΐ', + 'ῖ' => 'ῖ', + 'ῗ' => 'ῗ', + 'Ῐ' => 'Ῐ', + 'Ῑ' => 'Ῑ', + 'Ὶ' => 'Ὶ', + 'Ί' => 'Ί', + '῝' => '῝', + '῞' => '῞', + '῟' => '῟', + 'ῠ' => 'ῠ', + 'ῡ' => 'ῡ', + 'ῢ' => 'ῢ', + 'ΰ' => 'ΰ', + 'ῤ' => 'ῤ', + 'ῥ' => 'ῥ', + 'ῦ' => 'ῦ', + 'ῧ' => 'ῧ', + 'Ῠ' => 'Ῠ', + 'Ῡ' => 'Ῡ', + 'Ὺ' => 'Ὺ', + 'Ύ' => 'Ύ', + 'Ῥ' => 'Ῥ', + '῭' => '῭', + '΅' => '΅', + '`' => '`', + 'ῲ' => 'ῲ', + 'ῳ' => 'ῳ', + 'ῴ' => 'ῴ', + 'ῶ' => 'ῶ', + 'ῷ' => 'ῷ', + 'Ὸ' => 'Ὸ', + 'Ό' => 'Ό', + 'Ὼ' => 'Ὼ', + 'Ώ' => 'Ώ', + 'ῼ' => 'ῼ', + '´' => '´', + ' ' => ' ', + ' ' => ' ', + 'Ω' => 'Ω', + 'K' => 'K', + 'Å' => 'Å', + '↚' => '↚', + '↛' => '↛', + '↮' => '↮', + '⇍' => '⇍', + '⇎' => '⇎', + '⇏' => '⇏', + '∄' => '∄', + '∉' => '∉', + '∌' => '∌', + '∤' => '∤', + '∦' => '∦', + '≁' => '≁', + '≄' => '≄', + '≇' => '≇', + '≉' => '≉', + '≠' => '≠', + '≢' => '≢', + '≭' => '≭', + '≮' => '≮', + '≯' => '≯', + '≰' => '≰', + '≱' => '≱', + '≴' => '≴', + '≵' => '≵', + '≸' => '≸', + '≹' => '≹', + '⊀' => '⊀', + '⊁' => '⊁', + '⊄' => '⊄', + '⊅' => '⊅', + '⊈' => '⊈', + '⊉' => '⊉', + '⊬' => '⊬', + '⊭' => '⊭', + '⊮' => '⊮', + '⊯' => '⊯', + '⋠' => '⋠', + '⋡' => '⋡', + '⋢' => '⋢', + '⋣' => '⋣', + '⋪' => '⋪', + '⋫' => '⋫', + '⋬' => '⋬', + '⋭' => '⋭', + '〈' => '〈', + '〉' => '〉', + '⫝̸' => '⫝̸', + 'が' => 'が', + 'ぎ' => 'ぎ', + 'ぐ' => 'ぐ', + 'げ' => 'げ', + 'ご' => 'ご', + 'ざ' => 'ざ', + 'じ' => 'じ', + 'ず' => 'ず', + 'ぜ' => 'ぜ', + 'ぞ' => 'ぞ', + 'だ' => 'だ', + 'ぢ' => 'ぢ', + 'づ' => 'づ', + 'で' => 'で', + 'ど' => 'ど', + 'ば' => 'ば', + 'ぱ' => 'ぱ', + 'び' => 'び', + 'ぴ' => 'ぴ', + 'ぶ' => 'ぶ', + 'ぷ' => 'ぷ', + 'べ' => 'べ', + 'ぺ' => 'ぺ', + 'ぼ' => 'ぼ', + 'ぽ' => 'ぽ', + 'ゔ' => 'ゔ', + 'ゞ' => 'ゞ', + 'ガ' => 'ガ', + 'ギ' => 'ギ', + 'グ' => 'グ', + 'ゲ' => 'ゲ', + 'ゴ' => 'ゴ', + 'ザ' => 'ザ', + 'ジ' => 'ジ', + 'ズ' => 'ズ', + 'ゼ' => 'ゼ', + 'ゾ' => 'ゾ', + 'ダ' => 'ダ', + 'ヂ' => 'ヂ', + 'ヅ' => 'ヅ', + 'デ' => 'デ', + 'ド' => 'ド', + 'バ' => 'バ', + 'パ' => 'パ', + 'ビ' => 'ビ', + 'ピ' => 'ピ', + 'ブ' => 'ブ', + 'プ' => 'プ', + 'ベ' => 'ベ', + 'ペ' => 'ペ', + 'ボ' => 'ボ', + 'ポ' => 'ポ', + 'ヴ' => 'ヴ', + 'ヷ' => 'ヷ', + 'ヸ' => 'ヸ', + 'ヹ' => 'ヹ', + 'ヺ' => 'ヺ', + 'ヾ' => 'ヾ', + '豈' => '豈', + '更' => '更', + '車' => '車', + '賈' => '賈', + '滑' => '滑', + '串' => '串', + '句' => '句', + '龜' => '龜', + '龜' => '龜', + '契' => '契', + '金' => '金', + '喇' => '喇', + '奈' => '奈', + '懶' => '懶', + '癩' => '癩', + '羅' => '羅', + '蘿' => '蘿', + '螺' => '螺', + '裸' => '裸', + '邏' => '邏', + '樂' => '樂', + '洛' => '洛', + '烙' => '烙', + '珞' => '珞', + '落' => '落', + '酪' => '酪', + '駱' => '駱', + '亂' => '亂', + '卵' => '卵', + '欄' => '欄', + '爛' => '爛', + '蘭' => '蘭', + '鸞' => '鸞', + '嵐' => '嵐', + '濫' => '濫', + '藍' => '藍', + '襤' => '襤', + '拉' => '拉', + '臘' => '臘', + '蠟' => '蠟', + '廊' => '廊', + '朗' => '朗', + '浪' => '浪', + '狼' => '狼', + '郎' => '郎', + '來' => '來', + '冷' => '冷', + '勞' => '勞', + '擄' => '擄', + '櫓' => '櫓', + '爐' => '爐', + '盧' => '盧', + '老' => '老', + '蘆' => '蘆', + '虜' => '虜', + '路' => '路', + '露' => '露', + '魯' => '魯', + '鷺' => '鷺', + '碌' => '碌', + '祿' => '祿', + '綠' => '綠', + '菉' => '菉', + '錄' => '錄', + '鹿' => '鹿', + '論' => '論', + '壟' => '壟', + '弄' => '弄', + '籠' => '籠', + '聾' => '聾', + '牢' => '牢', + '磊' => '磊', + '賂' => '賂', + '雷' => '雷', + '壘' => '壘', + '屢' => '屢', + '樓' => '樓', + '淚' => '淚', + '漏' => '漏', + '累' => '累', + '縷' => '縷', + '陋' => '陋', + '勒' => '勒', + '肋' => '肋', + '凜' => '凜', + '凌' => '凌', + '稜' => '稜', + '綾' => '綾', + '菱' => '菱', + '陵' => '陵', + '讀' => '讀', + '拏' => '拏', + '樂' => '樂', + '諾' => '諾', + '丹' => '丹', + '寧' => '寧', + '怒' => '怒', + '率' => '率', + '異' => '異', + '北' => '北', + '磻' => '磻', + '便' => '便', + '復' => '復', + '不' => '不', + '泌' => '泌', + '數' => '數', + '索' => '索', + '參' => '參', + '塞' => '塞', + '省' => '省', + '葉' => '葉', + '說' => '說', + '殺' => '殺', + '辰' => '辰', + '沈' => '沈', + '拾' => '拾', + '若' => '若', + '掠' => '掠', + '略' => '略', + '亮' => '亮', + '兩' => '兩', + '凉' => '凉', + '梁' => '梁', + '糧' => '糧', + '良' => '良', + '諒' => '諒', + '量' => '量', + '勵' => '勵', + '呂' => '呂', + '女' => '女', + '廬' => '廬', + '旅' => '旅', + '濾' => '濾', + '礪' => '礪', + '閭' => '閭', + '驪' => '驪', + '麗' => '麗', + '黎' => '黎', + '力' => '力', + '曆' => '曆', + '歷' => '歷', + '轢' => '轢', + '年' => '年', + '憐' => '憐', + '戀' => '戀', + '撚' => '撚', + '漣' => '漣', + '煉' => '煉', + '璉' => '璉', + '秊' => '秊', + '練' => '練', + '聯' => '聯', + '輦' => '輦', + '蓮' => '蓮', + '連' => '連', + '鍊' => '鍊', + '列' => '列', + '劣' => '劣', + '咽' => '咽', + '烈' => '烈', + '裂' => '裂', + '說' => '說', + '廉' => '廉', + '念' => '念', + '捻' => '捻', + '殮' => '殮', + '簾' => '簾', + '獵' => '獵', + '令' => '令', + '囹' => '囹', + '寧' => '寧', + '嶺' => '嶺', + '怜' => '怜', + '玲' => '玲', + '瑩' => '瑩', + '羚' => '羚', + '聆' => '聆', + '鈴' => '鈴', + '零' => '零', + '靈' => '靈', + '領' => '領', + '例' => '例', + '禮' => '禮', + '醴' => '醴', + '隸' => '隸', + '惡' => '惡', + '了' => '了', + '僚' => '僚', + '寮' => '寮', + '尿' => '尿', + '料' => '料', + '樂' => '樂', + '燎' => '燎', + '療' => '療', + '蓼' => '蓼', + '遼' => '遼', + '龍' => '龍', + '暈' => '暈', + '阮' => '阮', + '劉' => '劉', + '杻' => '杻', + '柳' => '柳', + '流' => '流', + '溜' => '溜', + '琉' => '琉', + '留' => '留', + '硫' => '硫', + '紐' => '紐', + '類' => '類', + '六' => '六', + '戮' => '戮', + '陸' => '陸', + '倫' => '倫', + '崙' => '崙', + '淪' => '淪', + '輪' => '輪', + '律' => '律', + '慄' => '慄', + '栗' => '栗', + '率' => '率', + '隆' => '隆', + '利' => '利', + '吏' => '吏', + '履' => '履', + '易' => '易', + '李' => '李', + '梨' => '梨', + '泥' => '泥', + '理' => '理', + '痢' => '痢', + '罹' => '罹', + '裏' => '裏', + '裡' => '裡', + '里' => '里', + '離' => '離', + '匿' => '匿', + '溺' => '溺', + '吝' => '吝', + '燐' => '燐', + '璘' => '璘', + '藺' => '藺', + '隣' => '隣', + '鱗' => '鱗', + '麟' => '麟', + '林' => '林', + '淋' => '淋', + '臨' => '臨', + '立' => '立', + '笠' => '笠', + '粒' => '粒', + '狀' => '狀', + '炙' => '炙', + '識' => '識', + '什' => '什', + '茶' => '茶', + '刺' => '刺', + '切' => '切', + '度' => '度', + '拓' => '拓', + '糖' => '糖', + '宅' => '宅', + '洞' => '洞', + '暴' => '暴', + '輻' => '輻', + '行' => '行', + '降' => '降', + '見' => '見', + '廓' => '廓', + '兀' => '兀', + '嗀' => '嗀', + '塚' => '塚', + '晴' => '晴', + '凞' => '凞', + '猪' => '猪', + '益' => '益', + '礼' => '礼', + '神' => '神', + '祥' => '祥', + '福' => '福', + '靖' => '靖', + '精' => '精', + '羽' => '羽', + '蘒' => '蘒', + '諸' => '諸', + '逸' => '逸', + '都' => '都', + '飯' => '飯', + '飼' => '飼', + '館' => '館', + '鶴' => '鶴', + '郞' => '郞', + '隷' => '隷', + '侮' => '侮', + '僧' => '僧', + '免' => '免', + '勉' => '勉', + '勤' => '勤', + '卑' => '卑', + '喝' => '喝', + '嘆' => '嘆', + '器' => '器', + '塀' => '塀', + '墨' => '墨', + '層' => '層', + '屮' => '屮', + '悔' => '悔', + '慨' => '慨', + '憎' => '憎', + '懲' => '懲', + '敏' => '敏', + '既' => '既', + '暑' => '暑', + '梅' => '梅', + '海' => '海', + '渚' => '渚', + '漢' => '漢', + '煮' => '煮', + '爫' => '爫', + '琢' => '琢', + '碑' => '碑', + '社' => '社', + '祉' => '祉', + '祈' => '祈', + '祐' => '祐', + '祖' => '祖', + '祝' => '祝', + '禍' => '禍', + '禎' => '禎', + '穀' => '穀', + '突' => '突', + '節' => '節', + '練' => '練', + '縉' => '縉', + '繁' => '繁', + '署' => '署', + '者' => '者', + '臭' => '臭', + '艹' => '艹', + '艹' => '艹', + '著' => '著', + '褐' => '褐', + '視' => '視', + '謁' => '謁', + '謹' => '謹', + '賓' => '賓', + '贈' => '贈', + '辶' => '辶', + '逸' => '逸', + '難' => '難', + '響' => '響', + '頻' => '頻', + '恵' => '恵', + '𤋮' => '𤋮', + '舘' => '舘', + '並' => '並', + '况' => '况', + '全' => '全', + '侀' => '侀', + '充' => '充', + '冀' => '冀', + '勇' => '勇', + '勺' => '勺', + '喝' => '喝', + '啕' => '啕', + '喙' => '喙', + '嗢' => '嗢', + '塚' => '塚', + '墳' => '墳', + '奄' => '奄', + '奔' => '奔', + '婢' => '婢', + '嬨' => '嬨', + '廒' => '廒', + '廙' => '廙', + '彩' => '彩', + '徭' => '徭', + '惘' => '惘', + '慎' => '慎', + '愈' => '愈', + '憎' => '憎', + '慠' => '慠', + '懲' => '懲', + '戴' => '戴', + '揄' => '揄', + '搜' => '搜', + '摒' => '摒', + '敖' => '敖', + '晴' => '晴', + '朗' => '朗', + '望' => '望', + '杖' => '杖', + '歹' => '歹', + '殺' => '殺', + '流' => '流', + '滛' => '滛', + '滋' => '滋', + '漢' => '漢', + '瀞' => '瀞', + '煮' => '煮', + '瞧' => '瞧', + '爵' => '爵', + '犯' => '犯', + '猪' => '猪', + '瑱' => '瑱', + '甆' => '甆', + '画' => '画', + '瘝' => '瘝', + '瘟' => '瘟', + '益' => '益', + '盛' => '盛', + '直' => '直', + '睊' => '睊', + '着' => '着', + '磌' => '磌', + '窱' => '窱', + '節' => '節', + '类' => '类', + '絛' => '絛', + '練' => '練', + '缾' => '缾', + '者' => '者', + '荒' => '荒', + '華' => '華', + '蝹' => '蝹', + '襁' => '襁', + '覆' => '覆', + '視' => '視', + '調' => '調', + '諸' => '諸', + '請' => '請', + '謁' => '謁', + '諾' => '諾', + '諭' => '諭', + '謹' => '謹', + '變' => '變', + '贈' => '贈', + '輸' => '輸', + '遲' => '遲', + '醙' => '醙', + '鉶' => '鉶', + '陼' => '陼', + '難' => '難', + '靖' => '靖', + '韛' => '韛', + '響' => '響', + '頋' => '頋', + '頻' => '頻', + '鬒' => '鬒', + '龜' => '龜', + '𢡊' => '𢡊', + '𢡄' => '𢡄', + '𣏕' => '𣏕', + '㮝' => '㮝', + '䀘' => '䀘', + '䀹' => '䀹', + '𥉉' => '𥉉', + '𥳐' => '𥳐', + '𧻓' => '𧻓', + '齃' => '齃', + '龎' => '龎', + 'יִ' => 'יִ', + 'ײַ' => 'ײַ', + 'שׁ' => 'שׁ', + 'שׂ' => 'שׂ', + 'שּׁ' => 'שּׁ', + 'שּׂ' => 'שּׂ', + 'אַ' => 'אַ', + 'אָ' => 'אָ', + 'אּ' => 'אּ', + 'בּ' => 'בּ', + 'גּ' => 'גּ', + 'דּ' => 'דּ', + 'הּ' => 'הּ', + 'וּ' => 'וּ', + 'זּ' => 'זּ', + 'טּ' => 'טּ', + 'יּ' => 'יּ', + 'ךּ' => 'ךּ', + 'כּ' => 'כּ', + 'לּ' => 'לּ', + 'מּ' => 'מּ', + 'נּ' => 'נּ', + 'סּ' => 'סּ', + 'ףּ' => 'ףּ', + 'פּ' => 'פּ', + 'צּ' => 'צּ', + 'קּ' => 'קּ', + 'רּ' => 'רּ', + 'שּ' => 'שּ', + 'תּ' => 'תּ', + 'וֹ' => 'וֹ', + 'בֿ' => 'בֿ', + 'כֿ' => 'כֿ', + 'פֿ' => 'פֿ', + '𑂚' => '𑂚', + '𑂜' => '𑂜', + '𑂫' => '𑂫', + '𑄮' => '𑄮', + '𑄯' => '𑄯', + '𑍋' => '𑍋', + '𑍌' => '𑍌', + '𑒻' => '𑒻', + '𑒼' => '𑒼', + '𑒾' => '𑒾', + '𑖺' => '𑖺', + '𑖻' => '𑖻', + '𑤸' => '𑤸', + '𝅗𝅥' => '𝅗𝅥', + '𝅘𝅥' => '𝅘𝅥', + '𝅘𝅥𝅮' => '𝅘𝅥𝅮', + '𝅘𝅥𝅯' => '𝅘𝅥𝅯', + '𝅘𝅥𝅰' => '𝅘𝅥𝅰', + '𝅘𝅥𝅱' => '𝅘𝅥𝅱', + '𝅘𝅥𝅲' => '𝅘𝅥𝅲', + '𝆹𝅥' => '𝆹𝅥', + '𝆺𝅥' => '𝆺𝅥', + '𝆹𝅥𝅮' => '𝆹𝅥𝅮', + '𝆺𝅥𝅮' => '𝆺𝅥𝅮', + '𝆹𝅥𝅯' => '𝆹𝅥𝅯', + '𝆺𝅥𝅯' => '𝆺𝅥𝅯', + '丽' => '丽', + '丸' => '丸', + '乁' => '乁', + '𠄢' => '𠄢', + '你' => '你', + '侮' => '侮', + '侻' => '侻', + '倂' => '倂', + '偺' => '偺', + '備' => '備', + '僧' => '僧', + '像' => '像', + '㒞' => '㒞', + '𠘺' => '𠘺', + '免' => '免', + '兔' => '兔', + '兤' => '兤', + '具' => '具', + '𠔜' => '𠔜', + '㒹' => '㒹', + '內' => '內', + '再' => '再', + '𠕋' => '𠕋', + '冗' => '冗', + '冤' => '冤', + '仌' => '仌', + '冬' => '冬', + '况' => '况', + '𩇟' => '𩇟', + '凵' => '凵', + '刃' => '刃', + '㓟' => '㓟', + '刻' => '刻', + '剆' => '剆', + '割' => '割', + '剷' => '剷', + '㔕' => '㔕', + '勇' => '勇', + '勉' => '勉', + '勤' => '勤', + '勺' => '勺', + '包' => '包', + '匆' => '匆', + '北' => '北', + '卉' => '卉', + '卑' => '卑', + '博' => '博', + '即' => '即', + '卽' => '卽', + '卿' => '卿', + '卿' => '卿', + '卿' => '卿', + '𠨬' => '𠨬', + '灰' => '灰', + '及' => '及', + '叟' => '叟', + '𠭣' => '𠭣', + '叫' => '叫', + '叱' => '叱', + '吆' => '吆', + '咞' => '咞', + '吸' => '吸', + '呈' => '呈', + '周' => '周', + '咢' => '咢', + '哶' => '哶', + '唐' => '唐', + '啓' => '啓', + '啣' => '啣', + '善' => '善', + '善' => '善', + '喙' => '喙', + '喫' => '喫', + '喳' => '喳', + '嗂' => '嗂', + '圖' => '圖', + '嘆' => '嘆', + '圗' => '圗', + '噑' => '噑', + '噴' => '噴', + '切' => '切', + '壮' => '壮', + '城' => '城', + '埴' => '埴', + '堍' => '堍', + '型' => '型', + '堲' => '堲', + '報' => '報', + '墬' => '墬', + '𡓤' => '𡓤', + '売' => '売', + '壷' => '壷', + '夆' => '夆', + '多' => '多', + '夢' => '夢', + '奢' => '奢', + '𡚨' => '𡚨', + '𡛪' => '𡛪', + '姬' => '姬', + '娛' => '娛', + '娧' => '娧', + '姘' => '姘', + '婦' => '婦', + '㛮' => '㛮', + '㛼' => '㛼', + '嬈' => '嬈', + '嬾' => '嬾', + '嬾' => '嬾', + '𡧈' => '𡧈', + '寃' => '寃', + '寘' => '寘', + '寧' => '寧', + '寳' => '寳', + '𡬘' => '𡬘', + '寿' => '寿', + '将' => '将', + '当' => '当', + '尢' => '尢', + '㞁' => '㞁', + '屠' => '屠', + '屮' => '屮', + '峀' => '峀', + '岍' => '岍', + '𡷤' => '𡷤', + '嵃' => '嵃', + '𡷦' => '𡷦', + '嵮' => '嵮', + '嵫' => '嵫', + '嵼' => '嵼', + '巡' => '巡', + '巢' => '巢', + '㠯' => '㠯', + '巽' => '巽', + '帨' => '帨', + '帽' => '帽', + '幩' => '幩', + '㡢' => '㡢', + '𢆃' => '𢆃', + '㡼' => '㡼', + '庰' => '庰', + '庳' => '庳', + '庶' => '庶', + '廊' => '廊', + '𪎒' => '𪎒', + '廾' => '廾', + '𢌱' => '𢌱', + '𢌱' => '𢌱', + '舁' => '舁', + '弢' => '弢', + '弢' => '弢', + '㣇' => '㣇', + '𣊸' => '𣊸', + '𦇚' => '𦇚', + '形' => '形', + '彫' => '彫', + '㣣' => '㣣', + '徚' => '徚', + '忍' => '忍', + '志' => '志', + '忹' => '忹', + '悁' => '悁', + '㤺' => '㤺', + '㤜' => '㤜', + '悔' => '悔', + '𢛔' => '𢛔', + '惇' => '惇', + '慈' => '慈', + '慌' => '慌', + '慎' => '慎', + '慌' => '慌', + '慺' => '慺', + '憎' => '憎', + '憲' => '憲', + '憤' => '憤', + '憯' => '憯', + '懞' => '懞', + '懲' => '懲', + '懶' => '懶', + '成' => '成', + '戛' => '戛', + '扝' => '扝', + '抱' => '抱', + '拔' => '拔', + '捐' => '捐', + '𢬌' => '𢬌', + '挽' => '挽', + '拼' => '拼', + '捨' => '捨', + '掃' => '掃', + '揤' => '揤', + '𢯱' => '𢯱', + '搢' => '搢', + '揅' => '揅', + '掩' => '掩', + '㨮' => '㨮', + '摩' => '摩', + '摾' => '摾', + '撝' => '撝', + '摷' => '摷', + '㩬' => '㩬', + '敏' => '敏', + '敬' => '敬', + '𣀊' => '𣀊', + '旣' => '旣', + '書' => '書', + '晉' => '晉', + '㬙' => '㬙', + '暑' => '暑', + '㬈' => '㬈', + '㫤' => '㫤', + '冒' => '冒', + '冕' => '冕', + '最' => '最', + '暜' => '暜', + '肭' => '肭', + '䏙' => '䏙', + '朗' => '朗', + '望' => '望', + '朡' => '朡', + '杞' => '杞', + '杓' => '杓', + '𣏃' => '𣏃', + '㭉' => '㭉', + '柺' => '柺', + '枅' => '枅', + '桒' => '桒', + '梅' => '梅', + '𣑭' => '𣑭', + '梎' => '梎', + '栟' => '栟', + '椔' => '椔', + '㮝' => '㮝', + '楂' => '楂', + '榣' => '榣', + '槪' => '槪', + '檨' => '檨', + '𣚣' => '𣚣', + '櫛' => '櫛', + '㰘' => '㰘', + '次' => '次', + '𣢧' => '𣢧', + '歔' => '歔', + '㱎' => '㱎', + '歲' => '歲', + '殟' => '殟', + '殺' => '殺', + '殻' => '殻', + '𣪍' => '𣪍', + '𡴋' => '𡴋', + '𣫺' => '𣫺', + '汎' => '汎', + '𣲼' => '𣲼', + '沿' => '沿', + '泍' => '泍', + '汧' => '汧', + '洖' => '洖', + '派' => '派', + '海' => '海', + '流' => '流', + '浩' => '浩', + '浸' => '浸', + '涅' => '涅', + '𣴞' => '𣴞', + '洴' => '洴', + '港' => '港', + '湮' => '湮', + '㴳' => '㴳', + '滋' => '滋', + '滇' => '滇', + '𣻑' => '𣻑', + '淹' => '淹', + '潮' => '潮', + '𣽞' => '𣽞', + '𣾎' => '𣾎', + '濆' => '濆', + '瀹' => '瀹', + '瀞' => '瀞', + '瀛' => '瀛', + '㶖' => '㶖', + '灊' => '灊', + '災' => '災', + '灷' => '灷', + '炭' => '炭', + '𠔥' => '𠔥', + '煅' => '煅', + '𤉣' => '𤉣', + '熜' => '熜', + '𤎫' => '𤎫', + '爨' => '爨', + '爵' => '爵', + '牐' => '牐', + '𤘈' => '𤘈', + '犀' => '犀', + '犕' => '犕', + '𤜵' => '𤜵', + '𤠔' => '𤠔', + '獺' => '獺', + '王' => '王', + '㺬' => '㺬', + '玥' => '玥', + '㺸' => '㺸', + '㺸' => '㺸', + '瑇' => '瑇', + '瑜' => '瑜', + '瑱' => '瑱', + '璅' => '璅', + '瓊' => '瓊', + '㼛' => '㼛', + '甤' => '甤', + '𤰶' => '𤰶', + '甾' => '甾', + '𤲒' => '𤲒', + '異' => '異', + '𢆟' => '𢆟', + '瘐' => '瘐', + '𤾡' => '𤾡', + '𤾸' => '𤾸', + '𥁄' => '𥁄', + '㿼' => '㿼', + '䀈' => '䀈', + '直' => '直', + '𥃳' => '𥃳', + '𥃲' => '𥃲', + '𥄙' => '𥄙', + '𥄳' => '𥄳', + '眞' => '眞', + '真' => '真', + '真' => '真', + '睊' => '睊', + '䀹' => '䀹', + '瞋' => '瞋', + '䁆' => '䁆', + '䂖' => '䂖', + '𥐝' => '𥐝', + '硎' => '硎', + '碌' => '碌', + '磌' => '磌', + '䃣' => '䃣', + '𥘦' => '𥘦', + '祖' => '祖', + '𥚚' => '𥚚', + '𥛅' => '𥛅', + '福' => '福', + '秫' => '秫', + '䄯' => '䄯', + '穀' => '穀', + '穊' => '穊', + '穏' => '穏', + '𥥼' => '𥥼', + '𥪧' => '𥪧', + '𥪧' => '𥪧', + '竮' => '竮', + '䈂' => '䈂', + '𥮫' => '𥮫', + '篆' => '篆', + '築' => '築', + '䈧' => '䈧', + '𥲀' => '𥲀', + '糒' => '糒', + '䊠' => '䊠', + '糨' => '糨', + '糣' => '糣', + '紀' => '紀', + '𥾆' => '𥾆', + '絣' => '絣', + '䌁' => '䌁', + '緇' => '緇', + '縂' => '縂', + '繅' => '繅', + '䌴' => '䌴', + '𦈨' => '𦈨', + '𦉇' => '𦉇', + '䍙' => '䍙', + '𦋙' => '𦋙', + '罺' => '罺', + '𦌾' => '𦌾', + '羕' => '羕', + '翺' => '翺', + '者' => '者', + '𦓚' => '𦓚', + '𦔣' => '𦔣', + '聠' => '聠', + '𦖨' => '𦖨', + '聰' => '聰', + '𣍟' => '𣍟', + '䏕' => '䏕', + '育' => '育', + '脃' => '脃', + '䐋' => '䐋', + '脾' => '脾', + '媵' => '媵', + '𦞧' => '𦞧', + '𦞵' => '𦞵', + '𣎓' => '𣎓', + '𣎜' => '𣎜', + '舁' => '舁', + '舄' => '舄', + '辞' => '辞', + '䑫' => '䑫', + '芑' => '芑', + '芋' => '芋', + '芝' => '芝', + '劳' => '劳', + '花' => '花', + '芳' => '芳', + '芽' => '芽', + '苦' => '苦', + '𦬼' => '𦬼', + '若' => '若', + '茝' => '茝', + '荣' => '荣', + '莭' => '莭', + '茣' => '茣', + '莽' => '莽', + '菧' => '菧', + '著' => '著', + '荓' => '荓', + '菊' => '菊', + '菌' => '菌', + '菜' => '菜', + '𦰶' => '𦰶', + '𦵫' => '𦵫', + '𦳕' => '𦳕', + '䔫' => '䔫', + '蓱' => '蓱', + '蓳' => '蓳', + '蔖' => '蔖', + '𧏊' => '𧏊', + '蕤' => '蕤', + '𦼬' => '𦼬', + '䕝' => '䕝', + '䕡' => '䕡', + '𦾱' => '𦾱', + '𧃒' => '𧃒', + '䕫' => '䕫', + '虐' => '虐', + '虜' => '虜', + '虧' => '虧', + '虩' => '虩', + '蚩' => '蚩', + '蚈' => '蚈', + '蜎' => '蜎', + '蛢' => '蛢', + '蝹' => '蝹', + '蜨' => '蜨', + '蝫' => '蝫', + '螆' => '螆', + '䗗' => '䗗', + '蟡' => '蟡', + '蠁' => '蠁', + '䗹' => '䗹', + '衠' => '衠', + '衣' => '衣', + '𧙧' => '𧙧', + '裗' => '裗', + '裞' => '裞', + '䘵' => '䘵', + '裺' => '裺', + '㒻' => '㒻', + '𧢮' => '𧢮', + '𧥦' => '𧥦', + '䚾' => '䚾', + '䛇' => '䛇', + '誠' => '誠', + '諭' => '諭', + '變' => '變', + '豕' => '豕', + '𧲨' => '𧲨', + '貫' => '貫', + '賁' => '賁', + '贛' => '贛', + '起' => '起', + '𧼯' => '𧼯', + '𠠄' => '𠠄', + '跋' => '跋', + '趼' => '趼', + '跰' => '跰', + '𠣞' => '𠣞', + '軔' => '軔', + '輸' => '輸', + '𨗒' => '𨗒', + '𨗭' => '𨗭', + '邔' => '邔', + '郱' => '郱', + '鄑' => '鄑', + '𨜮' => '𨜮', + '鄛' => '鄛', + '鈸' => '鈸', + '鋗' => '鋗', + '鋘' => '鋘', + '鉼' => '鉼', + '鏹' => '鏹', + '鐕' => '鐕', + '𨯺' => '𨯺', + '開' => '開', + '䦕' => '䦕', + '閷' => '閷', + '𨵷' => '𨵷', + '䧦' => '䧦', + '雃' => '雃', + '嶲' => '嶲', + '霣' => '霣', + '𩅅' => '𩅅', + '𩈚' => '𩈚', + '䩮' => '䩮', + '䩶' => '䩶', + '韠' => '韠', + '𩐊' => '𩐊', + '䪲' => '䪲', + '𩒖' => '𩒖', + '頋' => '頋', + '頋' => '頋', + '頩' => '頩', + '𩖶' => '𩖶', + '飢' => '飢', + '䬳' => '䬳', + '餩' => '餩', + '馧' => '馧', + '駂' => '駂', + '駾' => '駾', + '䯎' => '䯎', + '𩬰' => '𩬰', + '鬒' => '鬒', + '鱀' => '鱀', + '鳽' => '鳽', + '䳎' => '䳎', + '䳭' => '䳭', + '鵧' => '鵧', + '𪃎' => '𪃎', + '䳸' => '䳸', + '𪄅' => '𪄅', + '𪈎' => '𪈎', + '𪊑' => '𪊑', + '麻' => '麻', + '䵖' => '䵖', + '黹' => '黹', + '黾' => '黾', + '鼅' => '鼅', + '鼏' => '鼏', + '鼖' => '鼖', + '鼻' => '鼻', + '𪘀' => '𪘀', +); diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/combiningClass.php b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/combiningClass.php new file mode 100644 index 00000000..ec90f36e --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/combiningClass.php @@ -0,0 +1,876 @@ + 230, + '́' => 230, + '̂' => 230, + '̃' => 230, + '̄' => 230, + '̅' => 230, + '̆' => 230, + '̇' => 230, + '̈' => 230, + '̉' => 230, + '̊' => 230, + '̋' => 230, + '̌' => 230, + '̍' => 230, + '̎' => 230, + '̏' => 230, + '̐' => 230, + '̑' => 230, + '̒' => 230, + '̓' => 230, + '̔' => 230, + '̕' => 232, + '̖' => 220, + '̗' => 220, + '̘' => 220, + '̙' => 220, + '̚' => 232, + '̛' => 216, + '̜' => 220, + '̝' => 220, + '̞' => 220, + '̟' => 220, + '̠' => 220, + '̡' => 202, + '̢' => 202, + '̣' => 220, + '̤' => 220, + '̥' => 220, + '̦' => 220, + '̧' => 202, + '̨' => 202, + '̩' => 220, + '̪' => 220, + '̫' => 220, + '̬' => 220, + '̭' => 220, + '̮' => 220, + '̯' => 220, + '̰' => 220, + '̱' => 220, + '̲' => 220, + '̳' => 220, + '̴' => 1, + '̵' => 1, + '̶' => 1, + '̷' => 1, + '̸' => 1, + '̹' => 220, + '̺' => 220, + '̻' => 220, + '̼' => 220, + '̽' => 230, + '̾' => 230, + '̿' => 230, + '̀' => 230, + '́' => 230, + '͂' => 230, + '̓' => 230, + '̈́' => 230, + 'ͅ' => 240, + '͆' => 230, + '͇' => 220, + '͈' => 220, + '͉' => 220, + '͊' => 230, + '͋' => 230, + '͌' => 230, + '͍' => 220, + '͎' => 220, + '͐' => 230, + '͑' => 230, + '͒' => 230, + '͓' => 220, + '͔' => 220, + '͕' => 220, + '͖' => 220, + '͗' => 230, + '͘' => 232, + '͙' => 220, + '͚' => 220, + '͛' => 230, + '͜' => 233, + '͝' => 234, + '͞' => 234, + '͟' => 233, + '͠' => 234, + '͡' => 234, + '͢' => 233, + 'ͣ' => 230, + 'ͤ' => 230, + 'ͥ' => 230, + 'ͦ' => 230, + 'ͧ' => 230, + 'ͨ' => 230, + 'ͩ' => 230, + 'ͪ' => 230, + 'ͫ' => 230, + 'ͬ' => 230, + 'ͭ' => 230, + 'ͮ' => 230, + 'ͯ' => 230, + '҃' => 230, + '҄' => 230, + '҅' => 230, + '҆' => 230, + '҇' => 230, + '֑' => 220, + '֒' => 230, + '֓' => 230, + '֔' => 230, + '֕' => 230, + '֖' => 220, + '֗' => 230, + '֘' => 230, + '֙' => 230, + '֚' => 222, + '֛' => 220, + '֜' => 230, + '֝' => 230, + '֞' => 230, + '֟' => 230, + '֠' => 230, + '֡' => 230, + '֢' => 220, + '֣' => 220, + '֤' => 220, + '֥' => 220, + '֦' => 220, + '֧' => 220, + '֨' => 230, + '֩' => 230, + '֪' => 220, + '֫' => 230, + '֬' => 230, + '֭' => 222, + '֮' => 228, + '֯' => 230, + 'ְ' => 10, + 'ֱ' => 11, + 'ֲ' => 12, + 'ֳ' => 13, + 'ִ' => 14, + 'ֵ' => 15, + 'ֶ' => 16, + 'ַ' => 17, + 'ָ' => 18, + 'ֹ' => 19, + 'ֺ' => 19, + 'ֻ' => 20, + 'ּ' => 21, + 'ֽ' => 22, + 'ֿ' => 23, + 'ׁ' => 24, + 'ׂ' => 25, + 'ׄ' => 230, + 'ׅ' => 220, + 'ׇ' => 18, + 'ؐ' => 230, + 'ؑ' => 230, + 'ؒ' => 230, + 'ؓ' => 230, + 'ؔ' => 230, + 'ؕ' => 230, + 'ؖ' => 230, + 'ؗ' => 230, + 'ؘ' => 30, + 'ؙ' => 31, + 'ؚ' => 32, + 'ً' => 27, + 'ٌ' => 28, + 'ٍ' => 29, + 'َ' => 30, + 'ُ' => 31, + 'ِ' => 32, + 'ّ' => 33, + 'ْ' => 34, + 'ٓ' => 230, + 'ٔ' => 230, + 'ٕ' => 220, + 'ٖ' => 220, + 'ٗ' => 230, + '٘' => 230, + 'ٙ' => 230, + 'ٚ' => 230, + 'ٛ' => 230, + 'ٜ' => 220, + 'ٝ' => 230, + 'ٞ' => 230, + 'ٟ' => 220, + 'ٰ' => 35, + 'ۖ' => 230, + 'ۗ' => 230, + 'ۘ' => 230, + 'ۙ' => 230, + 'ۚ' => 230, + 'ۛ' => 230, + 'ۜ' => 230, + '۟' => 230, + '۠' => 230, + 'ۡ' => 230, + 'ۢ' => 230, + 'ۣ' => 220, + 'ۤ' => 230, + 'ۧ' => 230, + 'ۨ' => 230, + '۪' => 220, + '۫' => 230, + '۬' => 230, + 'ۭ' => 220, + 'ܑ' => 36, + 'ܰ' => 230, + 'ܱ' => 220, + 'ܲ' => 230, + 'ܳ' => 230, + 'ܴ' => 220, + 'ܵ' => 230, + 'ܶ' => 230, + 'ܷ' => 220, + 'ܸ' => 220, + 'ܹ' => 220, + 'ܺ' => 230, + 'ܻ' => 220, + 'ܼ' => 220, + 'ܽ' => 230, + 'ܾ' => 220, + 'ܿ' => 230, + '݀' => 230, + '݁' => 230, + '݂' => 220, + '݃' => 230, + '݄' => 220, + '݅' => 230, + '݆' => 220, + '݇' => 230, + '݈' => 220, + '݉' => 230, + '݊' => 230, + '߫' => 230, + '߬' => 230, + '߭' => 230, + '߮' => 230, + '߯' => 230, + '߰' => 230, + '߱' => 230, + '߲' => 220, + '߳' => 230, + '߽' => 220, + 'ࠖ' => 230, + 'ࠗ' => 230, + '࠘' => 230, + '࠙' => 230, + 'ࠛ' => 230, + 'ࠜ' => 230, + 'ࠝ' => 230, + 'ࠞ' => 230, + 'ࠟ' => 230, + 'ࠠ' => 230, + 'ࠡ' => 230, + 'ࠢ' => 230, + 'ࠣ' => 230, + 'ࠥ' => 230, + 'ࠦ' => 230, + 'ࠧ' => 230, + 'ࠩ' => 230, + 'ࠪ' => 230, + 'ࠫ' => 230, + 'ࠬ' => 230, + '࠭' => 230, + '࡙' => 220, + '࡚' => 220, + '࡛' => 220, + '࣓' => 220, + 'ࣔ' => 230, + 'ࣕ' => 230, + 'ࣖ' => 230, + 'ࣗ' => 230, + 'ࣘ' => 230, + 'ࣙ' => 230, + 'ࣚ' => 230, + 'ࣛ' => 230, + 'ࣜ' => 230, + 'ࣝ' => 230, + 'ࣞ' => 230, + 'ࣟ' => 230, + '࣠' => 230, + '࣡' => 230, + 'ࣣ' => 220, + 'ࣤ' => 230, + 'ࣥ' => 230, + 'ࣦ' => 220, + 'ࣧ' => 230, + 'ࣨ' => 230, + 'ࣩ' => 220, + '࣪' => 230, + '࣫' => 230, + '࣬' => 230, + '࣭' => 220, + '࣮' => 220, + '࣯' => 220, + 'ࣰ' => 27, + 'ࣱ' => 28, + 'ࣲ' => 29, + 'ࣳ' => 230, + 'ࣴ' => 230, + 'ࣵ' => 230, + 'ࣶ' => 220, + 'ࣷ' => 230, + 'ࣸ' => 230, + 'ࣹ' => 220, + 'ࣺ' => 220, + 'ࣻ' => 230, + 'ࣼ' => 230, + 'ࣽ' => 230, + 'ࣾ' => 230, + 'ࣿ' => 230, + '़' => 7, + '्' => 9, + '॑' => 230, + '॒' => 220, + '॓' => 230, + '॔' => 230, + '়' => 7, + '্' => 9, + '৾' => 230, + '਼' => 7, + '੍' => 9, + '઼' => 7, + '્' => 9, + '଼' => 7, + '୍' => 9, + '்' => 9, + '్' => 9, + 'ౕ' => 84, + 'ౖ' => 91, + '಼' => 7, + '್' => 9, + '഻' => 9, + '഼' => 9, + '്' => 9, + '්' => 9, + 'ุ' => 103, + 'ู' => 103, + 'ฺ' => 9, + '่' => 107, + '้' => 107, + '๊' => 107, + '๋' => 107, + 'ຸ' => 118, + 'ູ' => 118, + '຺' => 9, + '່' => 122, + '້' => 122, + '໊' => 122, + '໋' => 122, + '༘' => 220, + '༙' => 220, + '༵' => 220, + '༷' => 220, + '༹' => 216, + 'ཱ' => 129, + 'ི' => 130, + 'ུ' => 132, + 'ེ' => 130, + 'ཻ' => 130, + 'ོ' => 130, + 'ཽ' => 130, + 'ྀ' => 130, + 'ྂ' => 230, + 'ྃ' => 230, + '྄' => 9, + '྆' => 230, + '྇' => 230, + '࿆' => 220, + '့' => 7, + '္' => 9, + '်' => 9, + 'ႍ' => 220, + '፝' => 230, + '፞' => 230, + '፟' => 230, + '᜔' => 9, + '᜴' => 9, + '្' => 9, + '៝' => 230, + 'ᢩ' => 228, + '᤹' => 222, + '᤺' => 230, + '᤻' => 220, + 'ᨗ' => 230, + 'ᨘ' => 220, + '᩠' => 9, + '᩵' => 230, + '᩶' => 230, + '᩷' => 230, + '᩸' => 230, + '᩹' => 230, + '᩺' => 230, + '᩻' => 230, + '᩼' => 230, + '᩿' => 220, + '᪰' => 230, + '᪱' => 230, + '᪲' => 230, + '᪳' => 230, + '᪴' => 230, + '᪵' => 220, + '᪶' => 220, + '᪷' => 220, + '᪸' => 220, + '᪹' => 220, + '᪺' => 220, + '᪻' => 230, + '᪼' => 230, + '᪽' => 220, + 'ᪿ' => 220, + 'ᫀ' => 220, + '᬴' => 7, + '᭄' => 9, + '᭫' => 230, + '᭬' => 220, + '᭭' => 230, + '᭮' => 230, + '᭯' => 230, + '᭰' => 230, + '᭱' => 230, + '᭲' => 230, + '᭳' => 230, + '᮪' => 9, + '᮫' => 9, + '᯦' => 7, + '᯲' => 9, + '᯳' => 9, + '᰷' => 7, + '᳐' => 230, + '᳑' => 230, + '᳒' => 230, + '᳔' => 1, + '᳕' => 220, + '᳖' => 220, + '᳗' => 220, + '᳘' => 220, + '᳙' => 220, + '᳚' => 230, + '᳛' => 230, + '᳜' => 220, + '᳝' => 220, + '᳞' => 220, + '᳟' => 220, + '᳠' => 230, + '᳢' => 1, + '᳣' => 1, + '᳤' => 1, + '᳥' => 1, + '᳦' => 1, + '᳧' => 1, + '᳨' => 1, + '᳭' => 220, + '᳴' => 230, + '᳸' => 230, + '᳹' => 230, + '᷀' => 230, + '᷁' => 230, + '᷂' => 220, + '᷃' => 230, + '᷄' => 230, + '᷅' => 230, + '᷆' => 230, + '᷇' => 230, + '᷈' => 230, + '᷉' => 230, + '᷊' => 220, + '᷋' => 230, + '᷌' => 230, + '᷍' => 234, + '᷎' => 214, + '᷏' => 220, + '᷐' => 202, + '᷑' => 230, + '᷒' => 230, + 'ᷓ' => 230, + 'ᷔ' => 230, + 'ᷕ' => 230, + 'ᷖ' => 230, + 'ᷗ' => 230, + 'ᷘ' => 230, + 'ᷙ' => 230, + 'ᷚ' => 230, + 'ᷛ' => 230, + 'ᷜ' => 230, + 'ᷝ' => 230, + 'ᷞ' => 230, + 'ᷟ' => 230, + 'ᷠ' => 230, + 'ᷡ' => 230, + 'ᷢ' => 230, + 'ᷣ' => 230, + 'ᷤ' => 230, + 'ᷥ' => 230, + 'ᷦ' => 230, + 'ᷧ' => 230, + 'ᷨ' => 230, + 'ᷩ' => 230, + 'ᷪ' => 230, + 'ᷫ' => 230, + 'ᷬ' => 230, + 'ᷭ' => 230, + 'ᷮ' => 230, + 'ᷯ' => 230, + 'ᷰ' => 230, + 'ᷱ' => 230, + 'ᷲ' => 230, + 'ᷳ' => 230, + 'ᷴ' => 230, + '᷵' => 230, + '᷶' => 232, + '᷷' => 228, + '᷸' => 228, + '᷹' => 220, + '᷻' => 230, + '᷼' => 233, + '᷽' => 220, + '᷾' => 230, + '᷿' => 220, + '⃐' => 230, + '⃑' => 230, + '⃒' => 1, + '⃓' => 1, + '⃔' => 230, + '⃕' => 230, + '⃖' => 230, + '⃗' => 230, + '⃘' => 1, + '⃙' => 1, + '⃚' => 1, + '⃛' => 230, + '⃜' => 230, + '⃡' => 230, + '⃥' => 1, + '⃦' => 1, + '⃧' => 230, + '⃨' => 220, + '⃩' => 230, + '⃪' => 1, + '⃫' => 1, + '⃬' => 220, + '⃭' => 220, + '⃮' => 220, + '⃯' => 220, + '⃰' => 230, + '⳯' => 230, + '⳰' => 230, + '⳱' => 230, + '⵿' => 9, + 'ⷠ' => 230, + 'ⷡ' => 230, + 'ⷢ' => 230, + 'ⷣ' => 230, + 'ⷤ' => 230, + 'ⷥ' => 230, + 'ⷦ' => 230, + 'ⷧ' => 230, + 'ⷨ' => 230, + 'ⷩ' => 230, + 'ⷪ' => 230, + 'ⷫ' => 230, + 'ⷬ' => 230, + 'ⷭ' => 230, + 'ⷮ' => 230, + 'ⷯ' => 230, + 'ⷰ' => 230, + 'ⷱ' => 230, + 'ⷲ' => 230, + 'ⷳ' => 230, + 'ⷴ' => 230, + 'ⷵ' => 230, + 'ⷶ' => 230, + 'ⷷ' => 230, + 'ⷸ' => 230, + 'ⷹ' => 230, + 'ⷺ' => 230, + 'ⷻ' => 230, + 'ⷼ' => 230, + 'ⷽ' => 230, + 'ⷾ' => 230, + 'ⷿ' => 230, + '〪' => 218, + '〫' => 228, + '〬' => 232, + '〭' => 222, + '〮' => 224, + '〯' => 224, + '゙' => 8, + '゚' => 8, + '꙯' => 230, + 'ꙴ' => 230, + 'ꙵ' => 230, + 'ꙶ' => 230, + 'ꙷ' => 230, + 'ꙸ' => 230, + 'ꙹ' => 230, + 'ꙺ' => 230, + 'ꙻ' => 230, + '꙼' => 230, + '꙽' => 230, + 'ꚞ' => 230, + 'ꚟ' => 230, + '꛰' => 230, + '꛱' => 230, + '꠆' => 9, + '꠬' => 9, + '꣄' => 9, + '꣠' => 230, + '꣡' => 230, + '꣢' => 230, + '꣣' => 230, + '꣤' => 230, + '꣥' => 230, + '꣦' => 230, + '꣧' => 230, + '꣨' => 230, + '꣩' => 230, + '꣪' => 230, + '꣫' => 230, + '꣬' => 230, + '꣭' => 230, + '꣮' => 230, + '꣯' => 230, + '꣰' => 230, + '꣱' => 230, + '꤫' => 220, + '꤬' => 220, + '꤭' => 220, + '꥓' => 9, + '꦳' => 7, + '꧀' => 9, + 'ꪰ' => 230, + 'ꪲ' => 230, + 'ꪳ' => 230, + 'ꪴ' => 220, + 'ꪷ' => 230, + 'ꪸ' => 230, + 'ꪾ' => 230, + '꪿' => 230, + '꫁' => 230, + '꫶' => 9, + '꯭' => 9, + 'ﬞ' => 26, + '︠' => 230, + '︡' => 230, + '︢' => 230, + '︣' => 230, + '︤' => 230, + '︥' => 230, + '︦' => 230, + '︧' => 220, + '︨' => 220, + '︩' => 220, + '︪' => 220, + '︫' => 220, + '︬' => 220, + '︭' => 220, + '︮' => 230, + '︯' => 230, + '𐇽' => 220, + '𐋠' => 220, + '𐍶' => 230, + '𐍷' => 230, + '𐍸' => 230, + '𐍹' => 230, + '𐍺' => 230, + '𐨍' => 220, + '𐨏' => 230, + '𐨸' => 230, + '𐨹' => 1, + '𐨺' => 220, + '𐨿' => 9, + '𐫥' => 230, + '𐫦' => 220, + '𐴤' => 230, + '𐴥' => 230, + '𐴦' => 230, + '𐴧' => 230, + '𐺫' => 230, + '𐺬' => 230, + '𐽆' => 220, + '𐽇' => 220, + '𐽈' => 230, + '𐽉' => 230, + '𐽊' => 230, + '𐽋' => 220, + '𐽌' => 230, + '𐽍' => 220, + '𐽎' => 220, + '𐽏' => 220, + '𐽐' => 220, + '𑁆' => 9, + '𑁿' => 9, + '𑂹' => 9, + '𑂺' => 7, + '𑄀' => 230, + '𑄁' => 230, + '𑄂' => 230, + '𑄳' => 9, + '𑄴' => 9, + '𑅳' => 7, + '𑇀' => 9, + '𑇊' => 7, + '𑈵' => 9, + '𑈶' => 7, + '𑋩' => 7, + '𑋪' => 9, + '𑌻' => 7, + '𑌼' => 7, + '𑍍' => 9, + '𑍦' => 230, + '𑍧' => 230, + '𑍨' => 230, + '𑍩' => 230, + '𑍪' => 230, + '𑍫' => 230, + '𑍬' => 230, + '𑍰' => 230, + '𑍱' => 230, + '𑍲' => 230, + '𑍳' => 230, + '𑍴' => 230, + '𑑂' => 9, + '𑑆' => 7, + '𑑞' => 230, + '𑓂' => 9, + '𑓃' => 7, + '𑖿' => 9, + '𑗀' => 7, + '𑘿' => 9, + '𑚶' => 9, + '𑚷' => 7, + '𑜫' => 9, + '𑠹' => 9, + '𑠺' => 7, + '𑤽' => 9, + '𑤾' => 9, + '𑥃' => 7, + '𑧠' => 9, + '𑨴' => 9, + '𑩇' => 9, + '𑪙' => 9, + '𑰿' => 9, + '𑵂' => 7, + '𑵄' => 9, + '𑵅' => 9, + '𑶗' => 9, + '𖫰' => 1, + '𖫱' => 1, + '𖫲' => 1, + '𖫳' => 1, + '𖫴' => 1, + '𖬰' => 230, + '𖬱' => 230, + '𖬲' => 230, + '𖬳' => 230, + '𖬴' => 230, + '𖬵' => 230, + '𖬶' => 230, + '𖿰' => 6, + '𖿱' => 6, + '𛲞' => 1, + '𝅥' => 216, + '𝅦' => 216, + '𝅧' => 1, + '𝅨' => 1, + '𝅩' => 1, + '𝅭' => 226, + '𝅮' => 216, + '𝅯' => 216, + '𝅰' => 216, + '𝅱' => 216, + '𝅲' => 216, + '𝅻' => 220, + '𝅼' => 220, + '𝅽' => 220, + '𝅾' => 220, + '𝅿' => 220, + '𝆀' => 220, + '𝆁' => 220, + '𝆂' => 220, + '𝆅' => 230, + '𝆆' => 230, + '𝆇' => 230, + '𝆈' => 230, + '𝆉' => 230, + '𝆊' => 220, + '𝆋' => 220, + '𝆪' => 230, + '𝆫' => 230, + '𝆬' => 230, + '𝆭' => 230, + '𝉂' => 230, + '𝉃' => 230, + '𝉄' => 230, + '𞀀' => 230, + '𞀁' => 230, + '𞀂' => 230, + '𞀃' => 230, + '𞀄' => 230, + '𞀅' => 230, + '𞀆' => 230, + '𞀈' => 230, + '𞀉' => 230, + '𞀊' => 230, + '𞀋' => 230, + '𞀌' => 230, + '𞀍' => 230, + '𞀎' => 230, + '𞀏' => 230, + '𞀐' => 230, + '𞀑' => 230, + '𞀒' => 230, + '𞀓' => 230, + '𞀔' => 230, + '𞀕' => 230, + '𞀖' => 230, + '𞀗' => 230, + '𞀘' => 230, + '𞀛' => 230, + '𞀜' => 230, + '𞀝' => 230, + '𞀞' => 230, + '𞀟' => 230, + '𞀠' => 230, + '𞀡' => 230, + '𞀣' => 230, + '𞀤' => 230, + '𞀦' => 230, + '𞀧' => 230, + '𞀨' => 230, + '𞀩' => 230, + '𞀪' => 230, + '𞄰' => 230, + '𞄱' => 230, + '𞄲' => 230, + '𞄳' => 230, + '𞄴' => 230, + '𞄵' => 230, + '𞄶' => 230, + '𞋬' => 230, + '𞋭' => 230, + '𞋮' => 230, + '𞋯' => 230, + '𞣐' => 220, + '𞣑' => 220, + '𞣒' => 220, + '𞣓' => 220, + '𞣔' => 220, + '𞣕' => 220, + '𞣖' => 220, + '𞥄' => 230, + '𞥅' => 230, + '𞥆' => 230, + '𞥇' => 230, + '𞥈' => 230, + '𞥉' => 230, + '𞥊' => 7, +); diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/compatibilityDecomposition.php b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/compatibilityDecomposition.php new file mode 100644 index 00000000..15749028 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/Resources/unidata/compatibilityDecomposition.php @@ -0,0 +1,3695 @@ + ' ', + '¨' => ' ̈', + 'ª' => 'a', + '¯' => ' ̄', + '²' => '2', + '³' => '3', + '´' => ' ́', + 'µ' => 'μ', + '¸' => ' ̧', + '¹' => '1', + 'º' => 'o', + '¼' => '1⁄4', + '½' => '1⁄2', + '¾' => '3⁄4', + 'IJ' => 'IJ', + 'ij' => 'ij', + 'Ŀ' => 'L·', + 'ŀ' => 'l·', + 'ʼn' => 'ʼn', + 'ſ' => 's', + 'DŽ' => 'DŽ', + 'Dž' => 'Dž', + 'dž' => 'dž', + 'LJ' => 'LJ', + 'Lj' => 'Lj', + 'lj' => 'lj', + 'NJ' => 'NJ', + 'Nj' => 'Nj', + 'nj' => 'nj', + 'DZ' => 'DZ', + 'Dz' => 'Dz', + 'dz' => 'dz', + 'ʰ' => 'h', + 'ʱ' => 'ɦ', + 'ʲ' => 'j', + 'ʳ' => 'r', + 'ʴ' => 'ɹ', + 'ʵ' => 'ɻ', + 'ʶ' => 'ʁ', + 'ʷ' => 'w', + 'ʸ' => 'y', + '˘' => ' ̆', + '˙' => ' ̇', + '˚' => ' ̊', + '˛' => ' ̨', + '˜' => ' ̃', + '˝' => ' ̋', + 'ˠ' => 'ɣ', + 'ˡ' => 'l', + 'ˢ' => 's', + 'ˣ' => 'x', + 'ˤ' => 'ʕ', + 'ͺ' => ' ͅ', + '΄' => ' ́', + '΅' => ' ̈́', + 'ϐ' => 'β', + 'ϑ' => 'θ', + 'ϒ' => 'Υ', + 'ϓ' => 'Ύ', + 'ϔ' => 'Ϋ', + 'ϕ' => 'φ', + 'ϖ' => 'π', + 'ϰ' => 'κ', + 'ϱ' => 'ρ', + 'ϲ' => 'ς', + 'ϴ' => 'Θ', + 'ϵ' => 'ε', + 'Ϲ' => 'Σ', + 'և' => 'եւ', + 'ٵ' => 'اٴ', + 'ٶ' => 'وٴ', + 'ٷ' => 'ۇٴ', + 'ٸ' => 'يٴ', + 'ำ' => 'ํา', + 'ຳ' => 'ໍາ', + 'ໜ' => 'ຫນ', + 'ໝ' => 'ຫມ', + '༌' => '་', + 'ཷ' => 'ྲཱྀ', + 'ཹ' => 'ླཱྀ', + 'ჼ' => 'ნ', + 'ᴬ' => 'A', + 'ᴭ' => 'Æ', + 'ᴮ' => 'B', + 'ᴰ' => 'D', + 'ᴱ' => 'E', + 'ᴲ' => 'Ǝ', + 'ᴳ' => 'G', + 'ᴴ' => 'H', + 'ᴵ' => 'I', + 'ᴶ' => 'J', + 'ᴷ' => 'K', + 'ᴸ' => 'L', + 'ᴹ' => 'M', + 'ᴺ' => 'N', + 'ᴼ' => 'O', + 'ᴽ' => 'Ȣ', + 'ᴾ' => 'P', + 'ᴿ' => 'R', + 'ᵀ' => 'T', + 'ᵁ' => 'U', + 'ᵂ' => 'W', + 'ᵃ' => 'a', + 'ᵄ' => 'ɐ', + 'ᵅ' => 'ɑ', + 'ᵆ' => 'ᴂ', + 'ᵇ' => 'b', + 'ᵈ' => 'd', + 'ᵉ' => 'e', + 'ᵊ' => 'ə', + 'ᵋ' => 'ɛ', + 'ᵌ' => 'ɜ', + 'ᵍ' => 'g', + 'ᵏ' => 'k', + 'ᵐ' => 'm', + 'ᵑ' => 'ŋ', + 'ᵒ' => 'o', + 'ᵓ' => 'ɔ', + 'ᵔ' => 'ᴖ', + 'ᵕ' => 'ᴗ', + 'ᵖ' => 'p', + 'ᵗ' => 't', + 'ᵘ' => 'u', + 'ᵙ' => 'ᴝ', + 'ᵚ' => 'ɯ', + 'ᵛ' => 'v', + 'ᵜ' => 'ᴥ', + 'ᵝ' => 'β', + 'ᵞ' => 'γ', + 'ᵟ' => 'δ', + 'ᵠ' => 'φ', + 'ᵡ' => 'χ', + 'ᵢ' => 'i', + 'ᵣ' => 'r', + 'ᵤ' => 'u', + 'ᵥ' => 'v', + 'ᵦ' => 'β', + 'ᵧ' => 'γ', + 'ᵨ' => 'ρ', + 'ᵩ' => 'φ', + 'ᵪ' => 'χ', + 'ᵸ' => 'н', + 'ᶛ' => 'ɒ', + 'ᶜ' => 'c', + 'ᶝ' => 'ɕ', + 'ᶞ' => 'ð', + 'ᶟ' => 'ɜ', + 'ᶠ' => 'f', + 'ᶡ' => 'ɟ', + 'ᶢ' => 'ɡ', + 'ᶣ' => 'ɥ', + 'ᶤ' => 'ɨ', + 'ᶥ' => 'ɩ', + 'ᶦ' => 'ɪ', + 'ᶧ' => 'ᵻ', + 'ᶨ' => 'ʝ', + 'ᶩ' => 'ɭ', + 'ᶪ' => 'ᶅ', + 'ᶫ' => 'ʟ', + 'ᶬ' => 'ɱ', + 'ᶭ' => 'ɰ', + 'ᶮ' => 'ɲ', + 'ᶯ' => 'ɳ', + 'ᶰ' => 'ɴ', + 'ᶱ' => 'ɵ', + 'ᶲ' => 'ɸ', + 'ᶳ' => 'ʂ', + 'ᶴ' => 'ʃ', + 'ᶵ' => 'ƫ', + 'ᶶ' => 'ʉ', + 'ᶷ' => 'ʊ', + 'ᶸ' => 'ᴜ', + 'ᶹ' => 'ʋ', + 'ᶺ' => 'ʌ', + 'ᶻ' => 'z', + 'ᶼ' => 'ʐ', + 'ᶽ' => 'ʑ', + 'ᶾ' => 'ʒ', + 'ᶿ' => 'θ', + 'ẚ' => 'aʾ', + 'ẛ' => 'ṡ', + '᾽' => ' ̓', + '᾿' => ' ̓', + '῀' => ' ͂', + '῁' => ' ̈͂', + '῍' => ' ̓̀', + '῎' => ' ̓́', + '῏' => ' ̓͂', + '῝' => ' ̔̀', + '῞' => ' ̔́', + '῟' => ' ̔͂', + '῭' => ' ̈̀', + '΅' => ' ̈́', + '´' => ' ́', + '῾' => ' ̔', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + '‑' => '‐', + '‗' => ' ̳', + '․' => '.', + '‥' => '..', + '…' => '...', + ' ' => ' ', + '″' => '′′', + '‴' => '′′′', + '‶' => '‵‵', + '‷' => '‵‵‵', + '‼' => '!!', + '‾' => ' ̅', + '⁇' => '??', + '⁈' => '?!', + '⁉' => '!?', + '⁗' => '′′′′', + ' ' => ' ', + '⁰' => '0', + 'ⁱ' => 'i', + '⁴' => '4', + '⁵' => '5', + '⁶' => '6', + '⁷' => '7', + '⁸' => '8', + '⁹' => '9', + '⁺' => '+', + '⁻' => '−', + '⁼' => '=', + '⁽' => '(', + '⁾' => ')', + 'ⁿ' => 'n', + '₀' => '0', + '₁' => '1', + '₂' => '2', + '₃' => '3', + '₄' => '4', + '₅' => '5', + '₆' => '6', + '₇' => '7', + '₈' => '8', + '₉' => '9', + '₊' => '+', + '₋' => '−', + '₌' => '=', + '₍' => '(', + '₎' => ')', + 'ₐ' => 'a', + 'ₑ' => 'e', + 'ₒ' => 'o', + 'ₓ' => 'x', + 'ₔ' => 'ə', + 'ₕ' => 'h', + 'ₖ' => 'k', + 'ₗ' => 'l', + 'ₘ' => 'm', + 'ₙ' => 'n', + 'ₚ' => 'p', + 'ₛ' => 's', + 'ₜ' => 't', + '₨' => 'Rs', + '℀' => 'a/c', + '℁' => 'a/s', + 'ℂ' => 'C', + '℃' => '°C', + '℅' => 'c/o', + '℆' => 'c/u', + 'ℇ' => 'Ɛ', + '℉' => '°F', + 'ℊ' => 'g', + 'ℋ' => 'H', + 'ℌ' => 'H', + 'ℍ' => 'H', + 'ℎ' => 'h', + 'ℏ' => 'ħ', + 'ℐ' => 'I', + 'ℑ' => 'I', + 'ℒ' => 'L', + 'ℓ' => 'l', + 'ℕ' => 'N', + '№' => 'No', + 'ℙ' => 'P', + 'ℚ' => 'Q', + 'ℛ' => 'R', + 'ℜ' => 'R', + 'ℝ' => 'R', + '℠' => 'SM', + '℡' => 'TEL', + '™' => 'TM', + 'ℤ' => 'Z', + 'ℨ' => 'Z', + 'ℬ' => 'B', + 'ℭ' => 'C', + 'ℯ' => 'e', + 'ℰ' => 'E', + 'ℱ' => 'F', + 'ℳ' => 'M', + 'ℴ' => 'o', + 'ℵ' => 'א', + 'ℶ' => 'ב', + 'ℷ' => 'ג', + 'ℸ' => 'ד', + 'ℹ' => 'i', + '℻' => 'FAX', + 'ℼ' => 'π', + 'ℽ' => 'γ', + 'ℾ' => 'Γ', + 'ℿ' => 'Π', + '⅀' => '∑', + 'ⅅ' => 'D', + 'ⅆ' => 'd', + 'ⅇ' => 'e', + 'ⅈ' => 'i', + 'ⅉ' => 'j', + '⅐' => '1⁄7', + '⅑' => '1⁄9', + '⅒' => '1⁄10', + '⅓' => '1⁄3', + '⅔' => '2⁄3', + '⅕' => '1⁄5', + '⅖' => '2⁄5', + '⅗' => '3⁄5', + '⅘' => '4⁄5', + '⅙' => '1⁄6', + '⅚' => '5⁄6', + '⅛' => '1⁄8', + '⅜' => '3⁄8', + '⅝' => '5⁄8', + '⅞' => '7⁄8', + '⅟' => '1⁄', + 'Ⅰ' => 'I', + 'Ⅱ' => 'II', + 'Ⅲ' => 'III', + 'Ⅳ' => 'IV', + 'Ⅴ' => 'V', + 'Ⅵ' => 'VI', + 'Ⅶ' => 'VII', + 'Ⅷ' => 'VIII', + 'Ⅸ' => 'IX', + 'Ⅹ' => 'X', + 'Ⅺ' => 'XI', + 'Ⅻ' => 'XII', + 'Ⅼ' => 'L', + 'Ⅽ' => 'C', + 'Ⅾ' => 'D', + 'Ⅿ' => 'M', + 'ⅰ' => 'i', + 'ⅱ' => 'ii', + 'ⅲ' => 'iii', + 'ⅳ' => 'iv', + 'ⅴ' => 'v', + 'ⅵ' => 'vi', + 'ⅶ' => 'vii', + 'ⅷ' => 'viii', + 'ⅸ' => 'ix', + 'ⅹ' => 'x', + 'ⅺ' => 'xi', + 'ⅻ' => 'xii', + 'ⅼ' => 'l', + 'ⅽ' => 'c', + 'ⅾ' => 'd', + 'ⅿ' => 'm', + '↉' => '0⁄3', + '∬' => '∫∫', + '∭' => '∫∫∫', + '∯' => '∮∮', + '∰' => '∮∮∮', + '①' => '1', + '②' => '2', + '③' => '3', + '④' => '4', + '⑤' => '5', + '⑥' => '6', + '⑦' => '7', + '⑧' => '8', + '⑨' => '9', + '⑩' => '10', + '⑪' => '11', + '⑫' => '12', + '⑬' => '13', + '⑭' => '14', + '⑮' => '15', + '⑯' => '16', + '⑰' => '17', + '⑱' => '18', + '⑲' => '19', + '⑳' => '20', + '⑴' => '(1)', + '⑵' => '(2)', + '⑶' => '(3)', + '⑷' => '(4)', + '⑸' => '(5)', + '⑹' => '(6)', + '⑺' => '(7)', + '⑻' => '(8)', + '⑼' => '(9)', + '⑽' => '(10)', + '⑾' => '(11)', + '⑿' => '(12)', + '⒀' => '(13)', + '⒁' => '(14)', + '⒂' => '(15)', + '⒃' => '(16)', + '⒄' => '(17)', + '⒅' => '(18)', + '⒆' => '(19)', + '⒇' => '(20)', + '⒈' => '1.', + '⒉' => '2.', + '⒊' => '3.', + '⒋' => '4.', + '⒌' => '5.', + '⒍' => '6.', + '⒎' => '7.', + '⒏' => '8.', + '⒐' => '9.', + '⒑' => '10.', + '⒒' => '11.', + '⒓' => '12.', + '⒔' => '13.', + '⒕' => '14.', + '⒖' => '15.', + '⒗' => '16.', + '⒘' => '17.', + '⒙' => '18.', + '⒚' => '19.', + '⒛' => '20.', + '⒜' => '(a)', + '⒝' => '(b)', + '⒞' => '(c)', + '⒟' => '(d)', + '⒠' => '(e)', + '⒡' => '(f)', + '⒢' => '(g)', + '⒣' => '(h)', + '⒤' => '(i)', + '⒥' => '(j)', + '⒦' => '(k)', + '⒧' => '(l)', + '⒨' => '(m)', + '⒩' => '(n)', + '⒪' => '(o)', + '⒫' => '(p)', + '⒬' => '(q)', + '⒭' => '(r)', + '⒮' => '(s)', + '⒯' => '(t)', + '⒰' => '(u)', + '⒱' => '(v)', + '⒲' => '(w)', + '⒳' => '(x)', + '⒴' => '(y)', + '⒵' => '(z)', + 'Ⓐ' => 'A', + 'Ⓑ' => 'B', + 'Ⓒ' => 'C', + 'Ⓓ' => 'D', + 'Ⓔ' => 'E', + 'Ⓕ' => 'F', + 'Ⓖ' => 'G', + 'Ⓗ' => 'H', + 'Ⓘ' => 'I', + 'Ⓙ' => 'J', + 'Ⓚ' => 'K', + 'Ⓛ' => 'L', + 'Ⓜ' => 'M', + 'Ⓝ' => 'N', + 'Ⓞ' => 'O', + 'Ⓟ' => 'P', + 'Ⓠ' => 'Q', + 'Ⓡ' => 'R', + 'Ⓢ' => 'S', + 'Ⓣ' => 'T', + 'Ⓤ' => 'U', + 'Ⓥ' => 'V', + 'Ⓦ' => 'W', + 'Ⓧ' => 'X', + 'Ⓨ' => 'Y', + 'Ⓩ' => 'Z', + 'ⓐ' => 'a', + 'ⓑ' => 'b', + 'ⓒ' => 'c', + 'ⓓ' => 'd', + 'ⓔ' => 'e', + 'ⓕ' => 'f', + 'ⓖ' => 'g', + 'ⓗ' => 'h', + 'ⓘ' => 'i', + 'ⓙ' => 'j', + 'ⓚ' => 'k', + 'ⓛ' => 'l', + 'ⓜ' => 'm', + 'ⓝ' => 'n', + 'ⓞ' => 'o', + 'ⓟ' => 'p', + 'ⓠ' => 'q', + 'ⓡ' => 'r', + 'ⓢ' => 's', + 'ⓣ' => 't', + 'ⓤ' => 'u', + 'ⓥ' => 'v', + 'ⓦ' => 'w', + 'ⓧ' => 'x', + 'ⓨ' => 'y', + 'ⓩ' => 'z', + '⓪' => '0', + '⨌' => '∫∫∫∫', + '⩴' => '::=', + '⩵' => '==', + '⩶' => '===', + 'ⱼ' => 'j', + 'ⱽ' => 'V', + 'ⵯ' => 'ⵡ', + '⺟' => '母', + '⻳' => '龟', + '⼀' => '一', + '⼁' => '丨', + '⼂' => '丶', + '⼃' => '丿', + '⼄' => '乙', + '⼅' => '亅', + '⼆' => '二', + '⼇' => '亠', + '⼈' => '人', + '⼉' => '儿', + '⼊' => '入', + '⼋' => '八', + '⼌' => '冂', + '⼍' => '冖', + '⼎' => '冫', + '⼏' => '几', + '⼐' => '凵', + '⼑' => '刀', + '⼒' => '力', + '⼓' => '勹', + '⼔' => '匕', + '⼕' => '匚', + '⼖' => '匸', + '⼗' => '十', + '⼘' => '卜', + '⼙' => '卩', + '⼚' => '厂', + '⼛' => '厶', + '⼜' => '又', + '⼝' => '口', + '⼞' => '囗', + '⼟' => '土', + '⼠' => '士', + '⼡' => '夂', + '⼢' => '夊', + '⼣' => '夕', + '⼤' => '大', + '⼥' => '女', + '⼦' => '子', + '⼧' => '宀', + '⼨' => '寸', + '⼩' => '小', + '⼪' => '尢', + '⼫' => '尸', + '⼬' => '屮', + '⼭' => '山', + '⼮' => '巛', + '⼯' => '工', + '⼰' => '己', + '⼱' => '巾', + '⼲' => '干', + '⼳' => '幺', + '⼴' => '广', + '⼵' => '廴', + '⼶' => '廾', + '⼷' => '弋', + '⼸' => '弓', + '⼹' => '彐', + '⼺' => '彡', + '⼻' => '彳', + '⼼' => '心', + '⼽' => '戈', + '⼾' => '戶', + '⼿' => '手', + '⽀' => '支', + '⽁' => '攴', + '⽂' => '文', + '⽃' => '斗', + '⽄' => '斤', + '⽅' => '方', + '⽆' => '无', + '⽇' => '日', + '⽈' => '曰', + '⽉' => '月', + '⽊' => '木', + '⽋' => '欠', + '⽌' => '止', + '⽍' => '歹', + '⽎' => '殳', + '⽏' => '毋', + '⽐' => '比', + '⽑' => '毛', + '⽒' => '氏', + '⽓' => '气', + '⽔' => '水', + '⽕' => '火', + '⽖' => '爪', + '⽗' => '父', + '⽘' => '爻', + '⽙' => '爿', + '⽚' => '片', + '⽛' => '牙', + '⽜' => '牛', + '⽝' => '犬', + '⽞' => '玄', + '⽟' => '玉', + '⽠' => '瓜', + '⽡' => '瓦', + '⽢' => '甘', + '⽣' => '生', + '⽤' => '用', + '⽥' => '田', + '⽦' => '疋', + '⽧' => '疒', + '⽨' => '癶', + '⽩' => '白', + '⽪' => '皮', + '⽫' => '皿', + '⽬' => '目', + '⽭' => '矛', + '⽮' => '矢', + '⽯' => '石', + '⽰' => '示', + '⽱' => '禸', + '⽲' => '禾', + '⽳' => '穴', + '⽴' => '立', + '⽵' => '竹', + '⽶' => '米', + '⽷' => '糸', + '⽸' => '缶', + '⽹' => '网', + '⽺' => '羊', + '⽻' => '羽', + '⽼' => '老', + '⽽' => '而', + '⽾' => '耒', + '⽿' => '耳', + '⾀' => '聿', + '⾁' => '肉', + '⾂' => '臣', + '⾃' => '自', + '⾄' => '至', + '⾅' => '臼', + '⾆' => '舌', + '⾇' => '舛', + '⾈' => '舟', + '⾉' => '艮', + '⾊' => '色', + '⾋' => '艸', + '⾌' => '虍', + '⾍' => '虫', + '⾎' => '血', + '⾏' => '行', + '⾐' => '衣', + '⾑' => '襾', + '⾒' => '見', + '⾓' => '角', + '⾔' => '言', + '⾕' => '谷', + '⾖' => '豆', + '⾗' => '豕', + '⾘' => '豸', + '⾙' => '貝', + '⾚' => '赤', + '⾛' => '走', + '⾜' => '足', + '⾝' => '身', + '⾞' => '車', + '⾟' => '辛', + '⾠' => '辰', + '⾡' => '辵', + '⾢' => '邑', + '⾣' => '酉', + '⾤' => '釆', + '⾥' => '里', + '⾦' => '金', + '⾧' => '長', + '⾨' => '門', + '⾩' => '阜', + '⾪' => '隶', + '⾫' => '隹', + '⾬' => '雨', + '⾭' => '靑', + '⾮' => '非', + '⾯' => '面', + '⾰' => '革', + '⾱' => '韋', + '⾲' => '韭', + '⾳' => '音', + '⾴' => '頁', + '⾵' => '風', + '⾶' => '飛', + '⾷' => '食', + '⾸' => '首', + '⾹' => '香', + '⾺' => '馬', + '⾻' => '骨', + '⾼' => '高', + '⾽' => '髟', + '⾾' => '鬥', + '⾿' => '鬯', + '⿀' => '鬲', + '⿁' => '鬼', + '⿂' => '魚', + '⿃' => '鳥', + '⿄' => '鹵', + '⿅' => '鹿', + '⿆' => '麥', + '⿇' => '麻', + '⿈' => '黃', + '⿉' => '黍', + '⿊' => '黑', + '⿋' => '黹', + '⿌' => '黽', + '⿍' => '鼎', + '⿎' => '鼓', + '⿏' => '鼠', + '⿐' => '鼻', + '⿑' => '齊', + '⿒' => '齒', + '⿓' => '龍', + '⿔' => '龜', + '⿕' => '龠', + ' ' => ' ', + '〶' => '〒', + '〸' => '十', + '〹' => '卄', + '〺' => '卅', + '゛' => ' ゙', + '゜' => ' ゚', + 'ゟ' => 'より', + 'ヿ' => 'コト', + 'ㄱ' => 'ᄀ', + 'ㄲ' => 'ᄁ', + 'ㄳ' => 'ᆪ', + 'ㄴ' => 'ᄂ', + 'ㄵ' => 'ᆬ', + 'ㄶ' => 'ᆭ', + 'ㄷ' => 'ᄃ', + 'ㄸ' => 'ᄄ', + 'ㄹ' => 'ᄅ', + 'ㄺ' => 'ᆰ', + 'ㄻ' => 'ᆱ', + 'ㄼ' => 'ᆲ', + 'ㄽ' => 'ᆳ', + 'ㄾ' => 'ᆴ', + 'ㄿ' => 'ᆵ', + 'ㅀ' => 'ᄚ', + 'ㅁ' => 'ᄆ', + 'ㅂ' => 'ᄇ', + 'ㅃ' => 'ᄈ', + 'ㅄ' => 'ᄡ', + 'ㅅ' => 'ᄉ', + 'ㅆ' => 'ᄊ', + 'ㅇ' => 'ᄋ', + 'ㅈ' => 'ᄌ', + 'ㅉ' => 'ᄍ', + 'ㅊ' => 'ᄎ', + 'ㅋ' => 'ᄏ', + 'ㅌ' => 'ᄐ', + 'ㅍ' => 'ᄑ', + 'ㅎ' => 'ᄒ', + 'ㅏ' => 'ᅡ', + 'ㅐ' => 'ᅢ', + 'ㅑ' => 'ᅣ', + 'ㅒ' => 'ᅤ', + 'ㅓ' => 'ᅥ', + 'ㅔ' => 'ᅦ', + 'ㅕ' => 'ᅧ', + 'ㅖ' => 'ᅨ', + 'ㅗ' => 'ᅩ', + 'ㅘ' => 'ᅪ', + 'ㅙ' => 'ᅫ', + 'ㅚ' => 'ᅬ', + 'ㅛ' => 'ᅭ', + 'ㅜ' => 'ᅮ', + 'ㅝ' => 'ᅯ', + 'ㅞ' => 'ᅰ', + 'ㅟ' => 'ᅱ', + 'ㅠ' => 'ᅲ', + 'ㅡ' => 'ᅳ', + 'ㅢ' => 'ᅴ', + 'ㅣ' => 'ᅵ', + 'ㅤ' => 'ᅠ', + 'ㅥ' => 'ᄔ', + 'ㅦ' => 'ᄕ', + 'ㅧ' => 'ᇇ', + 'ㅨ' => 'ᇈ', + 'ㅩ' => 'ᇌ', + 'ㅪ' => 'ᇎ', + 'ㅫ' => 'ᇓ', + 'ㅬ' => 'ᇗ', + 'ㅭ' => 'ᇙ', + 'ㅮ' => 'ᄜ', + 'ㅯ' => 'ᇝ', + 'ㅰ' => 'ᇟ', + 'ㅱ' => 'ᄝ', + 'ㅲ' => 'ᄞ', + 'ㅳ' => 'ᄠ', + 'ㅴ' => 'ᄢ', + 'ㅵ' => 'ᄣ', + 'ㅶ' => 'ᄧ', + 'ㅷ' => 'ᄩ', + 'ㅸ' => 'ᄫ', + 'ㅹ' => 'ᄬ', + 'ㅺ' => 'ᄭ', + 'ㅻ' => 'ᄮ', + 'ㅼ' => 'ᄯ', + 'ㅽ' => 'ᄲ', + 'ㅾ' => 'ᄶ', + 'ㅿ' => 'ᅀ', + 'ㆀ' => 'ᅇ', + 'ㆁ' => 'ᅌ', + 'ㆂ' => 'ᇱ', + 'ㆃ' => 'ᇲ', + 'ㆄ' => 'ᅗ', + 'ㆅ' => 'ᅘ', + 'ㆆ' => 'ᅙ', + 'ㆇ' => 'ᆄ', + 'ㆈ' => 'ᆅ', + 'ㆉ' => 'ᆈ', + 'ㆊ' => 'ᆑ', + 'ㆋ' => 'ᆒ', + 'ㆌ' => 'ᆔ', + 'ㆍ' => 'ᆞ', + 'ㆎ' => 'ᆡ', + '㆒' => '一', + '㆓' => '二', + '㆔' => '三', + '㆕' => '四', + '㆖' => '上', + '㆗' => '中', + '㆘' => '下', + '㆙' => '甲', + '㆚' => '乙', + '㆛' => '丙', + '㆜' => '丁', + '㆝' => '天', + '㆞' => '地', + '㆟' => '人', + '㈀' => '(ᄀ)', + '㈁' => '(ᄂ)', + '㈂' => '(ᄃ)', + '㈃' => '(ᄅ)', + '㈄' => '(ᄆ)', + '㈅' => '(ᄇ)', + '㈆' => '(ᄉ)', + '㈇' => '(ᄋ)', + '㈈' => '(ᄌ)', + '㈉' => '(ᄎ)', + '㈊' => '(ᄏ)', + '㈋' => '(ᄐ)', + '㈌' => '(ᄑ)', + '㈍' => '(ᄒ)', + '㈎' => '(가)', + '㈏' => '(나)', + '㈐' => '(다)', + '㈑' => '(라)', + '㈒' => '(마)', + '㈓' => '(바)', + '㈔' => '(사)', + '㈕' => '(아)', + '㈖' => '(자)', + '㈗' => '(차)', + '㈘' => '(카)', + '㈙' => '(타)', + '㈚' => '(파)', + '㈛' => '(하)', + '㈜' => '(주)', + '㈝' => '(오전)', + '㈞' => '(오후)', + '㈠' => '(一)', + '㈡' => '(二)', + '㈢' => '(三)', + '㈣' => '(四)', + '㈤' => '(五)', + '㈥' => '(六)', + '㈦' => '(七)', + '㈧' => '(八)', + '㈨' => '(九)', + '㈩' => '(十)', + '㈪' => '(月)', + '㈫' => '(火)', + '㈬' => '(水)', + '㈭' => '(木)', + '㈮' => '(金)', + '㈯' => '(土)', + '㈰' => '(日)', + '㈱' => '(株)', + '㈲' => '(有)', + '㈳' => '(社)', + '㈴' => '(名)', + '㈵' => '(特)', + '㈶' => '(財)', + '㈷' => '(祝)', + '㈸' => '(労)', + '㈹' => '(代)', + '㈺' => '(呼)', + '㈻' => '(学)', + '㈼' => '(監)', + '㈽' => '(企)', + '㈾' => '(資)', + '㈿' => '(協)', + '㉀' => '(祭)', + '㉁' => '(休)', + '㉂' => '(自)', + '㉃' => '(至)', + '㉄' => '問', + '㉅' => '幼', + '㉆' => '文', + '㉇' => '箏', + '㉐' => 'PTE', + '㉑' => '21', + '㉒' => '22', + '㉓' => '23', + '㉔' => '24', + '㉕' => '25', + '㉖' => '26', + '㉗' => '27', + '㉘' => '28', + '㉙' => '29', + '㉚' => '30', + '㉛' => '31', + '㉜' => '32', + '㉝' => '33', + '㉞' => '34', + '㉟' => '35', + '㉠' => 'ᄀ', + '㉡' => 'ᄂ', + '㉢' => 'ᄃ', + '㉣' => 'ᄅ', + '㉤' => 'ᄆ', + '㉥' => 'ᄇ', + '㉦' => 'ᄉ', + '㉧' => 'ᄋ', + '㉨' => 'ᄌ', + '㉩' => 'ᄎ', + '㉪' => 'ᄏ', + '㉫' => 'ᄐ', + '㉬' => 'ᄑ', + '㉭' => 'ᄒ', + '㉮' => '가', + '㉯' => '나', + '㉰' => '다', + '㉱' => '라', + '㉲' => '마', + '㉳' => '바', + '㉴' => '사', + '㉵' => '아', + '㉶' => '자', + '㉷' => '차', + '㉸' => '카', + '㉹' => '타', + '㉺' => '파', + '㉻' => '하', + '㉼' => '참고', + '㉽' => '주의', + '㉾' => '우', + '㊀' => '一', + '㊁' => '二', + '㊂' => '三', + '㊃' => '四', + '㊄' => '五', + '㊅' => '六', + '㊆' => '七', + '㊇' => '八', + '㊈' => '九', + '㊉' => '十', + '㊊' => '月', + '㊋' => '火', + '㊌' => '水', + '㊍' => '木', + '㊎' => '金', + '㊏' => '土', + '㊐' => '日', + '㊑' => '株', + '㊒' => '有', + '㊓' => '社', + '㊔' => '名', + '㊕' => '特', + '㊖' => '財', + '㊗' => '祝', + '㊘' => '労', + '㊙' => '秘', + '㊚' => '男', + '㊛' => '女', + '㊜' => '適', + '㊝' => '優', + '㊞' => '印', + '㊟' => '注', + '㊠' => '項', + '㊡' => '休', + '㊢' => '写', + '㊣' => '正', + '㊤' => '上', + '㊥' => '中', + '㊦' => '下', + '㊧' => '左', + '㊨' => '右', + '㊩' => '医', + '㊪' => '宗', + '㊫' => '学', + '㊬' => '監', + '㊭' => '企', + '㊮' => '資', + '㊯' => '協', + '㊰' => '夜', + '㊱' => '36', + '㊲' => '37', + '㊳' => '38', + '㊴' => '39', + '㊵' => '40', + '㊶' => '41', + '㊷' => '42', + '㊸' => '43', + '㊹' => '44', + '㊺' => '45', + '㊻' => '46', + '㊼' => '47', + '㊽' => '48', + '㊾' => '49', + '㊿' => '50', + '㋀' => '1月', + '㋁' => '2月', + '㋂' => '3月', + '㋃' => '4月', + '㋄' => '5月', + '㋅' => '6月', + '㋆' => '7月', + '㋇' => '8月', + '㋈' => '9月', + '㋉' => '10月', + '㋊' => '11月', + '㋋' => '12月', + '㋌' => 'Hg', + '㋍' => 'erg', + '㋎' => 'eV', + '㋏' => 'LTD', + '㋐' => 'ア', + '㋑' => 'イ', + '㋒' => 'ウ', + '㋓' => 'エ', + '㋔' => 'オ', + '㋕' => 'カ', + '㋖' => 'キ', + '㋗' => 'ク', + '㋘' => 'ケ', + '㋙' => 'コ', + '㋚' => 'サ', + '㋛' => 'シ', + '㋜' => 'ス', + '㋝' => 'セ', + '㋞' => 'ソ', + '㋟' => 'タ', + '㋠' => 'チ', + '㋡' => 'ツ', + '㋢' => 'テ', + '㋣' => 'ト', + '㋤' => 'ナ', + '㋥' => 'ニ', + '㋦' => 'ヌ', + '㋧' => 'ネ', + '㋨' => 'ノ', + '㋩' => 'ハ', + '㋪' => 'ヒ', + '㋫' => 'フ', + '㋬' => 'ヘ', + '㋭' => 'ホ', + '㋮' => 'マ', + '㋯' => 'ミ', + '㋰' => 'ム', + '㋱' => 'メ', + '㋲' => 'モ', + '㋳' => 'ヤ', + '㋴' => 'ユ', + '㋵' => 'ヨ', + '㋶' => 'ラ', + '㋷' => 'リ', + '㋸' => 'ル', + '㋹' => 'レ', + '㋺' => 'ロ', + '㋻' => 'ワ', + '㋼' => 'ヰ', + '㋽' => 'ヱ', + '㋾' => 'ヲ', + '㋿' => '令和', + '㌀' => 'アパート', + '㌁' => 'アルファ', + '㌂' => 'アンペア', + '㌃' => 'アール', + '㌄' => 'イニング', + '㌅' => 'インチ', + '㌆' => 'ウォン', + '㌇' => 'エスクード', + '㌈' => 'エーカー', + '㌉' => 'オンス', + '㌊' => 'オーム', + '㌋' => 'カイリ', + '㌌' => 'カラット', + '㌍' => 'カロリー', + '㌎' => 'ガロン', + '㌏' => 'ガンマ', + '㌐' => 'ギガ', + '㌑' => 'ギニー', + '㌒' => 'キュリー', + '㌓' => 'ギルダー', + '㌔' => 'キロ', + '㌕' => 'キログラム', + '㌖' => 'キロメートル', + '㌗' => 'キロワット', + '㌘' => 'グラム', + '㌙' => 'グラムトン', + '㌚' => 'クルゼイロ', + '㌛' => 'クローネ', + '㌜' => 'ケース', + '㌝' => 'コルナ', + '㌞' => 'コーポ', + '㌟' => 'サイクル', + '㌠' => 'サンチーム', + '㌡' => 'シリング', + '㌢' => 'センチ', + '㌣' => 'セント', + '㌤' => 'ダース', + '㌥' => 'デシ', + '㌦' => 'ドル', + '㌧' => 'トン', + '㌨' => 'ナノ', + '㌩' => 'ノット', + '㌪' => 'ハイツ', + '㌫' => 'パーセント', + '㌬' => 'パーツ', + '㌭' => 'バーレル', + '㌮' => 'ピアストル', + '㌯' => 'ピクル', + '㌰' => 'ピコ', + '㌱' => 'ビル', + '㌲' => 'ファラッド', + '㌳' => 'フィート', + '㌴' => 'ブッシェル', + '㌵' => 'フラン', + '㌶' => 'ヘクタール', + '㌷' => 'ペソ', + '㌸' => 'ペニヒ', + '㌹' => 'ヘルツ', + '㌺' => 'ペンス', + '㌻' => 'ページ', + '㌼' => 'ベータ', + '㌽' => 'ポイント', + '㌾' => 'ボルト', + '㌿' => 'ホン', + '㍀' => 'ポンド', + '㍁' => 'ホール', + '㍂' => 'ホーン', + '㍃' => 'マイクロ', + '㍄' => 'マイル', + '㍅' => 'マッハ', + '㍆' => 'マルク', + '㍇' => 'マンション', + '㍈' => 'ミクロン', + '㍉' => 'ミリ', + '㍊' => 'ミリバール', + '㍋' => 'メガ', + '㍌' => 'メガトン', + '㍍' => 'メートル', + '㍎' => 'ヤード', + '㍏' => 'ヤール', + '㍐' => 'ユアン', + '㍑' => 'リットル', + '㍒' => 'リラ', + '㍓' => 'ルピー', + '㍔' => 'ルーブル', + '㍕' => 'レム', + '㍖' => 'レントゲン', + '㍗' => 'ワット', + '㍘' => '0点', + '㍙' => '1点', + '㍚' => '2点', + '㍛' => '3点', + '㍜' => '4点', + '㍝' => '5点', + '㍞' => '6点', + '㍟' => '7点', + '㍠' => '8点', + '㍡' => '9点', + '㍢' => '10点', + '㍣' => '11点', + '㍤' => '12点', + '㍥' => '13点', + '㍦' => '14点', + '㍧' => '15点', + '㍨' => '16点', + '㍩' => '17点', + '㍪' => '18点', + '㍫' => '19点', + '㍬' => '20点', + '㍭' => '21点', + '㍮' => '22点', + '㍯' => '23点', + '㍰' => '24点', + '㍱' => 'hPa', + '㍲' => 'da', + '㍳' => 'AU', + '㍴' => 'bar', + '㍵' => 'oV', + '㍶' => 'pc', + '㍷' => 'dm', + '㍸' => 'dm2', + '㍹' => 'dm3', + '㍺' => 'IU', + '㍻' => '平成', + '㍼' => '昭和', + '㍽' => '大正', + '㍾' => '明治', + '㍿' => '株式会社', + '㎀' => 'pA', + '㎁' => 'nA', + '㎂' => 'μA', + '㎃' => 'mA', + '㎄' => 'kA', + '㎅' => 'KB', + '㎆' => 'MB', + '㎇' => 'GB', + '㎈' => 'cal', + '㎉' => 'kcal', + '㎊' => 'pF', + '㎋' => 'nF', + '㎌' => 'μF', + '㎍' => 'μg', + '㎎' => 'mg', + '㎏' => 'kg', + '㎐' => 'Hz', + '㎑' => 'kHz', + '㎒' => 'MHz', + '㎓' => 'GHz', + '㎔' => 'THz', + '㎕' => 'μl', + '㎖' => 'ml', + '㎗' => 'dl', + '㎘' => 'kl', + '㎙' => 'fm', + '㎚' => 'nm', + '㎛' => 'μm', + '㎜' => 'mm', + '㎝' => 'cm', + '㎞' => 'km', + '㎟' => 'mm2', + '㎠' => 'cm2', + '㎡' => 'm2', + '㎢' => 'km2', + '㎣' => 'mm3', + '㎤' => 'cm3', + '㎥' => 'm3', + '㎦' => 'km3', + '㎧' => 'm∕s', + '㎨' => 'm∕s2', + '㎩' => 'Pa', + '㎪' => 'kPa', + '㎫' => 'MPa', + '㎬' => 'GPa', + '㎭' => 'rad', + '㎮' => 'rad∕s', + '㎯' => 'rad∕s2', + '㎰' => 'ps', + '㎱' => 'ns', + '㎲' => 'μs', + '㎳' => 'ms', + '㎴' => 'pV', + '㎵' => 'nV', + '㎶' => 'μV', + '㎷' => 'mV', + '㎸' => 'kV', + '㎹' => 'MV', + '㎺' => 'pW', + '㎻' => 'nW', + '㎼' => 'μW', + '㎽' => 'mW', + '㎾' => 'kW', + '㎿' => 'MW', + '㏀' => 'kΩ', + '㏁' => 'MΩ', + '㏂' => 'a.m.', + '㏃' => 'Bq', + '㏄' => 'cc', + '㏅' => 'cd', + '㏆' => 'C∕kg', + '㏇' => 'Co.', + '㏈' => 'dB', + '㏉' => 'Gy', + '㏊' => 'ha', + '㏋' => 'HP', + '㏌' => 'in', + '㏍' => 'KK', + '㏎' => 'KM', + '㏏' => 'kt', + '㏐' => 'lm', + '㏑' => 'ln', + '㏒' => 'log', + '㏓' => 'lx', + '㏔' => 'mb', + '㏕' => 'mil', + '㏖' => 'mol', + '㏗' => 'PH', + '㏘' => 'p.m.', + '㏙' => 'PPM', + '㏚' => 'PR', + '㏛' => 'sr', + '㏜' => 'Sv', + '㏝' => 'Wb', + '㏞' => 'V∕m', + '㏟' => 'A∕m', + '㏠' => '1日', + '㏡' => '2日', + '㏢' => '3日', + '㏣' => '4日', + '㏤' => '5日', + '㏥' => '6日', + '㏦' => '7日', + '㏧' => '8日', + '㏨' => '9日', + '㏩' => '10日', + '㏪' => '11日', + '㏫' => '12日', + '㏬' => '13日', + '㏭' => '14日', + '㏮' => '15日', + '㏯' => '16日', + '㏰' => '17日', + '㏱' => '18日', + '㏲' => '19日', + '㏳' => '20日', + '㏴' => '21日', + '㏵' => '22日', + '㏶' => '23日', + '㏷' => '24日', + '㏸' => '25日', + '㏹' => '26日', + '㏺' => '27日', + '㏻' => '28日', + '㏼' => '29日', + '㏽' => '30日', + '㏾' => '31日', + '㏿' => 'gal', + 'ꚜ' => 'ъ', + 'ꚝ' => 'ь', + 'ꝰ' => 'ꝯ', + 'ꟸ' => 'Ħ', + 'ꟹ' => 'œ', + 'ꭜ' => 'ꜧ', + 'ꭝ' => 'ꬷ', + 'ꭞ' => 'ɫ', + 'ꭟ' => 'ꭒ', + 'ꭩ' => 'ʍ', + 'ff' => 'ff', + 'fi' => 'fi', + 'fl' => 'fl', + 'ffi' => 'ffi', + 'ffl' => 'ffl', + 'ſt' => 'st', + 'st' => 'st', + 'ﬓ' => 'մն', + 'ﬔ' => 'մե', + 'ﬕ' => 'մի', + 'ﬖ' => 'վն', + 'ﬗ' => 'մխ', + 'ﬠ' => 'ע', + 'ﬡ' => 'א', + 'ﬢ' => 'ד', + 'ﬣ' => 'ה', + 'ﬤ' => 'כ', + 'ﬥ' => 'ל', + 'ﬦ' => 'ם', + 'ﬧ' => 'ר', + 'ﬨ' => 'ת', + '﬩' => '+', + 'ﭏ' => 'אל', + 'ﭐ' => 'ٱ', + 'ﭑ' => 'ٱ', + 'ﭒ' => 'ٻ', + 'ﭓ' => 'ٻ', + 'ﭔ' => 'ٻ', + 'ﭕ' => 'ٻ', + 'ﭖ' => 'پ', + 'ﭗ' => 'پ', + 'ﭘ' => 'پ', + 'ﭙ' => 'پ', + 'ﭚ' => 'ڀ', + 'ﭛ' => 'ڀ', + 'ﭜ' => 'ڀ', + 'ﭝ' => 'ڀ', + 'ﭞ' => 'ٺ', + 'ﭟ' => 'ٺ', + 'ﭠ' => 'ٺ', + 'ﭡ' => 'ٺ', + 'ﭢ' => 'ٿ', + 'ﭣ' => 'ٿ', + 'ﭤ' => 'ٿ', + 'ﭥ' => 'ٿ', + 'ﭦ' => 'ٹ', + 'ﭧ' => 'ٹ', + 'ﭨ' => 'ٹ', + 'ﭩ' => 'ٹ', + 'ﭪ' => 'ڤ', + 'ﭫ' => 'ڤ', + 'ﭬ' => 'ڤ', + 'ﭭ' => 'ڤ', + 'ﭮ' => 'ڦ', + 'ﭯ' => 'ڦ', + 'ﭰ' => 'ڦ', + 'ﭱ' => 'ڦ', + 'ﭲ' => 'ڄ', + 'ﭳ' => 'ڄ', + 'ﭴ' => 'ڄ', + 'ﭵ' => 'ڄ', + 'ﭶ' => 'ڃ', + 'ﭷ' => 'ڃ', + 'ﭸ' => 'ڃ', + 'ﭹ' => 'ڃ', + 'ﭺ' => 'چ', + 'ﭻ' => 'چ', + 'ﭼ' => 'چ', + 'ﭽ' => 'چ', + 'ﭾ' => 'ڇ', + 'ﭿ' => 'ڇ', + 'ﮀ' => 'ڇ', + 'ﮁ' => 'ڇ', + 'ﮂ' => 'ڍ', + 'ﮃ' => 'ڍ', + 'ﮄ' => 'ڌ', + 'ﮅ' => 'ڌ', + 'ﮆ' => 'ڎ', + 'ﮇ' => 'ڎ', + 'ﮈ' => 'ڈ', + 'ﮉ' => 'ڈ', + 'ﮊ' => 'ژ', + 'ﮋ' => 'ژ', + 'ﮌ' => 'ڑ', + 'ﮍ' => 'ڑ', + 'ﮎ' => 'ک', + 'ﮏ' => 'ک', + 'ﮐ' => 'ک', + 'ﮑ' => 'ک', + 'ﮒ' => 'گ', + 'ﮓ' => 'گ', + 'ﮔ' => 'گ', + 'ﮕ' => 'گ', + 'ﮖ' => 'ڳ', + 'ﮗ' => 'ڳ', + 'ﮘ' => 'ڳ', + 'ﮙ' => 'ڳ', + 'ﮚ' => 'ڱ', + 'ﮛ' => 'ڱ', + 'ﮜ' => 'ڱ', + 'ﮝ' => 'ڱ', + 'ﮞ' => 'ں', + 'ﮟ' => 'ں', + 'ﮠ' => 'ڻ', + 'ﮡ' => 'ڻ', + 'ﮢ' => 'ڻ', + 'ﮣ' => 'ڻ', + 'ﮤ' => 'ۀ', + 'ﮥ' => 'ۀ', + 'ﮦ' => 'ہ', + 'ﮧ' => 'ہ', + 'ﮨ' => 'ہ', + 'ﮩ' => 'ہ', + 'ﮪ' => 'ھ', + 'ﮫ' => 'ھ', + 'ﮬ' => 'ھ', + 'ﮭ' => 'ھ', + 'ﮮ' => 'ے', + 'ﮯ' => 'ے', + 'ﮰ' => 'ۓ', + 'ﮱ' => 'ۓ', + 'ﯓ' => 'ڭ', + 'ﯔ' => 'ڭ', + 'ﯕ' => 'ڭ', + 'ﯖ' => 'ڭ', + 'ﯗ' => 'ۇ', + 'ﯘ' => 'ۇ', + 'ﯙ' => 'ۆ', + 'ﯚ' => 'ۆ', + 'ﯛ' => 'ۈ', + 'ﯜ' => 'ۈ', + 'ﯝ' => 'ۇٴ', + 'ﯞ' => 'ۋ', + 'ﯟ' => 'ۋ', + 'ﯠ' => 'ۅ', + 'ﯡ' => 'ۅ', + 'ﯢ' => 'ۉ', + 'ﯣ' => 'ۉ', + 'ﯤ' => 'ې', + 'ﯥ' => 'ې', + 'ﯦ' => 'ې', + 'ﯧ' => 'ې', + 'ﯨ' => 'ى', + 'ﯩ' => 'ى', + 'ﯪ' => 'ئا', + 'ﯫ' => 'ئا', + 'ﯬ' => 'ئە', + 'ﯭ' => 'ئە', + 'ﯮ' => 'ئو', + 'ﯯ' => 'ئو', + 'ﯰ' => 'ئۇ', + 'ﯱ' => 'ئۇ', + 'ﯲ' => 'ئۆ', + 'ﯳ' => 'ئۆ', + 'ﯴ' => 'ئۈ', + 'ﯵ' => 'ئۈ', + 'ﯶ' => 'ئې', + 'ﯷ' => 'ئې', + 'ﯸ' => 'ئې', + 'ﯹ' => 'ئى', + 'ﯺ' => 'ئى', + 'ﯻ' => 'ئى', + 'ﯼ' => 'ی', + 'ﯽ' => 'ی', + 'ﯾ' => 'ی', + 'ﯿ' => 'ی', + 'ﰀ' => 'ئج', + 'ﰁ' => 'ئح', + 'ﰂ' => 'ئم', + 'ﰃ' => 'ئى', + 'ﰄ' => 'ئي', + 'ﰅ' => 'بج', + 'ﰆ' => 'بح', + 'ﰇ' => 'بخ', + 'ﰈ' => 'بم', + 'ﰉ' => 'بى', + 'ﰊ' => 'بي', + 'ﰋ' => 'تج', + 'ﰌ' => 'تح', + 'ﰍ' => 'تخ', + 'ﰎ' => 'تم', + 'ﰏ' => 'تى', + 'ﰐ' => 'تي', + 'ﰑ' => 'ثج', + 'ﰒ' => 'ثم', + 'ﰓ' => 'ثى', + 'ﰔ' => 'ثي', + 'ﰕ' => 'جح', + 'ﰖ' => 'جم', + 'ﰗ' => 'حج', + 'ﰘ' => 'حم', + 'ﰙ' => 'خج', + 'ﰚ' => 'خح', + 'ﰛ' => 'خم', + 'ﰜ' => 'سج', + 'ﰝ' => 'سح', + 'ﰞ' => 'سخ', + 'ﰟ' => 'سم', + 'ﰠ' => 'صح', + 'ﰡ' => 'صم', + 'ﰢ' => 'ضج', + 'ﰣ' => 'ضح', + 'ﰤ' => 'ضخ', + 'ﰥ' => 'ضم', + 'ﰦ' => 'طح', + 'ﰧ' => 'طم', + 'ﰨ' => 'ظم', + 'ﰩ' => 'عج', + 'ﰪ' => 'عم', + 'ﰫ' => 'غج', + 'ﰬ' => 'غم', + 'ﰭ' => 'فج', + 'ﰮ' => 'فح', + 'ﰯ' => 'فخ', + 'ﰰ' => 'فم', + 'ﰱ' => 'فى', + 'ﰲ' => 'في', + 'ﰳ' => 'قح', + 'ﰴ' => 'قم', + 'ﰵ' => 'قى', + 'ﰶ' => 'قي', + 'ﰷ' => 'كا', + 'ﰸ' => 'كج', + 'ﰹ' => 'كح', + 'ﰺ' => 'كخ', + 'ﰻ' => 'كل', + 'ﰼ' => 'كم', + 'ﰽ' => 'كى', + 'ﰾ' => 'كي', + 'ﰿ' => 'لج', + 'ﱀ' => 'لح', + 'ﱁ' => 'لخ', + 'ﱂ' => 'لم', + 'ﱃ' => 'لى', + 'ﱄ' => 'لي', + 'ﱅ' => 'مج', + 'ﱆ' => 'مح', + 'ﱇ' => 'مخ', + 'ﱈ' => 'مم', + 'ﱉ' => 'مى', + 'ﱊ' => 'مي', + 'ﱋ' => 'نج', + 'ﱌ' => 'نح', + 'ﱍ' => 'نخ', + 'ﱎ' => 'نم', + 'ﱏ' => 'نى', + 'ﱐ' => 'ني', + 'ﱑ' => 'هج', + 'ﱒ' => 'هم', + 'ﱓ' => 'هى', + 'ﱔ' => 'هي', + 'ﱕ' => 'يج', + 'ﱖ' => 'يح', + 'ﱗ' => 'يخ', + 'ﱘ' => 'يم', + 'ﱙ' => 'يى', + 'ﱚ' => 'يي', + 'ﱛ' => 'ذٰ', + 'ﱜ' => 'رٰ', + 'ﱝ' => 'ىٰ', + 'ﱞ' => ' ٌّ', + 'ﱟ' => ' ٍّ', + 'ﱠ' => ' َّ', + 'ﱡ' => ' ُّ', + 'ﱢ' => ' ِّ', + 'ﱣ' => ' ّٰ', + 'ﱤ' => 'ئر', + 'ﱥ' => 'ئز', + 'ﱦ' => 'ئم', + 'ﱧ' => 'ئن', + 'ﱨ' => 'ئى', + 'ﱩ' => 'ئي', + 'ﱪ' => 'بر', + 'ﱫ' => 'بز', + 'ﱬ' => 'بم', + 'ﱭ' => 'بن', + 'ﱮ' => 'بى', + 'ﱯ' => 'بي', + 'ﱰ' => 'تر', + 'ﱱ' => 'تز', + 'ﱲ' => 'تم', + 'ﱳ' => 'تن', + 'ﱴ' => 'تى', + 'ﱵ' => 'تي', + 'ﱶ' => 'ثر', + 'ﱷ' => 'ثز', + 'ﱸ' => 'ثم', + 'ﱹ' => 'ثن', + 'ﱺ' => 'ثى', + 'ﱻ' => 'ثي', + 'ﱼ' => 'فى', + 'ﱽ' => 'في', + 'ﱾ' => 'قى', + 'ﱿ' => 'قي', + 'ﲀ' => 'كا', + 'ﲁ' => 'كل', + 'ﲂ' => 'كم', + 'ﲃ' => 'كى', + 'ﲄ' => 'كي', + 'ﲅ' => 'لم', + 'ﲆ' => 'لى', + 'ﲇ' => 'لي', + 'ﲈ' => 'ما', + 'ﲉ' => 'مم', + 'ﲊ' => 'نر', + 'ﲋ' => 'نز', + 'ﲌ' => 'نم', + 'ﲍ' => 'نن', + 'ﲎ' => 'نى', + 'ﲏ' => 'ني', + 'ﲐ' => 'ىٰ', + 'ﲑ' => 'ير', + 'ﲒ' => 'يز', + 'ﲓ' => 'يم', + 'ﲔ' => 'ين', + 'ﲕ' => 'يى', + 'ﲖ' => 'يي', + 'ﲗ' => 'ئج', + 'ﲘ' => 'ئح', + 'ﲙ' => 'ئخ', + 'ﲚ' => 'ئم', + 'ﲛ' => 'ئه', + 'ﲜ' => 'بج', + 'ﲝ' => 'بح', + 'ﲞ' => 'بخ', + 'ﲟ' => 'بم', + 'ﲠ' => 'به', + 'ﲡ' => 'تج', + 'ﲢ' => 'تح', + 'ﲣ' => 'تخ', + 'ﲤ' => 'تم', + 'ﲥ' => 'ته', + 'ﲦ' => 'ثم', + 'ﲧ' => 'جح', + 'ﲨ' => 'جم', + 'ﲩ' => 'حج', + 'ﲪ' => 'حم', + 'ﲫ' => 'خج', + 'ﲬ' => 'خم', + 'ﲭ' => 'سج', + 'ﲮ' => 'سح', + 'ﲯ' => 'سخ', + 'ﲰ' => 'سم', + 'ﲱ' => 'صح', + 'ﲲ' => 'صخ', + 'ﲳ' => 'صم', + 'ﲴ' => 'ضج', + 'ﲵ' => 'ضح', + 'ﲶ' => 'ضخ', + 'ﲷ' => 'ضم', + 'ﲸ' => 'طح', + 'ﲹ' => 'ظم', + 'ﲺ' => 'عج', + 'ﲻ' => 'عم', + 'ﲼ' => 'غج', + 'ﲽ' => 'غم', + 'ﲾ' => 'فج', + 'ﲿ' => 'فح', + 'ﳀ' => 'فخ', + 'ﳁ' => 'فم', + 'ﳂ' => 'قح', + 'ﳃ' => 'قم', + 'ﳄ' => 'كج', + 'ﳅ' => 'كح', + 'ﳆ' => 'كخ', + 'ﳇ' => 'كل', + 'ﳈ' => 'كم', + 'ﳉ' => 'لج', + 'ﳊ' => 'لح', + 'ﳋ' => 'لخ', + 'ﳌ' => 'لم', + 'ﳍ' => 'له', + 'ﳎ' => 'مج', + 'ﳏ' => 'مح', + 'ﳐ' => 'مخ', + 'ﳑ' => 'مم', + 'ﳒ' => 'نج', + 'ﳓ' => 'نح', + 'ﳔ' => 'نخ', + 'ﳕ' => 'نم', + 'ﳖ' => 'نه', + 'ﳗ' => 'هج', + 'ﳘ' => 'هم', + 'ﳙ' => 'هٰ', + 'ﳚ' => 'يج', + 'ﳛ' => 'يح', + 'ﳜ' => 'يخ', + 'ﳝ' => 'يم', + 'ﳞ' => 'يه', + 'ﳟ' => 'ئم', + 'ﳠ' => 'ئه', + 'ﳡ' => 'بم', + 'ﳢ' => 'به', + 'ﳣ' => 'تم', + 'ﳤ' => 'ته', + 'ﳥ' => 'ثم', + 'ﳦ' => 'ثه', + 'ﳧ' => 'سم', + 'ﳨ' => 'سه', + 'ﳩ' => 'شم', + 'ﳪ' => 'شه', + 'ﳫ' => 'كل', + 'ﳬ' => 'كم', + 'ﳭ' => 'لم', + 'ﳮ' => 'نم', + 'ﳯ' => 'نه', + 'ﳰ' => 'يم', + 'ﳱ' => 'يه', + 'ﳲ' => 'ـَّ', + 'ﳳ' => 'ـُّ', + 'ﳴ' => 'ـِّ', + 'ﳵ' => 'طى', + 'ﳶ' => 'طي', + 'ﳷ' => 'عى', + 'ﳸ' => 'عي', + 'ﳹ' => 'غى', + 'ﳺ' => 'غي', + 'ﳻ' => 'سى', + 'ﳼ' => 'سي', + 'ﳽ' => 'شى', + 'ﳾ' => 'شي', + 'ﳿ' => 'حى', + 'ﴀ' => 'حي', + 'ﴁ' => 'جى', + 'ﴂ' => 'جي', + 'ﴃ' => 'خى', + 'ﴄ' => 'خي', + 'ﴅ' => 'صى', + 'ﴆ' => 'صي', + 'ﴇ' => 'ضى', + 'ﴈ' => 'ضي', + 'ﴉ' => 'شج', + 'ﴊ' => 'شح', + 'ﴋ' => 'شخ', + 'ﴌ' => 'شم', + 'ﴍ' => 'شر', + 'ﴎ' => 'سر', + 'ﴏ' => 'صر', + 'ﴐ' => 'ضر', + 'ﴑ' => 'طى', + 'ﴒ' => 'طي', + 'ﴓ' => 'عى', + 'ﴔ' => 'عي', + 'ﴕ' => 'غى', + 'ﴖ' => 'غي', + 'ﴗ' => 'سى', + 'ﴘ' => 'سي', + 'ﴙ' => 'شى', + 'ﴚ' => 'شي', + 'ﴛ' => 'حى', + 'ﴜ' => 'حي', + 'ﴝ' => 'جى', + 'ﴞ' => 'جي', + 'ﴟ' => 'خى', + 'ﴠ' => 'خي', + 'ﴡ' => 'صى', + 'ﴢ' => 'صي', + 'ﴣ' => 'ضى', + 'ﴤ' => 'ضي', + 'ﴥ' => 'شج', + 'ﴦ' => 'شح', + 'ﴧ' => 'شخ', + 'ﴨ' => 'شم', + 'ﴩ' => 'شر', + 'ﴪ' => 'سر', + 'ﴫ' => 'صر', + 'ﴬ' => 'ضر', + 'ﴭ' => 'شج', + 'ﴮ' => 'شح', + 'ﴯ' => 'شخ', + 'ﴰ' => 'شم', + 'ﴱ' => 'سه', + 'ﴲ' => 'شه', + 'ﴳ' => 'طم', + 'ﴴ' => 'سج', + 'ﴵ' => 'سح', + 'ﴶ' => 'سخ', + 'ﴷ' => 'شج', + 'ﴸ' => 'شح', + 'ﴹ' => 'شخ', + 'ﴺ' => 'طم', + 'ﴻ' => 'ظم', + 'ﴼ' => 'اً', + 'ﴽ' => 'اً', + 'ﵐ' => 'تجم', + 'ﵑ' => 'تحج', + 'ﵒ' => 'تحج', + 'ﵓ' => 'تحم', + 'ﵔ' => 'تخم', + 'ﵕ' => 'تمج', + 'ﵖ' => 'تمح', + 'ﵗ' => 'تمخ', + 'ﵘ' => 'جمح', + 'ﵙ' => 'جمح', + 'ﵚ' => 'حمي', + 'ﵛ' => 'حمى', + 'ﵜ' => 'سحج', + 'ﵝ' => 'سجح', + 'ﵞ' => 'سجى', + 'ﵟ' => 'سمح', + 'ﵠ' => 'سمح', + 'ﵡ' => 'سمج', + 'ﵢ' => 'سمم', + 'ﵣ' => 'سمم', + 'ﵤ' => 'صحح', + 'ﵥ' => 'صحح', + 'ﵦ' => 'صمم', + 'ﵧ' => 'شحم', + 'ﵨ' => 'شحم', + 'ﵩ' => 'شجي', + 'ﵪ' => 'شمخ', + 'ﵫ' => 'شمخ', + 'ﵬ' => 'شمم', + 'ﵭ' => 'شمم', + 'ﵮ' => 'ضحى', + 'ﵯ' => 'ضخم', + 'ﵰ' => 'ضخم', + 'ﵱ' => 'طمح', + 'ﵲ' => 'طمح', + 'ﵳ' => 'طمم', + 'ﵴ' => 'طمي', + 'ﵵ' => 'عجم', + 'ﵶ' => 'عمم', + 'ﵷ' => 'عمم', + 'ﵸ' => 'عمى', + 'ﵹ' => 'غمم', + 'ﵺ' => 'غمي', + 'ﵻ' => 'غمى', + 'ﵼ' => 'فخم', + 'ﵽ' => 'فخم', + 'ﵾ' => 'قمح', + 'ﵿ' => 'قمم', + 'ﶀ' => 'لحم', + 'ﶁ' => 'لحي', + 'ﶂ' => 'لحى', + 'ﶃ' => 'لجج', + 'ﶄ' => 'لجج', + 'ﶅ' => 'لخم', + 'ﶆ' => 'لخم', + 'ﶇ' => 'لمح', + 'ﶈ' => 'لمح', + 'ﶉ' => 'محج', + 'ﶊ' => 'محم', + 'ﶋ' => 'محي', + 'ﶌ' => 'مجح', + 'ﶍ' => 'مجم', + 'ﶎ' => 'مخج', + 'ﶏ' => 'مخم', + 'ﶒ' => 'مجخ', + 'ﶓ' => 'همج', + 'ﶔ' => 'همم', + 'ﶕ' => 'نحم', + 'ﶖ' => 'نحى', + 'ﶗ' => 'نجم', + 'ﶘ' => 'نجم', + 'ﶙ' => 'نجى', + 'ﶚ' => 'نمي', + 'ﶛ' => 'نمى', + 'ﶜ' => 'يمم', + 'ﶝ' => 'يمم', + 'ﶞ' => 'بخي', + 'ﶟ' => 'تجي', + 'ﶠ' => 'تجى', + 'ﶡ' => 'تخي', + 'ﶢ' => 'تخى', + 'ﶣ' => 'تمي', + 'ﶤ' => 'تمى', + 'ﶥ' => 'جمي', + 'ﶦ' => 'جحى', + 'ﶧ' => 'جمى', + 'ﶨ' => 'سخى', + 'ﶩ' => 'صحي', + 'ﶪ' => 'شحي', + 'ﶫ' => 'ضحي', + 'ﶬ' => 'لجي', + 'ﶭ' => 'لمي', + 'ﶮ' => 'يحي', + 'ﶯ' => 'يجي', + 'ﶰ' => 'يمي', + 'ﶱ' => 'ممي', + 'ﶲ' => 'قمي', + 'ﶳ' => 'نحي', + 'ﶴ' => 'قمح', + 'ﶵ' => 'لحم', + 'ﶶ' => 'عمي', + 'ﶷ' => 'كمي', + 'ﶸ' => 'نجح', + 'ﶹ' => 'مخي', + 'ﶺ' => 'لجم', + 'ﶻ' => 'كمم', + 'ﶼ' => 'لجم', + 'ﶽ' => 'نجح', + 'ﶾ' => 'جحي', + 'ﶿ' => 'حجي', + 'ﷀ' => 'مجي', + 'ﷁ' => 'فمي', + 'ﷂ' => 'بحي', + 'ﷃ' => 'كمم', + 'ﷄ' => 'عجم', + 'ﷅ' => 'صمم', + 'ﷆ' => 'سخي', + 'ﷇ' => 'نجي', + 'ﷰ' => 'صلے', + 'ﷱ' => 'قلے', + 'ﷲ' => 'الله', + 'ﷳ' => 'اكبر', + 'ﷴ' => 'محمد', + 'ﷵ' => 'صلعم', + 'ﷶ' => 'رسول', + 'ﷷ' => 'عليه', + 'ﷸ' => 'وسلم', + 'ﷹ' => 'صلى', + 'ﷺ' => 'صلى الله عليه وسلم', + 'ﷻ' => 'جل جلاله', + '﷼' => 'ریال', + '︐' => ',', + '︑' => '、', + '︒' => '。', + '︓' => ':', + '︔' => ';', + '︕' => '!', + '︖' => '?', + '︗' => '〖', + '︘' => '〗', + '︙' => '...', + '︰' => '..', + '︱' => '—', + '︲' => '–', + '︳' => '_', + '︴' => '_', + '︵' => '(', + '︶' => ')', + '︷' => '{', + '︸' => '}', + '︹' => '〔', + '︺' => '〕', + '︻' => '【', + '︼' => '】', + '︽' => '《', + '︾' => '》', + '︿' => '〈', + '﹀' => '〉', + '﹁' => '「', + '﹂' => '」', + '﹃' => '『', + '﹄' => '』', + '﹇' => '[', + '﹈' => ']', + '﹉' => ' ̅', + '﹊' => ' ̅', + '﹋' => ' ̅', + '﹌' => ' ̅', + '﹍' => '_', + '﹎' => '_', + '﹏' => '_', + '﹐' => ',', + '﹑' => '、', + '﹒' => '.', + '﹔' => ';', + '﹕' => ':', + '﹖' => '?', + '﹗' => '!', + '﹘' => '—', + '﹙' => '(', + '﹚' => ')', + '﹛' => '{', + '﹜' => '}', + '﹝' => '〔', + '﹞' => '〕', + '﹟' => '#', + '﹠' => '&', + '﹡' => '*', + '﹢' => '+', + '﹣' => '-', + '﹤' => '<', + '﹥' => '>', + '﹦' => '=', + '﹨' => '\\', + '﹩' => '$', + '﹪' => '%', + '﹫' => '@', + 'ﹰ' => ' ً', + 'ﹱ' => 'ـً', + 'ﹲ' => ' ٌ', + 'ﹴ' => ' ٍ', + 'ﹶ' => ' َ', + 'ﹷ' => 'ـَ', + 'ﹸ' => ' ُ', + 'ﹹ' => 'ـُ', + 'ﹺ' => ' ِ', + 'ﹻ' => 'ـِ', + 'ﹼ' => ' ّ', + 'ﹽ' => 'ـّ', + 'ﹾ' => ' ْ', + 'ﹿ' => 'ـْ', + 'ﺀ' => 'ء', + 'ﺁ' => 'آ', + 'ﺂ' => 'آ', + 'ﺃ' => 'أ', + 'ﺄ' => 'أ', + 'ﺅ' => 'ؤ', + 'ﺆ' => 'ؤ', + 'ﺇ' => 'إ', + 'ﺈ' => 'إ', + 'ﺉ' => 'ئ', + 'ﺊ' => 'ئ', + 'ﺋ' => 'ئ', + 'ﺌ' => 'ئ', + 'ﺍ' => 'ا', + 'ﺎ' => 'ا', + 'ﺏ' => 'ب', + 'ﺐ' => 'ب', + 'ﺑ' => 'ب', + 'ﺒ' => 'ب', + 'ﺓ' => 'ة', + 'ﺔ' => 'ة', + 'ﺕ' => 'ت', + 'ﺖ' => 'ت', + 'ﺗ' => 'ت', + 'ﺘ' => 'ت', + 'ﺙ' => 'ث', + 'ﺚ' => 'ث', + 'ﺛ' => 'ث', + 'ﺜ' => 'ث', + 'ﺝ' => 'ج', + 'ﺞ' => 'ج', + 'ﺟ' => 'ج', + 'ﺠ' => 'ج', + 'ﺡ' => 'ح', + 'ﺢ' => 'ح', + 'ﺣ' => 'ح', + 'ﺤ' => 'ح', + 'ﺥ' => 'خ', + 'ﺦ' => 'خ', + 'ﺧ' => 'خ', + 'ﺨ' => 'خ', + 'ﺩ' => 'د', + 'ﺪ' => 'د', + 'ﺫ' => 'ذ', + 'ﺬ' => 'ذ', + 'ﺭ' => 'ر', + 'ﺮ' => 'ر', + 'ﺯ' => 'ز', + 'ﺰ' => 'ز', + 'ﺱ' => 'س', + 'ﺲ' => 'س', + 'ﺳ' => 'س', + 'ﺴ' => 'س', + 'ﺵ' => 'ش', + 'ﺶ' => 'ش', + 'ﺷ' => 'ش', + 'ﺸ' => 'ش', + 'ﺹ' => 'ص', + 'ﺺ' => 'ص', + 'ﺻ' => 'ص', + 'ﺼ' => 'ص', + 'ﺽ' => 'ض', + 'ﺾ' => 'ض', + 'ﺿ' => 'ض', + 'ﻀ' => 'ض', + 'ﻁ' => 'ط', + 'ﻂ' => 'ط', + 'ﻃ' => 'ط', + 'ﻄ' => 'ط', + 'ﻅ' => 'ظ', + 'ﻆ' => 'ظ', + 'ﻇ' => 'ظ', + 'ﻈ' => 'ظ', + 'ﻉ' => 'ع', + 'ﻊ' => 'ع', + 'ﻋ' => 'ع', + 'ﻌ' => 'ع', + 'ﻍ' => 'غ', + 'ﻎ' => 'غ', + 'ﻏ' => 'غ', + 'ﻐ' => 'غ', + 'ﻑ' => 'ف', + 'ﻒ' => 'ف', + 'ﻓ' => 'ف', + 'ﻔ' => 'ف', + 'ﻕ' => 'ق', + 'ﻖ' => 'ق', + 'ﻗ' => 'ق', + 'ﻘ' => 'ق', + 'ﻙ' => 'ك', + 'ﻚ' => 'ك', + 'ﻛ' => 'ك', + 'ﻜ' => 'ك', + 'ﻝ' => 'ل', + 'ﻞ' => 'ل', + 'ﻟ' => 'ل', + 'ﻠ' => 'ل', + 'ﻡ' => 'م', + 'ﻢ' => 'م', + 'ﻣ' => 'م', + 'ﻤ' => 'م', + 'ﻥ' => 'ن', + 'ﻦ' => 'ن', + 'ﻧ' => 'ن', + 'ﻨ' => 'ن', + 'ﻩ' => 'ه', + 'ﻪ' => 'ه', + 'ﻫ' => 'ه', + 'ﻬ' => 'ه', + 'ﻭ' => 'و', + 'ﻮ' => 'و', + 'ﻯ' => 'ى', + 'ﻰ' => 'ى', + 'ﻱ' => 'ي', + 'ﻲ' => 'ي', + 'ﻳ' => 'ي', + 'ﻴ' => 'ي', + 'ﻵ' => 'لآ', + 'ﻶ' => 'لآ', + 'ﻷ' => 'لأ', + 'ﻸ' => 'لأ', + 'ﻹ' => 'لإ', + 'ﻺ' => 'لإ', + 'ﻻ' => 'لا', + 'ﻼ' => 'لا', + '!' => '!', + '"' => '"', + '#' => '#', + '$' => '$', + '%' => '%', + '&' => '&', + ''' => '\'', + '(' => '(', + ')' => ')', + '*' => '*', + '+' => '+', + ',' => ',', + '-' => '-', + '.' => '.', + '/' => '/', + '0' => '0', + '1' => '1', + '2' => '2', + '3' => '3', + '4' => '4', + '5' => '5', + '6' => '6', + '7' => '7', + '8' => '8', + '9' => '9', + ':' => ':', + ';' => ';', + '<' => '<', + '=' => '=', + '>' => '>', + '?' => '?', + '@' => '@', + 'A' => 'A', + 'B' => 'B', + 'C' => 'C', + 'D' => 'D', + 'E' => 'E', + 'F' => 'F', + 'G' => 'G', + 'H' => 'H', + 'I' => 'I', + 'J' => 'J', + 'K' => 'K', + 'L' => 'L', + 'M' => 'M', + 'N' => 'N', + 'O' => 'O', + 'P' => 'P', + 'Q' => 'Q', + 'R' => 'R', + 'S' => 'S', + 'T' => 'T', + 'U' => 'U', + 'V' => 'V', + 'W' => 'W', + 'X' => 'X', + 'Y' => 'Y', + 'Z' => 'Z', + '[' => '[', + '\' => '\\', + ']' => ']', + '^' => '^', + '_' => '_', + '`' => '`', + 'a' => 'a', + 'b' => 'b', + 'c' => 'c', + 'd' => 'd', + 'e' => 'e', + 'f' => 'f', + 'g' => 'g', + 'h' => 'h', + 'i' => 'i', + 'j' => 'j', + 'k' => 'k', + 'l' => 'l', + 'm' => 'm', + 'n' => 'n', + 'o' => 'o', + 'p' => 'p', + 'q' => 'q', + 'r' => 'r', + 's' => 's', + 't' => 't', + 'u' => 'u', + 'v' => 'v', + 'w' => 'w', + 'x' => 'x', + 'y' => 'y', + 'z' => 'z', + '{' => '{', + '|' => '|', + '}' => '}', + '~' => '~', + '⦅' => '⦅', + '⦆' => '⦆', + '。' => '。', + '「' => '「', + '」' => '」', + '、' => '、', + '・' => '・', + 'ヲ' => 'ヲ', + 'ァ' => 'ァ', + 'ィ' => 'ィ', + 'ゥ' => 'ゥ', + 'ェ' => 'ェ', + 'ォ' => 'ォ', + 'ャ' => 'ャ', + 'ュ' => 'ュ', + 'ョ' => 'ョ', + 'ッ' => 'ッ', + 'ー' => 'ー', + 'ア' => 'ア', + 'イ' => 'イ', + 'ウ' => 'ウ', + 'エ' => 'エ', + 'オ' => 'オ', + 'カ' => 'カ', + 'キ' => 'キ', + 'ク' => 'ク', + 'ケ' => 'ケ', + 'コ' => 'コ', + 'サ' => 'サ', + 'シ' => 'シ', + 'ス' => 'ス', + 'セ' => 'セ', + 'ソ' => 'ソ', + 'タ' => 'タ', + 'チ' => 'チ', + 'ツ' => 'ツ', + 'テ' => 'テ', + 'ト' => 'ト', + 'ナ' => 'ナ', + 'ニ' => 'ニ', + 'ヌ' => 'ヌ', + 'ネ' => 'ネ', + 'ノ' => 'ノ', + 'ハ' => 'ハ', + 'ヒ' => 'ヒ', + 'フ' => 'フ', + 'ヘ' => 'ヘ', + 'ホ' => 'ホ', + 'マ' => 'マ', + 'ミ' => 'ミ', + 'ム' => 'ム', + 'メ' => 'メ', + 'モ' => 'モ', + 'ヤ' => 'ヤ', + 'ユ' => 'ユ', + 'ヨ' => 'ヨ', + 'ラ' => 'ラ', + 'リ' => 'リ', + 'ル' => 'ル', + 'レ' => 'レ', + 'ロ' => 'ロ', + 'ワ' => 'ワ', + 'ン' => 'ン', + '゙' => '゙', + '゚' => '゚', + 'ᅠ' => 'ᅠ', + 'ᄀ' => 'ᄀ', + 'ᄁ' => 'ᄁ', + 'ᆪ' => 'ᆪ', + 'ᄂ' => 'ᄂ', + 'ᆬ' => 'ᆬ', + 'ᆭ' => 'ᆭ', + 'ᄃ' => 'ᄃ', + 'ᄄ' => 'ᄄ', + 'ᄅ' => 'ᄅ', + 'ᆰ' => 'ᆰ', + 'ᆱ' => 'ᆱ', + 'ᆲ' => 'ᆲ', + 'ᆳ' => 'ᆳ', + 'ᆴ' => 'ᆴ', + 'ᆵ' => 'ᆵ', + 'ᄚ' => 'ᄚ', + 'ᄆ' => 'ᄆ', + 'ᄇ' => 'ᄇ', + 'ᄈ' => 'ᄈ', + 'ᄡ' => 'ᄡ', + 'ᄉ' => 'ᄉ', + 'ᄊ' => 'ᄊ', + 'ᄋ' => 'ᄋ', + 'ᄌ' => 'ᄌ', + 'ᄍ' => 'ᄍ', + 'ᄎ' => 'ᄎ', + 'ᄏ' => 'ᄏ', + 'ᄐ' => 'ᄐ', + 'ᄑ' => 'ᄑ', + 'ᄒ' => 'ᄒ', + 'ᅡ' => 'ᅡ', + 'ᅢ' => 'ᅢ', + 'ᅣ' => 'ᅣ', + 'ᅤ' => 'ᅤ', + 'ᅥ' => 'ᅥ', + 'ᅦ' => 'ᅦ', + 'ᅧ' => 'ᅧ', + 'ᅨ' => 'ᅨ', + 'ᅩ' => 'ᅩ', + 'ᅪ' => 'ᅪ', + 'ᅫ' => 'ᅫ', + 'ᅬ' => 'ᅬ', + 'ᅭ' => 'ᅭ', + 'ᅮ' => 'ᅮ', + 'ᅯ' => 'ᅯ', + 'ᅰ' => 'ᅰ', + 'ᅱ' => 'ᅱ', + 'ᅲ' => 'ᅲ', + 'ᅳ' => 'ᅳ', + 'ᅴ' => 'ᅴ', + 'ᅵ' => 'ᅵ', + '¢' => '¢', + '£' => '£', + '¬' => '¬', + ' ̄' => ' ̄', + '¦' => '¦', + '¥' => '¥', + '₩' => '₩', + '│' => '│', + '←' => '←', + '↑' => '↑', + '→' => '→', + '↓' => '↓', + '■' => '■', + '○' => '○', + '𝐀' => 'A', + '𝐁' => 'B', + '𝐂' => 'C', + '𝐃' => 'D', + '𝐄' => 'E', + '𝐅' => 'F', + '𝐆' => 'G', + '𝐇' => 'H', + '𝐈' => 'I', + '𝐉' => 'J', + '𝐊' => 'K', + '𝐋' => 'L', + '𝐌' => 'M', + '𝐍' => 'N', + '𝐎' => 'O', + '𝐏' => 'P', + '𝐐' => 'Q', + '𝐑' => 'R', + '𝐒' => 'S', + '𝐓' => 'T', + '𝐔' => 'U', + '𝐕' => 'V', + '𝐖' => 'W', + '𝐗' => 'X', + '𝐘' => 'Y', + '𝐙' => 'Z', + '𝐚' => 'a', + '𝐛' => 'b', + '𝐜' => 'c', + '𝐝' => 'd', + '𝐞' => 'e', + '𝐟' => 'f', + '𝐠' => 'g', + '𝐡' => 'h', + '𝐢' => 'i', + '𝐣' => 'j', + '𝐤' => 'k', + '𝐥' => 'l', + '𝐦' => 'm', + '𝐧' => 'n', + '𝐨' => 'o', + '𝐩' => 'p', + '𝐪' => 'q', + '𝐫' => 'r', + '𝐬' => 's', + '𝐭' => 't', + '𝐮' => 'u', + '𝐯' => 'v', + '𝐰' => 'w', + '𝐱' => 'x', + '𝐲' => 'y', + '𝐳' => 'z', + '𝐴' => 'A', + '𝐵' => 'B', + '𝐶' => 'C', + '𝐷' => 'D', + '𝐸' => 'E', + '𝐹' => 'F', + '𝐺' => 'G', + '𝐻' => 'H', + '𝐼' => 'I', + '𝐽' => 'J', + '𝐾' => 'K', + '𝐿' => 'L', + '𝑀' => 'M', + '𝑁' => 'N', + '𝑂' => 'O', + '𝑃' => 'P', + '𝑄' => 'Q', + '𝑅' => 'R', + '𝑆' => 'S', + '𝑇' => 'T', + '𝑈' => 'U', + '𝑉' => 'V', + '𝑊' => 'W', + '𝑋' => 'X', + '𝑌' => 'Y', + '𝑍' => 'Z', + '𝑎' => 'a', + '𝑏' => 'b', + '𝑐' => 'c', + '𝑑' => 'd', + '𝑒' => 'e', + '𝑓' => 'f', + '𝑔' => 'g', + '𝑖' => 'i', + '𝑗' => 'j', + '𝑘' => 'k', + '𝑙' => 'l', + '𝑚' => 'm', + '𝑛' => 'n', + '𝑜' => 'o', + '𝑝' => 'p', + '𝑞' => 'q', + '𝑟' => 'r', + '𝑠' => 's', + '𝑡' => 't', + '𝑢' => 'u', + '𝑣' => 'v', + '𝑤' => 'w', + '𝑥' => 'x', + '𝑦' => 'y', + '𝑧' => 'z', + '𝑨' => 'A', + '𝑩' => 'B', + '𝑪' => 'C', + '𝑫' => 'D', + '𝑬' => 'E', + '𝑭' => 'F', + '𝑮' => 'G', + '𝑯' => 'H', + '𝑰' => 'I', + '𝑱' => 'J', + '𝑲' => 'K', + '𝑳' => 'L', + '𝑴' => 'M', + '𝑵' => 'N', + '𝑶' => 'O', + '𝑷' => 'P', + '𝑸' => 'Q', + '𝑹' => 'R', + '𝑺' => 'S', + '𝑻' => 'T', + '𝑼' => 'U', + '𝑽' => 'V', + '𝑾' => 'W', + '𝑿' => 'X', + '𝒀' => 'Y', + '𝒁' => 'Z', + '𝒂' => 'a', + '𝒃' => 'b', + '𝒄' => 'c', + '𝒅' => 'd', + '𝒆' => 'e', + '𝒇' => 'f', + '𝒈' => 'g', + '𝒉' => 'h', + '𝒊' => 'i', + '𝒋' => 'j', + '𝒌' => 'k', + '𝒍' => 'l', + '𝒎' => 'm', + '𝒏' => 'n', + '𝒐' => 'o', + '𝒑' => 'p', + '𝒒' => 'q', + '𝒓' => 'r', + '𝒔' => 's', + '𝒕' => 't', + '𝒖' => 'u', + '𝒗' => 'v', + '𝒘' => 'w', + '𝒙' => 'x', + '𝒚' => 'y', + '𝒛' => 'z', + '𝒜' => 'A', + '𝒞' => 'C', + '𝒟' => 'D', + '𝒢' => 'G', + '𝒥' => 'J', + '𝒦' => 'K', + '𝒩' => 'N', + '𝒪' => 'O', + '𝒫' => 'P', + '𝒬' => 'Q', + '𝒮' => 'S', + '𝒯' => 'T', + '𝒰' => 'U', + '𝒱' => 'V', + '𝒲' => 'W', + '𝒳' => 'X', + '𝒴' => 'Y', + '𝒵' => 'Z', + '𝒶' => 'a', + '𝒷' => 'b', + '𝒸' => 'c', + '𝒹' => 'd', + '𝒻' => 'f', + '𝒽' => 'h', + '𝒾' => 'i', + '𝒿' => 'j', + '𝓀' => 'k', + '𝓁' => 'l', + '𝓂' => 'm', + '𝓃' => 'n', + '𝓅' => 'p', + '𝓆' => 'q', + '𝓇' => 'r', + '𝓈' => 's', + '𝓉' => 't', + '𝓊' => 'u', + '𝓋' => 'v', + '𝓌' => 'w', + '𝓍' => 'x', + '𝓎' => 'y', + '𝓏' => 'z', + '𝓐' => 'A', + '𝓑' => 'B', + '𝓒' => 'C', + '𝓓' => 'D', + '𝓔' => 'E', + '𝓕' => 'F', + '𝓖' => 'G', + '𝓗' => 'H', + '𝓘' => 'I', + '𝓙' => 'J', + '𝓚' => 'K', + '𝓛' => 'L', + '𝓜' => 'M', + '𝓝' => 'N', + '𝓞' => 'O', + '𝓟' => 'P', + '𝓠' => 'Q', + '𝓡' => 'R', + '𝓢' => 'S', + '𝓣' => 'T', + '𝓤' => 'U', + '𝓥' => 'V', + '𝓦' => 'W', + '𝓧' => 'X', + '𝓨' => 'Y', + '𝓩' => 'Z', + '𝓪' => 'a', + '𝓫' => 'b', + '𝓬' => 'c', + '𝓭' => 'd', + '𝓮' => 'e', + '𝓯' => 'f', + '𝓰' => 'g', + '𝓱' => 'h', + '𝓲' => 'i', + '𝓳' => 'j', + '𝓴' => 'k', + '𝓵' => 'l', + '𝓶' => 'm', + '𝓷' => 'n', + '𝓸' => 'o', + '𝓹' => 'p', + '𝓺' => 'q', + '𝓻' => 'r', + '𝓼' => 's', + '𝓽' => 't', + '𝓾' => 'u', + '𝓿' => 'v', + '𝔀' => 'w', + '𝔁' => 'x', + '𝔂' => 'y', + '𝔃' => 'z', + '𝔄' => 'A', + '𝔅' => 'B', + '𝔇' => 'D', + '𝔈' => 'E', + '𝔉' => 'F', + '𝔊' => 'G', + '𝔍' => 'J', + '𝔎' => 'K', + '𝔏' => 'L', + '𝔐' => 'M', + '𝔑' => 'N', + '𝔒' => 'O', + '𝔓' => 'P', + '𝔔' => 'Q', + '𝔖' => 'S', + '𝔗' => 'T', + '𝔘' => 'U', + '𝔙' => 'V', + '𝔚' => 'W', + '𝔛' => 'X', + '𝔜' => 'Y', + '𝔞' => 'a', + '𝔟' => 'b', + '𝔠' => 'c', + '𝔡' => 'd', + '𝔢' => 'e', + '𝔣' => 'f', + '𝔤' => 'g', + '𝔥' => 'h', + '𝔦' => 'i', + '𝔧' => 'j', + '𝔨' => 'k', + '𝔩' => 'l', + '𝔪' => 'm', + '𝔫' => 'n', + '𝔬' => 'o', + '𝔭' => 'p', + '𝔮' => 'q', + '𝔯' => 'r', + '𝔰' => 's', + '𝔱' => 't', + '𝔲' => 'u', + '𝔳' => 'v', + '𝔴' => 'w', + '𝔵' => 'x', + '𝔶' => 'y', + '𝔷' => 'z', + '𝔸' => 'A', + '𝔹' => 'B', + '𝔻' => 'D', + '𝔼' => 'E', + '𝔽' => 'F', + '𝔾' => 'G', + '𝕀' => 'I', + '𝕁' => 'J', + '𝕂' => 'K', + '𝕃' => 'L', + '𝕄' => 'M', + '𝕆' => 'O', + '𝕊' => 'S', + '𝕋' => 'T', + '𝕌' => 'U', + '𝕍' => 'V', + '𝕎' => 'W', + '𝕏' => 'X', + '𝕐' => 'Y', + '𝕒' => 'a', + '𝕓' => 'b', + '𝕔' => 'c', + '𝕕' => 'd', + '𝕖' => 'e', + '𝕗' => 'f', + '𝕘' => 'g', + '𝕙' => 'h', + '𝕚' => 'i', + '𝕛' => 'j', + '𝕜' => 'k', + '𝕝' => 'l', + '𝕞' => 'm', + '𝕟' => 'n', + '𝕠' => 'o', + '𝕡' => 'p', + '𝕢' => 'q', + '𝕣' => 'r', + '𝕤' => 's', + '𝕥' => 't', + '𝕦' => 'u', + '𝕧' => 'v', + '𝕨' => 'w', + '𝕩' => 'x', + '𝕪' => 'y', + '𝕫' => 'z', + '𝕬' => 'A', + '𝕭' => 'B', + '𝕮' => 'C', + '𝕯' => 'D', + '𝕰' => 'E', + '𝕱' => 'F', + '𝕲' => 'G', + '𝕳' => 'H', + '𝕴' => 'I', + '𝕵' => 'J', + '𝕶' => 'K', + '𝕷' => 'L', + '𝕸' => 'M', + '𝕹' => 'N', + '𝕺' => 'O', + '𝕻' => 'P', + '𝕼' => 'Q', + '𝕽' => 'R', + '𝕾' => 'S', + '𝕿' => 'T', + '𝖀' => 'U', + '𝖁' => 'V', + '𝖂' => 'W', + '𝖃' => 'X', + '𝖄' => 'Y', + '𝖅' => 'Z', + '𝖆' => 'a', + '𝖇' => 'b', + '𝖈' => 'c', + '𝖉' => 'd', + '𝖊' => 'e', + '𝖋' => 'f', + '𝖌' => 'g', + '𝖍' => 'h', + '𝖎' => 'i', + '𝖏' => 'j', + '𝖐' => 'k', + '𝖑' => 'l', + '𝖒' => 'm', + '𝖓' => 'n', + '𝖔' => 'o', + '𝖕' => 'p', + '𝖖' => 'q', + '𝖗' => 'r', + '𝖘' => 's', + '𝖙' => 't', + '𝖚' => 'u', + '𝖛' => 'v', + '𝖜' => 'w', + '𝖝' => 'x', + '𝖞' => 'y', + '𝖟' => 'z', + '𝖠' => 'A', + '𝖡' => 'B', + '𝖢' => 'C', + '𝖣' => 'D', + '𝖤' => 'E', + '𝖥' => 'F', + '𝖦' => 'G', + '𝖧' => 'H', + '𝖨' => 'I', + '𝖩' => 'J', + '𝖪' => 'K', + '𝖫' => 'L', + '𝖬' => 'M', + '𝖭' => 'N', + '𝖮' => 'O', + '𝖯' => 'P', + '𝖰' => 'Q', + '𝖱' => 'R', + '𝖲' => 'S', + '𝖳' => 'T', + '𝖴' => 'U', + '𝖵' => 'V', + '𝖶' => 'W', + '𝖷' => 'X', + '𝖸' => 'Y', + '𝖹' => 'Z', + '𝖺' => 'a', + '𝖻' => 'b', + '𝖼' => 'c', + '𝖽' => 'd', + '𝖾' => 'e', + '𝖿' => 'f', + '𝗀' => 'g', + '𝗁' => 'h', + '𝗂' => 'i', + '𝗃' => 'j', + '𝗄' => 'k', + '𝗅' => 'l', + '𝗆' => 'm', + '𝗇' => 'n', + '𝗈' => 'o', + '𝗉' => 'p', + '𝗊' => 'q', + '𝗋' => 'r', + '𝗌' => 's', + '𝗍' => 't', + '𝗎' => 'u', + '𝗏' => 'v', + '𝗐' => 'w', + '𝗑' => 'x', + '𝗒' => 'y', + '𝗓' => 'z', + '𝗔' => 'A', + '𝗕' => 'B', + '𝗖' => 'C', + '𝗗' => 'D', + '𝗘' => 'E', + '𝗙' => 'F', + '𝗚' => 'G', + '𝗛' => 'H', + '𝗜' => 'I', + '𝗝' => 'J', + '𝗞' => 'K', + '𝗟' => 'L', + '𝗠' => 'M', + '𝗡' => 'N', + '𝗢' => 'O', + '𝗣' => 'P', + '𝗤' => 'Q', + '𝗥' => 'R', + '𝗦' => 'S', + '𝗧' => 'T', + '𝗨' => 'U', + '𝗩' => 'V', + '𝗪' => 'W', + '𝗫' => 'X', + '𝗬' => 'Y', + '𝗭' => 'Z', + '𝗮' => 'a', + '𝗯' => 'b', + '𝗰' => 'c', + '𝗱' => 'd', + '𝗲' => 'e', + '𝗳' => 'f', + '𝗴' => 'g', + '𝗵' => 'h', + '𝗶' => 'i', + '𝗷' => 'j', + '𝗸' => 'k', + '𝗹' => 'l', + '𝗺' => 'm', + '𝗻' => 'n', + '𝗼' => 'o', + '𝗽' => 'p', + '𝗾' => 'q', + '𝗿' => 'r', + '𝘀' => 's', + '𝘁' => 't', + '𝘂' => 'u', + '𝘃' => 'v', + '𝘄' => 'w', + '𝘅' => 'x', + '𝘆' => 'y', + '𝘇' => 'z', + '𝘈' => 'A', + '𝘉' => 'B', + '𝘊' => 'C', + '𝘋' => 'D', + '𝘌' => 'E', + '𝘍' => 'F', + '𝘎' => 'G', + '𝘏' => 'H', + '𝘐' => 'I', + '𝘑' => 'J', + '𝘒' => 'K', + '𝘓' => 'L', + '𝘔' => 'M', + '𝘕' => 'N', + '𝘖' => 'O', + '𝘗' => 'P', + '𝘘' => 'Q', + '𝘙' => 'R', + '𝘚' => 'S', + '𝘛' => 'T', + '𝘜' => 'U', + '𝘝' => 'V', + '𝘞' => 'W', + '𝘟' => 'X', + '𝘠' => 'Y', + '𝘡' => 'Z', + '𝘢' => 'a', + '𝘣' => 'b', + '𝘤' => 'c', + '𝘥' => 'd', + '𝘦' => 'e', + '𝘧' => 'f', + '𝘨' => 'g', + '𝘩' => 'h', + '𝘪' => 'i', + '𝘫' => 'j', + '𝘬' => 'k', + '𝘭' => 'l', + '𝘮' => 'm', + '𝘯' => 'n', + '𝘰' => 'o', + '𝘱' => 'p', + '𝘲' => 'q', + '𝘳' => 'r', + '𝘴' => 's', + '𝘵' => 't', + '𝘶' => 'u', + '𝘷' => 'v', + '𝘸' => 'w', + '𝘹' => 'x', + '𝘺' => 'y', + '𝘻' => 'z', + '𝘼' => 'A', + '𝘽' => 'B', + '𝘾' => 'C', + '𝘿' => 'D', + '𝙀' => 'E', + '𝙁' => 'F', + '𝙂' => 'G', + '𝙃' => 'H', + '𝙄' => 'I', + '𝙅' => 'J', + '𝙆' => 'K', + '𝙇' => 'L', + '𝙈' => 'M', + '𝙉' => 'N', + '𝙊' => 'O', + '𝙋' => 'P', + '𝙌' => 'Q', + '𝙍' => 'R', + '𝙎' => 'S', + '𝙏' => 'T', + '𝙐' => 'U', + '𝙑' => 'V', + '𝙒' => 'W', + '𝙓' => 'X', + '𝙔' => 'Y', + '𝙕' => 'Z', + '𝙖' => 'a', + '𝙗' => 'b', + '𝙘' => 'c', + '𝙙' => 'd', + '𝙚' => 'e', + '𝙛' => 'f', + '𝙜' => 'g', + '𝙝' => 'h', + '𝙞' => 'i', + '𝙟' => 'j', + '𝙠' => 'k', + '𝙡' => 'l', + '𝙢' => 'm', + '𝙣' => 'n', + '𝙤' => 'o', + '𝙥' => 'p', + '𝙦' => 'q', + '𝙧' => 'r', + '𝙨' => 's', + '𝙩' => 't', + '𝙪' => 'u', + '𝙫' => 'v', + '𝙬' => 'w', + '𝙭' => 'x', + '𝙮' => 'y', + '𝙯' => 'z', + '𝙰' => 'A', + '𝙱' => 'B', + '𝙲' => 'C', + '𝙳' => 'D', + '𝙴' => 'E', + '𝙵' => 'F', + '𝙶' => 'G', + '𝙷' => 'H', + '𝙸' => 'I', + '𝙹' => 'J', + '𝙺' => 'K', + '𝙻' => 'L', + '𝙼' => 'M', + '𝙽' => 'N', + '𝙾' => 'O', + '𝙿' => 'P', + '𝚀' => 'Q', + '𝚁' => 'R', + '𝚂' => 'S', + '𝚃' => 'T', + '𝚄' => 'U', + '𝚅' => 'V', + '𝚆' => 'W', + '𝚇' => 'X', + '𝚈' => 'Y', + '𝚉' => 'Z', + '𝚊' => 'a', + '𝚋' => 'b', + '𝚌' => 'c', + '𝚍' => 'd', + '𝚎' => 'e', + '𝚏' => 'f', + '𝚐' => 'g', + '𝚑' => 'h', + '𝚒' => 'i', + '𝚓' => 'j', + '𝚔' => 'k', + '𝚕' => 'l', + '𝚖' => 'm', + '𝚗' => 'n', + '𝚘' => 'o', + '𝚙' => 'p', + '𝚚' => 'q', + '𝚛' => 'r', + '𝚜' => 's', + '𝚝' => 't', + '𝚞' => 'u', + '𝚟' => 'v', + '𝚠' => 'w', + '𝚡' => 'x', + '𝚢' => 'y', + '𝚣' => 'z', + '𝚤' => 'ı', + '𝚥' => 'ȷ', + '𝚨' => 'Α', + '𝚩' => 'Β', + '𝚪' => 'Γ', + '𝚫' => 'Δ', + '𝚬' => 'Ε', + '𝚭' => 'Ζ', + '𝚮' => 'Η', + '𝚯' => 'Θ', + '𝚰' => 'Ι', + '𝚱' => 'Κ', + '𝚲' => 'Λ', + '𝚳' => 'Μ', + '𝚴' => 'Ν', + '𝚵' => 'Ξ', + '𝚶' => 'Ο', + '𝚷' => 'Π', + '𝚸' => 'Ρ', + '𝚹' => 'Θ', + '𝚺' => 'Σ', + '𝚻' => 'Τ', + '𝚼' => 'Υ', + '𝚽' => 'Φ', + '𝚾' => 'Χ', + '𝚿' => 'Ψ', + '𝛀' => 'Ω', + '𝛁' => '∇', + '𝛂' => 'α', + '𝛃' => 'β', + '𝛄' => 'γ', + '𝛅' => 'δ', + '𝛆' => 'ε', + '𝛇' => 'ζ', + '𝛈' => 'η', + '𝛉' => 'θ', + '𝛊' => 'ι', + '𝛋' => 'κ', + '𝛌' => 'λ', + '𝛍' => 'μ', + '𝛎' => 'ν', + '𝛏' => 'ξ', + '𝛐' => 'ο', + '𝛑' => 'π', + '𝛒' => 'ρ', + '𝛓' => 'ς', + '𝛔' => 'σ', + '𝛕' => 'τ', + '𝛖' => 'υ', + '𝛗' => 'φ', + '𝛘' => 'χ', + '𝛙' => 'ψ', + '𝛚' => 'ω', + '𝛛' => '∂', + '𝛜' => 'ε', + '𝛝' => 'θ', + '𝛞' => 'κ', + '𝛟' => 'φ', + '𝛠' => 'ρ', + '𝛡' => 'π', + '𝛢' => 'Α', + '𝛣' => 'Β', + '𝛤' => 'Γ', + '𝛥' => 'Δ', + '𝛦' => 'Ε', + '𝛧' => 'Ζ', + '𝛨' => 'Η', + '𝛩' => 'Θ', + '𝛪' => 'Ι', + '𝛫' => 'Κ', + '𝛬' => 'Λ', + '𝛭' => 'Μ', + '𝛮' => 'Ν', + '𝛯' => 'Ξ', + '𝛰' => 'Ο', + '𝛱' => 'Π', + '𝛲' => 'Ρ', + '𝛳' => 'Θ', + '𝛴' => 'Σ', + '𝛵' => 'Τ', + '𝛶' => 'Υ', + '𝛷' => 'Φ', + '𝛸' => 'Χ', + '𝛹' => 'Ψ', + '𝛺' => 'Ω', + '𝛻' => '∇', + '𝛼' => 'α', + '𝛽' => 'β', + '𝛾' => 'γ', + '𝛿' => 'δ', + '𝜀' => 'ε', + '𝜁' => 'ζ', + '𝜂' => 'η', + '𝜃' => 'θ', + '𝜄' => 'ι', + '𝜅' => 'κ', + '𝜆' => 'λ', + '𝜇' => 'μ', + '𝜈' => 'ν', + '𝜉' => 'ξ', + '𝜊' => 'ο', + '𝜋' => 'π', + '𝜌' => 'ρ', + '𝜍' => 'ς', + '𝜎' => 'σ', + '𝜏' => 'τ', + '𝜐' => 'υ', + '𝜑' => 'φ', + '𝜒' => 'χ', + '𝜓' => 'ψ', + '𝜔' => 'ω', + '𝜕' => '∂', + '𝜖' => 'ε', + '𝜗' => 'θ', + '𝜘' => 'κ', + '𝜙' => 'φ', + '𝜚' => 'ρ', + '𝜛' => 'π', + '𝜜' => 'Α', + '𝜝' => 'Β', + '𝜞' => 'Γ', + '𝜟' => 'Δ', + '𝜠' => 'Ε', + '𝜡' => 'Ζ', + '𝜢' => 'Η', + '𝜣' => 'Θ', + '𝜤' => 'Ι', + '𝜥' => 'Κ', + '𝜦' => 'Λ', + '𝜧' => 'Μ', + '𝜨' => 'Ν', + '𝜩' => 'Ξ', + '𝜪' => 'Ο', + '𝜫' => 'Π', + '𝜬' => 'Ρ', + '𝜭' => 'Θ', + '𝜮' => 'Σ', + '𝜯' => 'Τ', + '𝜰' => 'Υ', + '𝜱' => 'Φ', + '𝜲' => 'Χ', + '𝜳' => 'Ψ', + '𝜴' => 'Ω', + '𝜵' => '∇', + '𝜶' => 'α', + '𝜷' => 'β', + '𝜸' => 'γ', + '𝜹' => 'δ', + '𝜺' => 'ε', + '𝜻' => 'ζ', + '𝜼' => 'η', + '𝜽' => 'θ', + '𝜾' => 'ι', + '𝜿' => 'κ', + '𝝀' => 'λ', + '𝝁' => 'μ', + '𝝂' => 'ν', + '𝝃' => 'ξ', + '𝝄' => 'ο', + '𝝅' => 'π', + '𝝆' => 'ρ', + '𝝇' => 'ς', + '𝝈' => 'σ', + '𝝉' => 'τ', + '𝝊' => 'υ', + '𝝋' => 'φ', + '𝝌' => 'χ', + '𝝍' => 'ψ', + '𝝎' => 'ω', + '𝝏' => '∂', + '𝝐' => 'ε', + '𝝑' => 'θ', + '𝝒' => 'κ', + '𝝓' => 'φ', + '𝝔' => 'ρ', + '𝝕' => 'π', + '𝝖' => 'Α', + '𝝗' => 'Β', + '𝝘' => 'Γ', + '𝝙' => 'Δ', + '𝝚' => 'Ε', + '𝝛' => 'Ζ', + '𝝜' => 'Η', + '𝝝' => 'Θ', + '𝝞' => 'Ι', + '𝝟' => 'Κ', + '𝝠' => 'Λ', + '𝝡' => 'Μ', + '𝝢' => 'Ν', + '𝝣' => 'Ξ', + '𝝤' => 'Ο', + '𝝥' => 'Π', + '𝝦' => 'Ρ', + '𝝧' => 'Θ', + '𝝨' => 'Σ', + '𝝩' => 'Τ', + '𝝪' => 'Υ', + '𝝫' => 'Φ', + '𝝬' => 'Χ', + '𝝭' => 'Ψ', + '𝝮' => 'Ω', + '𝝯' => '∇', + '𝝰' => 'α', + '𝝱' => 'β', + '𝝲' => 'γ', + '𝝳' => 'δ', + '𝝴' => 'ε', + '𝝵' => 'ζ', + '𝝶' => 'η', + '𝝷' => 'θ', + '𝝸' => 'ι', + '𝝹' => 'κ', + '𝝺' => 'λ', + '𝝻' => 'μ', + '𝝼' => 'ν', + '𝝽' => 'ξ', + '𝝾' => 'ο', + '𝝿' => 'π', + '𝞀' => 'ρ', + '𝞁' => 'ς', + '𝞂' => 'σ', + '𝞃' => 'τ', + '𝞄' => 'υ', + '𝞅' => 'φ', + '𝞆' => 'χ', + '𝞇' => 'ψ', + '𝞈' => 'ω', + '𝞉' => '∂', + '𝞊' => 'ε', + '𝞋' => 'θ', + '𝞌' => 'κ', + '𝞍' => 'φ', + '𝞎' => 'ρ', + '𝞏' => 'π', + '𝞐' => 'Α', + '𝞑' => 'Β', + '𝞒' => 'Γ', + '𝞓' => 'Δ', + '𝞔' => 'Ε', + '𝞕' => 'Ζ', + '𝞖' => 'Η', + '𝞗' => 'Θ', + '𝞘' => 'Ι', + '𝞙' => 'Κ', + '𝞚' => 'Λ', + '𝞛' => 'Μ', + '𝞜' => 'Ν', + '𝞝' => 'Ξ', + '𝞞' => 'Ο', + '𝞟' => 'Π', + '𝞠' => 'Ρ', + '𝞡' => 'Θ', + '𝞢' => 'Σ', + '𝞣' => 'Τ', + '𝞤' => 'Υ', + '𝞥' => 'Φ', + '𝞦' => 'Χ', + '𝞧' => 'Ψ', + '𝞨' => 'Ω', + '𝞩' => '∇', + '𝞪' => 'α', + '𝞫' => 'β', + '𝞬' => 'γ', + '𝞭' => 'δ', + '𝞮' => 'ε', + '𝞯' => 'ζ', + '𝞰' => 'η', + '𝞱' => 'θ', + '𝞲' => 'ι', + '𝞳' => 'κ', + '𝞴' => 'λ', + '𝞵' => 'μ', + '𝞶' => 'ν', + '𝞷' => 'ξ', + '𝞸' => 'ο', + '𝞹' => 'π', + '𝞺' => 'ρ', + '𝞻' => 'ς', + '𝞼' => 'σ', + '𝞽' => 'τ', + '𝞾' => 'υ', + '𝞿' => 'φ', + '𝟀' => 'χ', + '𝟁' => 'ψ', + '𝟂' => 'ω', + '𝟃' => '∂', + '𝟄' => 'ε', + '𝟅' => 'θ', + '𝟆' => 'κ', + '𝟇' => 'φ', + '𝟈' => 'ρ', + '𝟉' => 'π', + '𝟊' => 'Ϝ', + '𝟋' => 'ϝ', + '𝟎' => '0', + '𝟏' => '1', + '𝟐' => '2', + '𝟑' => '3', + '𝟒' => '4', + '𝟓' => '5', + '𝟔' => '6', + '𝟕' => '7', + '𝟖' => '8', + '𝟗' => '9', + '𝟘' => '0', + '𝟙' => '1', + '𝟚' => '2', + '𝟛' => '3', + '𝟜' => '4', + '𝟝' => '5', + '𝟞' => '6', + '𝟟' => '7', + '𝟠' => '8', + '𝟡' => '9', + '𝟢' => '0', + '𝟣' => '1', + '𝟤' => '2', + '𝟥' => '3', + '𝟦' => '4', + '𝟧' => '5', + '𝟨' => '6', + '𝟩' => '7', + '𝟪' => '8', + '𝟫' => '9', + '𝟬' => '0', + '𝟭' => '1', + '𝟮' => '2', + '𝟯' => '3', + '𝟰' => '4', + '𝟱' => '5', + '𝟲' => '6', + '𝟳' => '7', + '𝟴' => '8', + '𝟵' => '9', + '𝟶' => '0', + '𝟷' => '1', + '𝟸' => '2', + '𝟹' => '3', + '𝟺' => '4', + '𝟻' => '5', + '𝟼' => '6', + '𝟽' => '7', + '𝟾' => '8', + '𝟿' => '9', + '𞸀' => 'ا', + '𞸁' => 'ب', + '𞸂' => 'ج', + '𞸃' => 'د', + '𞸅' => 'و', + '𞸆' => 'ز', + '𞸇' => 'ح', + '𞸈' => 'ط', + '𞸉' => 'ي', + '𞸊' => 'ك', + '𞸋' => 'ل', + '𞸌' => 'م', + '𞸍' => 'ن', + '𞸎' => 'س', + '𞸏' => 'ع', + '𞸐' => 'ف', + '𞸑' => 'ص', + '𞸒' => 'ق', + '𞸓' => 'ر', + '𞸔' => 'ش', + '𞸕' => 'ت', + '𞸖' => 'ث', + '𞸗' => 'خ', + '𞸘' => 'ذ', + '𞸙' => 'ض', + '𞸚' => 'ظ', + '𞸛' => 'غ', + '𞸜' => 'ٮ', + '𞸝' => 'ں', + '𞸞' => 'ڡ', + '𞸟' => 'ٯ', + '𞸡' => 'ب', + '𞸢' => 'ج', + '𞸤' => 'ه', + '𞸧' => 'ح', + '𞸩' => 'ي', + '𞸪' => 'ك', + '𞸫' => 'ل', + '𞸬' => 'م', + '𞸭' => 'ن', + '𞸮' => 'س', + '𞸯' => 'ع', + '𞸰' => 'ف', + '𞸱' => 'ص', + '𞸲' => 'ق', + '𞸴' => 'ش', + '𞸵' => 'ت', + '𞸶' => 'ث', + '𞸷' => 'خ', + '𞸹' => 'ض', + '𞸻' => 'غ', + '𞹂' => 'ج', + '𞹇' => 'ح', + '𞹉' => 'ي', + '𞹋' => 'ل', + '𞹍' => 'ن', + '𞹎' => 'س', + '𞹏' => 'ع', + '𞹑' => 'ص', + '𞹒' => 'ق', + '𞹔' => 'ش', + '𞹗' => 'خ', + '𞹙' => 'ض', + '𞹛' => 'غ', + '𞹝' => 'ں', + '𞹟' => 'ٯ', + '𞹡' => 'ب', + '𞹢' => 'ج', + '𞹤' => 'ه', + '𞹧' => 'ح', + '𞹨' => 'ط', + '𞹩' => 'ي', + '𞹪' => 'ك', + '𞹬' => 'م', + '𞹭' => 'ن', + '𞹮' => 'س', + '𞹯' => 'ع', + '𞹰' => 'ف', + '𞹱' => 'ص', + '𞹲' => 'ق', + '𞹴' => 'ش', + '𞹵' => 'ت', + '𞹶' => 'ث', + '𞹷' => 'خ', + '𞹹' => 'ض', + '𞹺' => 'ظ', + '𞹻' => 'غ', + '𞹼' => 'ٮ', + '𞹾' => 'ڡ', + '𞺀' => 'ا', + '𞺁' => 'ب', + '𞺂' => 'ج', + '𞺃' => 'د', + '𞺄' => 'ه', + '𞺅' => 'و', + '𞺆' => 'ز', + '𞺇' => 'ح', + '𞺈' => 'ط', + '𞺉' => 'ي', + '𞺋' => 'ل', + '𞺌' => 'م', + '𞺍' => 'ن', + '𞺎' => 'س', + '𞺏' => 'ع', + '𞺐' => 'ف', + '𞺑' => 'ص', + '𞺒' => 'ق', + '𞺓' => 'ر', + '𞺔' => 'ش', + '𞺕' => 'ت', + '𞺖' => 'ث', + '𞺗' => 'خ', + '𞺘' => 'ذ', + '𞺙' => 'ض', + '𞺚' => 'ظ', + '𞺛' => 'غ', + '𞺡' => 'ب', + '𞺢' => 'ج', + '𞺣' => 'د', + '𞺥' => 'و', + '𞺦' => 'ز', + '𞺧' => 'ح', + '𞺨' => 'ط', + '𞺩' => 'ي', + '𞺫' => 'ل', + '𞺬' => 'م', + '𞺭' => 'ن', + '𞺮' => 'س', + '𞺯' => 'ع', + '𞺰' => 'ف', + '𞺱' => 'ص', + '𞺲' => 'ق', + '𞺳' => 'ر', + '𞺴' => 'ش', + '𞺵' => 'ت', + '𞺶' => 'ث', + '𞺷' => 'خ', + '𞺸' => 'ذ', + '𞺹' => 'ض', + '𞺺' => 'ظ', + '𞺻' => 'غ', + '🄀' => '0.', + '🄁' => '0,', + '🄂' => '1,', + '🄃' => '2,', + '🄄' => '3,', + '🄅' => '4,', + '🄆' => '5,', + '🄇' => '6,', + '🄈' => '7,', + '🄉' => '8,', + '🄊' => '9,', + '🄐' => '(A)', + '🄑' => '(B)', + '🄒' => '(C)', + '🄓' => '(D)', + '🄔' => '(E)', + '🄕' => '(F)', + '🄖' => '(G)', + '🄗' => '(H)', + '🄘' => '(I)', + '🄙' => '(J)', + '🄚' => '(K)', + '🄛' => '(L)', + '🄜' => '(M)', + '🄝' => '(N)', + '🄞' => '(O)', + '🄟' => '(P)', + '🄠' => '(Q)', + '🄡' => '(R)', + '🄢' => '(S)', + '🄣' => '(T)', + '🄤' => '(U)', + '🄥' => '(V)', + '🄦' => '(W)', + '🄧' => '(X)', + '🄨' => '(Y)', + '🄩' => '(Z)', + '🄪' => '〔S〕', + '🄫' => 'C', + '🄬' => 'R', + '🄭' => 'CD', + '🄮' => 'WZ', + '🄰' => 'A', + '🄱' => 'B', + '🄲' => 'C', + '🄳' => 'D', + '🄴' => 'E', + '🄵' => 'F', + '🄶' => 'G', + '🄷' => 'H', + '🄸' => 'I', + '🄹' => 'J', + '🄺' => 'K', + '🄻' => 'L', + '🄼' => 'M', + '🄽' => 'N', + '🄾' => 'O', + '🄿' => 'P', + '🅀' => 'Q', + '🅁' => 'R', + '🅂' => 'S', + '🅃' => 'T', + '🅄' => 'U', + '🅅' => 'V', + '🅆' => 'W', + '🅇' => 'X', + '🅈' => 'Y', + '🅉' => 'Z', + '🅊' => 'HV', + '🅋' => 'MV', + '🅌' => 'SD', + '🅍' => 'SS', + '🅎' => 'PPV', + '🅏' => 'WC', + '🅪' => 'MC', + '🅫' => 'MD', + '🅬' => 'MR', + '🆐' => 'DJ', + '🈀' => 'ほか', + '🈁' => 'ココ', + '🈂' => 'サ', + '🈐' => '手', + '🈑' => '字', + '🈒' => '双', + '🈓' => 'デ', + '🈔' => '二', + '🈕' => '多', + '🈖' => '解', + '🈗' => '天', + '🈘' => '交', + '🈙' => '映', + '🈚' => '無', + '🈛' => '料', + '🈜' => '前', + '🈝' => '後', + '🈞' => '再', + '🈟' => '新', + '🈠' => '初', + '🈡' => '終', + '🈢' => '生', + '🈣' => '販', + '🈤' => '声', + '🈥' => '吹', + '🈦' => '演', + '🈧' => '投', + '🈨' => '捕', + '🈩' => '一', + '🈪' => '三', + '🈫' => '遊', + '🈬' => '左', + '🈭' => '中', + '🈮' => '右', + '🈯' => '指', + '🈰' => '走', + '🈱' => '打', + '🈲' => '禁', + '🈳' => '空', + '🈴' => '合', + '🈵' => '満', + '🈶' => '有', + '🈷' => '月', + '🈸' => '申', + '🈹' => '割', + '🈺' => '営', + '🈻' => '配', + '🉀' => '〔本〕', + '🉁' => '〔三〕', + '🉂' => '〔二〕', + '🉃' => '〔安〕', + '🉄' => '〔点〕', + '🉅' => '〔打〕', + '🉆' => '〔盗〕', + '🉇' => '〔勝〕', + '🉈' => '〔敗〕', + '🉐' => '得', + '🉑' => '可', + '🯰' => '0', + '🯱' => '1', + '🯲' => '2', + '🯳' => '3', + '🯴' => '4', + '🯵' => '5', + '🯶' => '6', + '🯷' => '7', + '🯸' => '8', + '🯹' => '9', +); diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/bootstrap.php b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/bootstrap.php new file mode 100644 index 00000000..3608e5c0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/bootstrap.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Intl\Normalizer as p; + +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + +if (!function_exists('normalizer_is_normalized')) { + function normalizer_is_normalized($string, $form = p\Normalizer::FORM_C) { return p\Normalizer::isNormalized($string, $form); } +} +if (!function_exists('normalizer_normalize')) { + function normalizer_normalize($string, $form = p\Normalizer::FORM_C) { return p\Normalizer::normalize($string, $form); } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/bootstrap80.php b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/bootstrap80.php new file mode 100644 index 00000000..e36d1a94 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/bootstrap80.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Intl\Normalizer as p; + +if (!function_exists('normalizer_is_normalized')) { + function normalizer_is_normalized(?string $string, ?int $form = p\Normalizer::FORM_C): bool { return p\Normalizer::isNormalized((string) $string, (int) $form); } +} +if (!function_exists('normalizer_normalize')) { + function normalizer_normalize(?string $string, ?int $form = p\Normalizer::FORM_C): string|false { return p\Normalizer::normalize((string) $string, (int) $form); } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/composer.json b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/composer.json new file mode 100644 index 00000000..2c4de2c8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-intl-normalizer/composer.json @@ -0,0 +1,39 @@ +{ + "name": "symfony/polyfill-intl-normalizer", + "type": "library", + "description": "Symfony polyfill for intl's Normalizer class and related functions", + "keywords": ["polyfill", "shim", "compatibility", "portable", "intl", "normalizer"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Intl\\Normalizer\\": "" }, + "files": [ "bootstrap.php" ], + "classmap": [ "Resources/stubs" ] + }, + "suggest": { + "ext-intl": "For best performance" + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/LICENSE b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/LICENSE new file mode 100644 index 00000000..6e3afce6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/Mbstring.php b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/Mbstring.php new file mode 100644 index 00000000..2e0b9694 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/Mbstring.php @@ -0,0 +1,947 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Mbstring; + +/** + * Partial mbstring implementation in PHP, iconv based, UTF-8 centric. + * + * Implemented: + * - mb_chr - Returns a specific character from its Unicode code point + * - mb_convert_encoding - Convert character encoding + * - mb_convert_variables - Convert character code in variable(s) + * - mb_decode_mimeheader - Decode string in MIME header field + * - mb_encode_mimeheader - Encode string for MIME header XXX NATIVE IMPLEMENTATION IS REALLY BUGGED + * - mb_decode_numericentity - Decode HTML numeric string reference to character + * - mb_encode_numericentity - Encode character to HTML numeric string reference + * - mb_convert_case - Perform case folding on a string + * - mb_detect_encoding - Detect character encoding + * - mb_get_info - Get internal settings of mbstring + * - mb_http_input - Detect HTTP input character encoding + * - mb_http_output - Set/Get HTTP output character encoding + * - mb_internal_encoding - Set/Get internal character encoding + * - mb_list_encodings - Returns an array of all supported encodings + * - mb_ord - Returns the Unicode code point of a character + * - mb_output_handler - Callback function converts character encoding in output buffer + * - mb_scrub - Replaces ill-formed byte sequences with substitute characters + * - mb_strlen - Get string length + * - mb_strpos - Find position of first occurrence of string in a string + * - mb_strrpos - Find position of last occurrence of a string in a string + * - mb_str_split - Convert a string to an array + * - mb_strtolower - Make a string lowercase + * - mb_strtoupper - Make a string uppercase + * - mb_substitute_character - Set/Get substitution character + * - mb_substr - Get part of string + * - mb_stripos - Finds position of first occurrence of a string within another, case insensitive + * - mb_stristr - Finds first occurrence of a string within another, case insensitive + * - mb_strrchr - Finds the last occurrence of a character in a string within another + * - mb_strrichr - Finds the last occurrence of a character in a string within another, case insensitive + * - mb_strripos - Finds position of last occurrence of a string within another, case insensitive + * - mb_strstr - Finds first occurrence of a string within another + * - mb_strwidth - Return width of string + * - mb_substr_count - Count the number of substring occurrences + * + * Not implemented: + * - mb_convert_kana - Convert "kana" one from another ("zen-kaku", "han-kaku" and more) + * - mb_ereg_* - Regular expression with multibyte support + * - mb_parse_str - Parse GET/POST/COOKIE data and set global variable + * - mb_preferred_mime_name - Get MIME charset string + * - mb_regex_encoding - Returns current encoding for multibyte regex as string + * - mb_regex_set_options - Set/Get the default options for mbregex functions + * - mb_send_mail - Send encoded mail + * - mb_split - Split multibyte string using regular expression + * - mb_strcut - Get part of string + * - mb_strimwidth - Get truncated string with specified width + * + * @author Nicolas Grekas + * + * @internal + */ +final class Mbstring +{ + public const MB_CASE_FOLD = \PHP_INT_MAX; + + private const SIMPLE_CASE_FOLD = [ + ['µ', 'ſ', "\xCD\x85", 'ς', "\xCF\x90", "\xCF\x91", "\xCF\x95", "\xCF\x96", "\xCF\xB0", "\xCF\xB1", "\xCF\xB5", "\xE1\xBA\x9B", "\xE1\xBE\xBE"], + ['μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', "\xE1\xB9\xA1", 'ι'], + ]; + + private static $encodingList = ['ASCII', 'UTF-8']; + private static $language = 'neutral'; + private static $internalEncoding = 'UTF-8'; + + public static function mb_convert_encoding($s, $toEncoding, $fromEncoding = null) + { + if (\is_array($fromEncoding) || (null !== $fromEncoding && false !== strpos($fromEncoding, ','))) { + $fromEncoding = self::mb_detect_encoding($s, $fromEncoding); + } else { + $fromEncoding = self::getEncoding($fromEncoding); + } + + $toEncoding = self::getEncoding($toEncoding); + + if ('BASE64' === $fromEncoding) { + $s = base64_decode($s); + $fromEncoding = $toEncoding; + } + + if ('BASE64' === $toEncoding) { + return base64_encode($s); + } + + if ('HTML-ENTITIES' === $toEncoding || 'HTML' === $toEncoding) { + if ('HTML-ENTITIES' === $fromEncoding || 'HTML' === $fromEncoding) { + $fromEncoding = 'Windows-1252'; + } + if ('UTF-8' !== $fromEncoding) { + $s = iconv($fromEncoding, 'UTF-8//IGNORE', $s); + } + + return preg_replace_callback('/[\x80-\xFF]+/', [__CLASS__, 'html_encoding_callback'], $s); + } + + if ('HTML-ENTITIES' === $fromEncoding) { + $s = html_entity_decode($s, \ENT_COMPAT, 'UTF-8'); + $fromEncoding = 'UTF-8'; + } + + return iconv($fromEncoding, $toEncoding.'//IGNORE', $s); + } + + public static function mb_convert_variables($toEncoding, $fromEncoding, &...$vars) + { + $ok = true; + array_walk_recursive($vars, function (&$v) use (&$ok, $toEncoding, $fromEncoding) { + if (false === $v = self::mb_convert_encoding($v, $toEncoding, $fromEncoding)) { + $ok = false; + } + }); + + return $ok ? $fromEncoding : false; + } + + public static function mb_decode_mimeheader($s) + { + return iconv_mime_decode($s, 2, self::$internalEncoding); + } + + public static function mb_encode_mimeheader($s, $charset = null, $transferEncoding = null, $linefeed = null, $indent = null) + { + trigger_error('mb_encode_mimeheader() is bugged. Please use iconv_mime_encode() instead', \E_USER_WARNING); + } + + public static function mb_decode_numericentity($s, $convmap, $encoding = null) + { + if (null !== $s && !\is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) { + trigger_error('mb_decode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return null; + } + + if (!\is_array($convmap) || (80000 > \PHP_VERSION_ID && !$convmap)) { + return false; + } + + if (null !== $encoding && !\is_scalar($encoding)) { + trigger_error('mb_decode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return ''; // Instead of null (cf. mb_encode_numericentity). + } + + $s = (string) $s; + if ('' === $s) { + return ''; + } + + $encoding = self::getEncoding($encoding); + + if ('UTF-8' === $encoding) { + $encoding = null; + if (!preg_match('//u', $s)) { + $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s); + } + } else { + $s = iconv($encoding, 'UTF-8//IGNORE', $s); + } + + $cnt = floor(\count($convmap) / 4) * 4; + + for ($i = 0; $i < $cnt; $i += 4) { + // collector_decode_htmlnumericentity ignores $convmap[$i + 3] + $convmap[$i] += $convmap[$i + 2]; + $convmap[$i + 1] += $convmap[$i + 2]; + } + + $s = preg_replace_callback('/&#(?:0*([0-9]+)|x0*([0-9a-fA-F]+))(?!&);?/', function (array $m) use ($cnt, $convmap) { + $c = isset($m[2]) ? (int) hexdec($m[2]) : $m[1]; + for ($i = 0; $i < $cnt; $i += 4) { + if ($c >= $convmap[$i] && $c <= $convmap[$i + 1]) { + return self::mb_chr($c - $convmap[$i + 2]); + } + } + + return $m[0]; + }, $s); + + if (null === $encoding) { + return $s; + } + + return iconv('UTF-8', $encoding.'//IGNORE', $s); + } + + public static function mb_encode_numericentity($s, $convmap, $encoding = null, $is_hex = false) + { + if (null !== $s && !\is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) { + trigger_error('mb_encode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return null; + } + + if (!\is_array($convmap) || (80000 > \PHP_VERSION_ID && !$convmap)) { + return false; + } + + if (null !== $encoding && !\is_scalar($encoding)) { + trigger_error('mb_encode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return null; // Instead of '' (cf. mb_decode_numericentity). + } + + if (null !== $is_hex && !\is_scalar($is_hex)) { + trigger_error('mb_encode_numericentity() expects parameter 4 to be boolean, '.\gettype($s).' given', \E_USER_WARNING); + + return null; + } + + $s = (string) $s; + if ('' === $s) { + return ''; + } + + $encoding = self::getEncoding($encoding); + + if ('UTF-8' === $encoding) { + $encoding = null; + if (!preg_match('//u', $s)) { + $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s); + } + } else { + $s = iconv($encoding, 'UTF-8//IGNORE', $s); + } + + static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4]; + + $cnt = floor(\count($convmap) / 4) * 4; + $i = 0; + $len = \strlen($s); + $result = ''; + + while ($i < $len) { + $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"]; + $uchr = substr($s, $i, $ulen); + $i += $ulen; + $c = self::mb_ord($uchr); + + for ($j = 0; $j < $cnt; $j += 4) { + if ($c >= $convmap[$j] && $c <= $convmap[$j + 1]) { + $cOffset = ($c + $convmap[$j + 2]) & $convmap[$j + 3]; + $result .= $is_hex ? sprintf('&#x%X;', $cOffset) : '&#'.$cOffset.';'; + continue 2; + } + } + $result .= $uchr; + } + + if (null === $encoding) { + return $result; + } + + return iconv('UTF-8', $encoding.'//IGNORE', $result); + } + + public static function mb_convert_case($s, $mode, $encoding = null) + { + $s = (string) $s; + if ('' === $s) { + return ''; + } + + $encoding = self::getEncoding($encoding); + + if ('UTF-8' === $encoding) { + $encoding = null; + if (!preg_match('//u', $s)) { + $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s); + } + } else { + $s = iconv($encoding, 'UTF-8//IGNORE', $s); + } + + if (\MB_CASE_TITLE == $mode) { + static $titleRegexp = null; + if (null === $titleRegexp) { + $titleRegexp = self::getData('titleCaseRegexp'); + } + $s = preg_replace_callback($titleRegexp, [__CLASS__, 'title_case'], $s); + } else { + if (\MB_CASE_UPPER == $mode) { + static $upper = null; + if (null === $upper) { + $upper = self::getData('upperCase'); + } + $map = $upper; + } else { + if (self::MB_CASE_FOLD === $mode) { + static $caseFolding = null; + if (null === $caseFolding) { + $caseFolding = self::getData('caseFolding'); + } + $s = strtr($s, $caseFolding); + } + + static $lower = null; + if (null === $lower) { + $lower = self::getData('lowerCase'); + } + $map = $lower; + } + + static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4]; + + $i = 0; + $len = \strlen($s); + + while ($i < $len) { + $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"]; + $uchr = substr($s, $i, $ulen); + $i += $ulen; + + if (isset($map[$uchr])) { + $uchr = $map[$uchr]; + $nlen = \strlen($uchr); + + if ($nlen == $ulen) { + $nlen = $i; + do { + $s[--$nlen] = $uchr[--$ulen]; + } while ($ulen); + } else { + $s = substr_replace($s, $uchr, $i - $ulen, $ulen); + $len += $nlen - $ulen; + $i += $nlen - $ulen; + } + } + } + } + + if (null === $encoding) { + return $s; + } + + return iconv('UTF-8', $encoding.'//IGNORE', $s); + } + + public static function mb_internal_encoding($encoding = null) + { + if (null === $encoding) { + return self::$internalEncoding; + } + + $normalizedEncoding = self::getEncoding($encoding); + + if ('UTF-8' === $normalizedEncoding || false !== @iconv($normalizedEncoding, $normalizedEncoding, ' ')) { + self::$internalEncoding = $normalizedEncoding; + + return true; + } + + if (80000 > \PHP_VERSION_ID) { + return false; + } + + throw new \ValueError(sprintf('Argument #1 ($encoding) must be a valid encoding, "%s" given', $encoding)); + } + + public static function mb_language($lang = null) + { + if (null === $lang) { + return self::$language; + } + + switch ($normalizedLang = strtolower($lang)) { + case 'uni': + case 'neutral': + self::$language = $normalizedLang; + + return true; + } + + if (80000 > \PHP_VERSION_ID) { + return false; + } + + throw new \ValueError(sprintf('Argument #1 ($language) must be a valid language, "%s" given', $lang)); + } + + public static function mb_list_encodings() + { + return ['UTF-8']; + } + + public static function mb_encoding_aliases($encoding) + { + switch (strtoupper($encoding)) { + case 'UTF8': + case 'UTF-8': + return ['utf8']; + } + + return false; + } + + public static function mb_check_encoding($var = null, $encoding = null) + { + if (PHP_VERSION_ID < 70200 && \is_array($var)) { + trigger_error('mb_check_encoding() expects parameter 1 to be string, array given', \E_USER_WARNING); + + return null; + } + + if (null === $encoding) { + if (null === $var) { + return false; + } + $encoding = self::$internalEncoding; + } + + if (!\is_array($var)) { + return self::mb_detect_encoding($var, [$encoding]) || false !== @iconv($encoding, $encoding, $var); + } + + foreach ($var as $key => $value) { + if (!self::mb_check_encoding($key, $encoding)) { + return false; + } + if (!self::mb_check_encoding($value, $encoding)) { + return false; + } + } + + return true; + + } + + public static function mb_detect_encoding($str, $encodingList = null, $strict = false) + { + if (null === $encodingList) { + $encodingList = self::$encodingList; + } else { + if (!\is_array($encodingList)) { + $encodingList = array_map('trim', explode(',', $encodingList)); + } + $encodingList = array_map('strtoupper', $encodingList); + } + + foreach ($encodingList as $enc) { + switch ($enc) { + case 'ASCII': + if (!preg_match('/[\x80-\xFF]/', $str)) { + return $enc; + } + break; + + case 'UTF8': + case 'UTF-8': + if (preg_match('//u', $str)) { + return 'UTF-8'; + } + break; + + default: + if (0 === strncmp($enc, 'ISO-8859-', 9)) { + return $enc; + } + } + } + + return false; + } + + public static function mb_detect_order($encodingList = null) + { + if (null === $encodingList) { + return self::$encodingList; + } + + if (!\is_array($encodingList)) { + $encodingList = array_map('trim', explode(',', $encodingList)); + } + $encodingList = array_map('strtoupper', $encodingList); + + foreach ($encodingList as $enc) { + switch ($enc) { + default: + if (strncmp($enc, 'ISO-8859-', 9)) { + return false; + } + // no break + case 'ASCII': + case 'UTF8': + case 'UTF-8': + } + } + + self::$encodingList = $encodingList; + + return true; + } + + public static function mb_strlen($s, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + return \strlen($s); + } + + return @iconv_strlen($s, $encoding); + } + + public static function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + return strpos($haystack, $needle, $offset); + } + + $needle = (string) $needle; + if ('' === $needle) { + if (80000 > \PHP_VERSION_ID) { + trigger_error(__METHOD__.': Empty delimiter', \E_USER_WARNING); + + return false; + } + + return 0; + } + + return iconv_strpos($haystack, $needle, $offset, $encoding); + } + + public static function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + return strrpos($haystack, $needle, $offset); + } + + if ($offset != (int) $offset) { + $offset = 0; + } elseif ($offset = (int) $offset) { + if ($offset < 0) { + if (0 > $offset += self::mb_strlen($needle)) { + $haystack = self::mb_substr($haystack, 0, $offset, $encoding); + } + $offset = 0; + } else { + $haystack = self::mb_substr($haystack, $offset, 2147483647, $encoding); + } + } + + $pos = '' !== $needle || 80000 > \PHP_VERSION_ID + ? iconv_strrpos($haystack, $needle, $encoding) + : self::mb_strlen($haystack, $encoding); + + return false !== $pos ? $offset + $pos : false; + } + + public static function mb_str_split($string, $split_length = 1, $encoding = null) + { + if (null !== $string && !\is_scalar($string) && !(\is_object($string) && method_exists($string, '__toString'))) { + trigger_error('mb_str_split() expects parameter 1 to be string, '.\gettype($string).' given', \E_USER_WARNING); + + return null; + } + + if (1 > $split_length = (int) $split_length) { + if (80000 > \PHP_VERSION_ID) { + trigger_error('The length of each segment must be greater than zero', \E_USER_WARNING); + + return false; + } + + throw new \ValueError('Argument #2 ($length) must be greater than 0'); + } + + if (null === $encoding) { + $encoding = mb_internal_encoding(); + } + + if ('UTF-8' === $encoding = self::getEncoding($encoding)) { + $rx = '/('; + while (65535 < $split_length) { + $rx .= '.{65535}'; + $split_length -= 65535; + } + $rx .= '.{'.$split_length.'})/us'; + + return preg_split($rx, $string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY); + } + + $result = []; + $length = mb_strlen($string, $encoding); + + for ($i = 0; $i < $length; $i += $split_length) { + $result[] = mb_substr($string, $i, $split_length, $encoding); + } + + return $result; + } + + public static function mb_strtolower($s, $encoding = null) + { + return self::mb_convert_case($s, \MB_CASE_LOWER, $encoding); + } + + public static function mb_strtoupper($s, $encoding = null) + { + return self::mb_convert_case($s, \MB_CASE_UPPER, $encoding); + } + + public static function mb_substitute_character($c = null) + { + if (null === $c) { + return 'none'; + } + if (0 === strcasecmp($c, 'none')) { + return true; + } + if (80000 > \PHP_VERSION_ID) { + return false; + } + if (\is_int($c) || 'long' === $c || 'entity' === $c) { + return false; + } + + throw new \ValueError('Argument #1 ($substitute_character) must be "none", "long", "entity" or a valid codepoint'); + } + + public static function mb_substr($s, $start, $length = null, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + return (string) substr($s, $start, null === $length ? 2147483647 : $length); + } + + if ($start < 0) { + $start = iconv_strlen($s, $encoding) + $start; + if ($start < 0) { + $start = 0; + } + } + + if (null === $length) { + $length = 2147483647; + } elseif ($length < 0) { + $length = iconv_strlen($s, $encoding) + $length - $start; + if ($length < 0) { + return ''; + } + } + + return (string) iconv_substr($s, $start, $length, $encoding); + } + + public static function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) + { + [$haystack, $needle] = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], [ + self::mb_convert_case($haystack, \MB_CASE_LOWER, $encoding), + self::mb_convert_case($needle, \MB_CASE_LOWER, $encoding), + ]); + + return self::mb_strpos($haystack, $needle, $offset, $encoding); + } + + public static function mb_stristr($haystack, $needle, $part = false, $encoding = null) + { + $pos = self::mb_stripos($haystack, $needle, 0, $encoding); + + return self::getSubpart($pos, $part, $haystack, $encoding); + } + + public static function mb_strrchr($haystack, $needle, $part = false, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + $pos = strrpos($haystack, $needle); + } else { + $needle = self::mb_substr($needle, 0, 1, $encoding); + $pos = iconv_strrpos($haystack, $needle, $encoding); + } + + return self::getSubpart($pos, $part, $haystack, $encoding); + } + + public static function mb_strrichr($haystack, $needle, $part = false, $encoding = null) + { + $needle = self::mb_substr($needle, 0, 1, $encoding); + $pos = self::mb_strripos($haystack, $needle, $encoding); + + return self::getSubpart($pos, $part, $haystack, $encoding); + } + + public static function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) + { + $haystack = self::mb_convert_case($haystack, \MB_CASE_LOWER, $encoding); + $needle = self::mb_convert_case($needle, \MB_CASE_LOWER, $encoding); + + $haystack = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], $haystack); + $needle = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], $needle); + + return self::mb_strrpos($haystack, $needle, $offset, $encoding); + } + + public static function mb_strstr($haystack, $needle, $part = false, $encoding = null) + { + $pos = strpos($haystack, $needle); + if (false === $pos) { + return false; + } + if ($part) { + return substr($haystack, 0, $pos); + } + + return substr($haystack, $pos); + } + + public static function mb_get_info($type = 'all') + { + $info = [ + 'internal_encoding' => self::$internalEncoding, + 'http_output' => 'pass', + 'http_output_conv_mimetypes' => '^(text/|application/xhtml\+xml)', + 'func_overload' => 0, + 'func_overload_list' => 'no overload', + 'mail_charset' => 'UTF-8', + 'mail_header_encoding' => 'BASE64', + 'mail_body_encoding' => 'BASE64', + 'illegal_chars' => 0, + 'encoding_translation' => 'Off', + 'language' => self::$language, + 'detect_order' => self::$encodingList, + 'substitute_character' => 'none', + 'strict_detection' => 'Off', + ]; + + if ('all' === $type) { + return $info; + } + if (isset($info[$type])) { + return $info[$type]; + } + + return false; + } + + public static function mb_http_input($type = '') + { + return false; + } + + public static function mb_http_output($encoding = null) + { + return null !== $encoding ? 'pass' === $encoding : 'pass'; + } + + public static function mb_strwidth($s, $encoding = null) + { + $encoding = self::getEncoding($encoding); + + if ('UTF-8' !== $encoding) { + $s = iconv($encoding, 'UTF-8//IGNORE', $s); + } + + $s = preg_replace('/[\x{1100}-\x{115F}\x{2329}\x{232A}\x{2E80}-\x{303E}\x{3040}-\x{A4CF}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE6F}\x{FF00}-\x{FF60}\x{FFE0}-\x{FFE6}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u', '', $s, -1, $wide); + + return ($wide << 1) + iconv_strlen($s, 'UTF-8'); + } + + public static function mb_substr_count($haystack, $needle, $encoding = null) + { + return substr_count($haystack, $needle); + } + + public static function mb_output_handler($contents, $status) + { + return $contents; + } + + public static function mb_chr($code, $encoding = null) + { + if (0x80 > $code %= 0x200000) { + $s = \chr($code); + } elseif (0x800 > $code) { + $s = \chr(0xC0 | $code >> 6).\chr(0x80 | $code & 0x3F); + } elseif (0x10000 > $code) { + $s = \chr(0xE0 | $code >> 12).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); + } else { + $s = \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); + } + + if ('UTF-8' !== $encoding = self::getEncoding($encoding)) { + $s = mb_convert_encoding($s, $encoding, 'UTF-8'); + } + + return $s; + } + + public static function mb_ord($s, $encoding = null) + { + if ('UTF-8' !== $encoding = self::getEncoding($encoding)) { + $s = mb_convert_encoding($s, 'UTF-8', $encoding); + } + + if (1 === \strlen($s)) { + return \ord($s); + } + + $code = ($s = unpack('C*', substr($s, 0, 4))) ? $s[1] : 0; + if (0xF0 <= $code) { + return (($code - 0xF0) << 18) + (($s[2] - 0x80) << 12) + (($s[3] - 0x80) << 6) + $s[4] - 0x80; + } + if (0xE0 <= $code) { + return (($code - 0xE0) << 12) + (($s[2] - 0x80) << 6) + $s[3] - 0x80; + } + if (0xC0 <= $code) { + return (($code - 0xC0) << 6) + $s[2] - 0x80; + } + + return $code; + } + + public static function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = \STR_PAD_RIGHT, string $encoding = null): string + { + if (!\in_array($pad_type, [\STR_PAD_RIGHT, \STR_PAD_LEFT, \STR_PAD_BOTH], true)) { + throw new \ValueError('mb_str_pad(): Argument #4 ($pad_type) must be STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH'); + } + + if (null === $encoding) { + $encoding = self::mb_internal_encoding(); + } + + try { + $validEncoding = @self::mb_check_encoding('', $encoding); + } catch (\ValueError $e) { + throw new \ValueError(sprintf('mb_str_pad(): Argument #5 ($encoding) must be a valid encoding, "%s" given', $encoding)); + } + + // BC for PHP 7.3 and lower + if (!$validEncoding) { + throw new \ValueError(sprintf('mb_str_pad(): Argument #5 ($encoding) must be a valid encoding, "%s" given', $encoding)); + } + + if (self::mb_strlen($pad_string, $encoding) <= 0) { + throw new \ValueError('mb_str_pad(): Argument #3 ($pad_string) must be a non-empty string'); + } + + $paddingRequired = $length - self::mb_strlen($string, $encoding); + + if ($paddingRequired < 1) { + return $string; + } + + switch ($pad_type) { + case \STR_PAD_LEFT: + return self::mb_substr(str_repeat($pad_string, $paddingRequired), 0, $paddingRequired, $encoding).$string; + case \STR_PAD_RIGHT: + return $string.self::mb_substr(str_repeat($pad_string, $paddingRequired), 0, $paddingRequired, $encoding); + default: + $leftPaddingLength = floor($paddingRequired / 2); + $rightPaddingLength = $paddingRequired - $leftPaddingLength; + + return self::mb_substr(str_repeat($pad_string, $leftPaddingLength), 0, $leftPaddingLength, $encoding).$string.self::mb_substr(str_repeat($pad_string, $rightPaddingLength), 0, $rightPaddingLength, $encoding); + } + } + + private static function getSubpart($pos, $part, $haystack, $encoding) + { + if (false === $pos) { + return false; + } + if ($part) { + return self::mb_substr($haystack, 0, $pos, $encoding); + } + + return self::mb_substr($haystack, $pos, null, $encoding); + } + + private static function html_encoding_callback(array $m) + { + $i = 1; + $entities = ''; + $m = unpack('C*', htmlentities($m[0], \ENT_COMPAT, 'UTF-8')); + + while (isset($m[$i])) { + if (0x80 > $m[$i]) { + $entities .= \chr($m[$i++]); + continue; + } + if (0xF0 <= $m[$i]) { + $c = (($m[$i++] - 0xF0) << 18) + (($m[$i++] - 0x80) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80; + } elseif (0xE0 <= $m[$i]) { + $c = (($m[$i++] - 0xE0) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80; + } else { + $c = (($m[$i++] - 0xC0) << 6) + $m[$i++] - 0x80; + } + + $entities .= '&#'.$c.';'; + } + + return $entities; + } + + private static function title_case(array $s) + { + return self::mb_convert_case($s[1], \MB_CASE_UPPER, 'UTF-8').self::mb_convert_case($s[2], \MB_CASE_LOWER, 'UTF-8'); + } + + private static function getData($file) + { + if (file_exists($file = __DIR__.'/Resources/unidata/'.$file.'.php')) { + return require $file; + } + + return false; + } + + private static function getEncoding($encoding) + { + if (null === $encoding) { + return self::$internalEncoding; + } + + if ('UTF-8' === $encoding) { + return 'UTF-8'; + } + + $encoding = strtoupper($encoding); + + if ('8BIT' === $encoding || 'BINARY' === $encoding) { + return 'CP850'; + } + + if ('UTF8' === $encoding) { + return 'UTF-8'; + } + + return $encoding; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/README.md b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/README.md new file mode 100644 index 00000000..478b40da --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/README.md @@ -0,0 +1,13 @@ +Symfony Polyfill / Mbstring +=========================== + +This component provides a partial, native PHP implementation for the +[Mbstring](https://php.net/mbstring) extension. + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/Resources/unidata/caseFolding.php b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/Resources/unidata/caseFolding.php new file mode 100644 index 00000000..512bba0b --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/Resources/unidata/caseFolding.php @@ -0,0 +1,119 @@ + 'i̇', + 'µ' => 'μ', + 'ſ' => 's', + 'ͅ' => 'ι', + 'ς' => 'σ', + 'ϐ' => 'β', + 'ϑ' => 'θ', + 'ϕ' => 'φ', + 'ϖ' => 'π', + 'ϰ' => 'κ', + 'ϱ' => 'ρ', + 'ϵ' => 'ε', + 'ẛ' => 'ṡ', + 'ι' => 'ι', + 'ß' => 'ss', + 'ʼn' => 'ʼn', + 'ǰ' => 'ǰ', + 'ΐ' => 'ΐ', + 'ΰ' => 'ΰ', + 'և' => 'եւ', + 'ẖ' => 'ẖ', + 'ẗ' => 'ẗ', + 'ẘ' => 'ẘ', + 'ẙ' => 'ẙ', + 'ẚ' => 'aʾ', + 'ẞ' => 'ss', + 'ὐ' => 'ὐ', + 'ὒ' => 'ὒ', + 'ὔ' => 'ὔ', + 'ὖ' => 'ὖ', + 'ᾀ' => 'ἀι', + 'ᾁ' => 'ἁι', + 'ᾂ' => 'ἂι', + 'ᾃ' => 'ἃι', + 'ᾄ' => 'ἄι', + 'ᾅ' => 'ἅι', + 'ᾆ' => 'ἆι', + 'ᾇ' => 'ἇι', + 'ᾈ' => 'ἀι', + 'ᾉ' => 'ἁι', + 'ᾊ' => 'ἂι', + 'ᾋ' => 'ἃι', + 'ᾌ' => 'ἄι', + 'ᾍ' => 'ἅι', + 'ᾎ' => 'ἆι', + 'ᾏ' => 'ἇι', + 'ᾐ' => 'ἠι', + 'ᾑ' => 'ἡι', + 'ᾒ' => 'ἢι', + 'ᾓ' => 'ἣι', + 'ᾔ' => 'ἤι', + 'ᾕ' => 'ἥι', + 'ᾖ' => 'ἦι', + 'ᾗ' => 'ἧι', + 'ᾘ' => 'ἠι', + 'ᾙ' => 'ἡι', + 'ᾚ' => 'ἢι', + 'ᾛ' => 'ἣι', + 'ᾜ' => 'ἤι', + 'ᾝ' => 'ἥι', + 'ᾞ' => 'ἦι', + 'ᾟ' => 'ἧι', + 'ᾠ' => 'ὠι', + 'ᾡ' => 'ὡι', + 'ᾢ' => 'ὢι', + 'ᾣ' => 'ὣι', + 'ᾤ' => 'ὤι', + 'ᾥ' => 'ὥι', + 'ᾦ' => 'ὦι', + 'ᾧ' => 'ὧι', + 'ᾨ' => 'ὠι', + 'ᾩ' => 'ὡι', + 'ᾪ' => 'ὢι', + 'ᾫ' => 'ὣι', + 'ᾬ' => 'ὤι', + 'ᾭ' => 'ὥι', + 'ᾮ' => 'ὦι', + 'ᾯ' => 'ὧι', + 'ᾲ' => 'ὰι', + 'ᾳ' => 'αι', + 'ᾴ' => 'άι', + 'ᾶ' => 'ᾶ', + 'ᾷ' => 'ᾶι', + 'ᾼ' => 'αι', + 'ῂ' => 'ὴι', + 'ῃ' => 'ηι', + 'ῄ' => 'ήι', + 'ῆ' => 'ῆ', + 'ῇ' => 'ῆι', + 'ῌ' => 'ηι', + 'ῒ' => 'ῒ', + 'ῖ' => 'ῖ', + 'ῗ' => 'ῗ', + 'ῢ' => 'ῢ', + 'ῤ' => 'ῤ', + 'ῦ' => 'ῦ', + 'ῧ' => 'ῧ', + 'ῲ' => 'ὼι', + 'ῳ' => 'ωι', + 'ῴ' => 'ώι', + 'ῶ' => 'ῶ', + 'ῷ' => 'ῶι', + 'ῼ' => 'ωι', + 'ff' => 'ff', + 'fi' => 'fi', + 'fl' => 'fl', + 'ffi' => 'ffi', + 'ffl' => 'ffl', + 'ſt' => 'st', + 'st' => 'st', + 'ﬓ' => 'մն', + 'ﬔ' => 'մե', + 'ﬕ' => 'մի', + 'ﬖ' => 'վն', + 'ﬗ' => 'մխ', +]; diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php new file mode 100644 index 00000000..fac60b08 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php @@ -0,0 +1,1397 @@ + 'a', + 'B' => 'b', + 'C' => 'c', + 'D' => 'd', + 'E' => 'e', + 'F' => 'f', + 'G' => 'g', + 'H' => 'h', + 'I' => 'i', + 'J' => 'j', + 'K' => 'k', + 'L' => 'l', + 'M' => 'm', + 'N' => 'n', + 'O' => 'o', + 'P' => 'p', + 'Q' => 'q', + 'R' => 'r', + 'S' => 's', + 'T' => 't', + 'U' => 'u', + 'V' => 'v', + 'W' => 'w', + 'X' => 'x', + 'Y' => 'y', + 'Z' => 'z', + 'À' => 'à', + 'Á' => 'á', + 'Â' => 'â', + 'Ã' => 'ã', + 'Ä' => 'ä', + 'Å' => 'å', + 'Æ' => 'æ', + 'Ç' => 'ç', + 'È' => 'è', + 'É' => 'é', + 'Ê' => 'ê', + 'Ë' => 'ë', + 'Ì' => 'ì', + 'Í' => 'í', + 'Î' => 'î', + 'Ï' => 'ï', + 'Ð' => 'ð', + 'Ñ' => 'ñ', + 'Ò' => 'ò', + 'Ó' => 'ó', + 'Ô' => 'ô', + 'Õ' => 'õ', + 'Ö' => 'ö', + 'Ø' => 'ø', + 'Ù' => 'ù', + 'Ú' => 'ú', + 'Û' => 'û', + 'Ü' => 'ü', + 'Ý' => 'ý', + 'Þ' => 'þ', + 'Ā' => 'ā', + 'Ă' => 'ă', + 'Ą' => 'ą', + 'Ć' => 'ć', + 'Ĉ' => 'ĉ', + 'Ċ' => 'ċ', + 'Č' => 'č', + 'Ď' => 'ď', + 'Đ' => 'đ', + 'Ē' => 'ē', + 'Ĕ' => 'ĕ', + 'Ė' => 'ė', + 'Ę' => 'ę', + 'Ě' => 'ě', + 'Ĝ' => 'ĝ', + 'Ğ' => 'ğ', + 'Ġ' => 'ġ', + 'Ģ' => 'ģ', + 'Ĥ' => 'ĥ', + 'Ħ' => 'ħ', + 'Ĩ' => 'ĩ', + 'Ī' => 'ī', + 'Ĭ' => 'ĭ', + 'Į' => 'į', + 'İ' => 'i̇', + 'IJ' => 'ij', + 'Ĵ' => 'ĵ', + 'Ķ' => 'ķ', + 'Ĺ' => 'ĺ', + 'Ļ' => 'ļ', + 'Ľ' => 'ľ', + 'Ŀ' => 'ŀ', + 'Ł' => 'ł', + 'Ń' => 'ń', + 'Ņ' => 'ņ', + 'Ň' => 'ň', + 'Ŋ' => 'ŋ', + 'Ō' => 'ō', + 'Ŏ' => 'ŏ', + 'Ő' => 'ő', + 'Œ' => 'œ', + 'Ŕ' => 'ŕ', + 'Ŗ' => 'ŗ', + 'Ř' => 'ř', + 'Ś' => 'ś', + 'Ŝ' => 'ŝ', + 'Ş' => 'ş', + 'Š' => 'š', + 'Ţ' => 'ţ', + 'Ť' => 'ť', + 'Ŧ' => 'ŧ', + 'Ũ' => 'ũ', + 'Ū' => 'ū', + 'Ŭ' => 'ŭ', + 'Ů' => 'ů', + 'Ű' => 'ű', + 'Ų' => 'ų', + 'Ŵ' => 'ŵ', + 'Ŷ' => 'ŷ', + 'Ÿ' => 'ÿ', + 'Ź' => 'ź', + 'Ż' => 'ż', + 'Ž' => 'ž', + 'Ɓ' => 'ɓ', + 'Ƃ' => 'ƃ', + 'Ƅ' => 'ƅ', + 'Ɔ' => 'ɔ', + 'Ƈ' => 'ƈ', + 'Ɖ' => 'ɖ', + 'Ɗ' => 'ɗ', + 'Ƌ' => 'ƌ', + 'Ǝ' => 'ǝ', + 'Ə' => 'ə', + 'Ɛ' => 'ɛ', + 'Ƒ' => 'ƒ', + 'Ɠ' => 'ɠ', + 'Ɣ' => 'ɣ', + 'Ɩ' => 'ɩ', + 'Ɨ' => 'ɨ', + 'Ƙ' => 'ƙ', + 'Ɯ' => 'ɯ', + 'Ɲ' => 'ɲ', + 'Ɵ' => 'ɵ', + 'Ơ' => 'ơ', + 'Ƣ' => 'ƣ', + 'Ƥ' => 'ƥ', + 'Ʀ' => 'ʀ', + 'Ƨ' => 'ƨ', + 'Ʃ' => 'ʃ', + 'Ƭ' => 'ƭ', + 'Ʈ' => 'ʈ', + 'Ư' => 'ư', + 'Ʊ' => 'ʊ', + 'Ʋ' => 'ʋ', + 'Ƴ' => 'ƴ', + 'Ƶ' => 'ƶ', + 'Ʒ' => 'ʒ', + 'Ƹ' => 'ƹ', + 'Ƽ' => 'ƽ', + 'DŽ' => 'dž', + 'Dž' => 'dž', + 'LJ' => 'lj', + 'Lj' => 'lj', + 'NJ' => 'nj', + 'Nj' => 'nj', + 'Ǎ' => 'ǎ', + 'Ǐ' => 'ǐ', + 'Ǒ' => 'ǒ', + 'Ǔ' => 'ǔ', + 'Ǖ' => 'ǖ', + 'Ǘ' => 'ǘ', + 'Ǚ' => 'ǚ', + 'Ǜ' => 'ǜ', + 'Ǟ' => 'ǟ', + 'Ǡ' => 'ǡ', + 'Ǣ' => 'ǣ', + 'Ǥ' => 'ǥ', + 'Ǧ' => 'ǧ', + 'Ǩ' => 'ǩ', + 'Ǫ' => 'ǫ', + 'Ǭ' => 'ǭ', + 'Ǯ' => 'ǯ', + 'DZ' => 'dz', + 'Dz' => 'dz', + 'Ǵ' => 'ǵ', + 'Ƕ' => 'ƕ', + 'Ƿ' => 'ƿ', + 'Ǹ' => 'ǹ', + 'Ǻ' => 'ǻ', + 'Ǽ' => 'ǽ', + 'Ǿ' => 'ǿ', + 'Ȁ' => 'ȁ', + 'Ȃ' => 'ȃ', + 'Ȅ' => 'ȅ', + 'Ȇ' => 'ȇ', + 'Ȉ' => 'ȉ', + 'Ȋ' => 'ȋ', + 'Ȍ' => 'ȍ', + 'Ȏ' => 'ȏ', + 'Ȑ' => 'ȑ', + 'Ȓ' => 'ȓ', + 'Ȕ' => 'ȕ', + 'Ȗ' => 'ȗ', + 'Ș' => 'ș', + 'Ț' => 'ț', + 'Ȝ' => 'ȝ', + 'Ȟ' => 'ȟ', + 'Ƞ' => 'ƞ', + 'Ȣ' => 'ȣ', + 'Ȥ' => 'ȥ', + 'Ȧ' => 'ȧ', + 'Ȩ' => 'ȩ', + 'Ȫ' => 'ȫ', + 'Ȭ' => 'ȭ', + 'Ȯ' => 'ȯ', + 'Ȱ' => 'ȱ', + 'Ȳ' => 'ȳ', + 'Ⱥ' => 'ⱥ', + 'Ȼ' => 'ȼ', + 'Ƚ' => 'ƚ', + 'Ⱦ' => 'ⱦ', + 'Ɂ' => 'ɂ', + 'Ƀ' => 'ƀ', + 'Ʉ' => 'ʉ', + 'Ʌ' => 'ʌ', + 'Ɇ' => 'ɇ', + 'Ɉ' => 'ɉ', + 'Ɋ' => 'ɋ', + 'Ɍ' => 'ɍ', + 'Ɏ' => 'ɏ', + 'Ͱ' => 'ͱ', + 'Ͳ' => 'ͳ', + 'Ͷ' => 'ͷ', + 'Ϳ' => 'ϳ', + 'Ά' => 'ά', + 'Έ' => 'έ', + 'Ή' => 'ή', + 'Ί' => 'ί', + 'Ό' => 'ό', + 'Ύ' => 'ύ', + 'Ώ' => 'ώ', + 'Α' => 'α', + 'Β' => 'β', + 'Γ' => 'γ', + 'Δ' => 'δ', + 'Ε' => 'ε', + 'Ζ' => 'ζ', + 'Η' => 'η', + 'Θ' => 'θ', + 'Ι' => 'ι', + 'Κ' => 'κ', + 'Λ' => 'λ', + 'Μ' => 'μ', + 'Ν' => 'ν', + 'Ξ' => 'ξ', + 'Ο' => 'ο', + 'Π' => 'π', + 'Ρ' => 'ρ', + 'Σ' => 'σ', + 'Τ' => 'τ', + 'Υ' => 'υ', + 'Φ' => 'φ', + 'Χ' => 'χ', + 'Ψ' => 'ψ', + 'Ω' => 'ω', + 'Ϊ' => 'ϊ', + 'Ϋ' => 'ϋ', + 'Ϗ' => 'ϗ', + 'Ϙ' => 'ϙ', + 'Ϛ' => 'ϛ', + 'Ϝ' => 'ϝ', + 'Ϟ' => 'ϟ', + 'Ϡ' => 'ϡ', + 'Ϣ' => 'ϣ', + 'Ϥ' => 'ϥ', + 'Ϧ' => 'ϧ', + 'Ϩ' => 'ϩ', + 'Ϫ' => 'ϫ', + 'Ϭ' => 'ϭ', + 'Ϯ' => 'ϯ', + 'ϴ' => 'θ', + 'Ϸ' => 'ϸ', + 'Ϲ' => 'ϲ', + 'Ϻ' => 'ϻ', + 'Ͻ' => 'ͻ', + 'Ͼ' => 'ͼ', + 'Ͽ' => 'ͽ', + 'Ѐ' => 'ѐ', + 'Ё' => 'ё', + 'Ђ' => 'ђ', + 'Ѓ' => 'ѓ', + 'Є' => 'є', + 'Ѕ' => 'ѕ', + 'І' => 'і', + 'Ї' => 'ї', + 'Ј' => 'ј', + 'Љ' => 'љ', + 'Њ' => 'њ', + 'Ћ' => 'ћ', + 'Ќ' => 'ќ', + 'Ѝ' => 'ѝ', + 'Ў' => 'ў', + 'Џ' => 'џ', + 'А' => 'а', + 'Б' => 'б', + 'В' => 'в', + 'Г' => 'г', + 'Д' => 'д', + 'Е' => 'е', + 'Ж' => 'ж', + 'З' => 'з', + 'И' => 'и', + 'Й' => 'й', + 'К' => 'к', + 'Л' => 'л', + 'М' => 'м', + 'Н' => 'н', + 'О' => 'о', + 'П' => 'п', + 'Р' => 'р', + 'С' => 'с', + 'Т' => 'т', + 'У' => 'у', + 'Ф' => 'ф', + 'Х' => 'х', + 'Ц' => 'ц', + 'Ч' => 'ч', + 'Ш' => 'ш', + 'Щ' => 'щ', + 'Ъ' => 'ъ', + 'Ы' => 'ы', + 'Ь' => 'ь', + 'Э' => 'э', + 'Ю' => 'ю', + 'Я' => 'я', + 'Ѡ' => 'ѡ', + 'Ѣ' => 'ѣ', + 'Ѥ' => 'ѥ', + 'Ѧ' => 'ѧ', + 'Ѩ' => 'ѩ', + 'Ѫ' => 'ѫ', + 'Ѭ' => 'ѭ', + 'Ѯ' => 'ѯ', + 'Ѱ' => 'ѱ', + 'Ѳ' => 'ѳ', + 'Ѵ' => 'ѵ', + 'Ѷ' => 'ѷ', + 'Ѹ' => 'ѹ', + 'Ѻ' => 'ѻ', + 'Ѽ' => 'ѽ', + 'Ѿ' => 'ѿ', + 'Ҁ' => 'ҁ', + 'Ҋ' => 'ҋ', + 'Ҍ' => 'ҍ', + 'Ҏ' => 'ҏ', + 'Ґ' => 'ґ', + 'Ғ' => 'ғ', + 'Ҕ' => 'ҕ', + 'Җ' => 'җ', + 'Ҙ' => 'ҙ', + 'Қ' => 'қ', + 'Ҝ' => 'ҝ', + 'Ҟ' => 'ҟ', + 'Ҡ' => 'ҡ', + 'Ң' => 'ң', + 'Ҥ' => 'ҥ', + 'Ҧ' => 'ҧ', + 'Ҩ' => 'ҩ', + 'Ҫ' => 'ҫ', + 'Ҭ' => 'ҭ', + 'Ү' => 'ү', + 'Ұ' => 'ұ', + 'Ҳ' => 'ҳ', + 'Ҵ' => 'ҵ', + 'Ҷ' => 'ҷ', + 'Ҹ' => 'ҹ', + 'Һ' => 'һ', + 'Ҽ' => 'ҽ', + 'Ҿ' => 'ҿ', + 'Ӏ' => 'ӏ', + 'Ӂ' => 'ӂ', + 'Ӄ' => 'ӄ', + 'Ӆ' => 'ӆ', + 'Ӈ' => 'ӈ', + 'Ӊ' => 'ӊ', + 'Ӌ' => 'ӌ', + 'Ӎ' => 'ӎ', + 'Ӑ' => 'ӑ', + 'Ӓ' => 'ӓ', + 'Ӕ' => 'ӕ', + 'Ӗ' => 'ӗ', + 'Ә' => 'ә', + 'Ӛ' => 'ӛ', + 'Ӝ' => 'ӝ', + 'Ӟ' => 'ӟ', + 'Ӡ' => 'ӡ', + 'Ӣ' => 'ӣ', + 'Ӥ' => 'ӥ', + 'Ӧ' => 'ӧ', + 'Ө' => 'ө', + 'Ӫ' => 'ӫ', + 'Ӭ' => 'ӭ', + 'Ӯ' => 'ӯ', + 'Ӱ' => 'ӱ', + 'Ӳ' => 'ӳ', + 'Ӵ' => 'ӵ', + 'Ӷ' => 'ӷ', + 'Ӹ' => 'ӹ', + 'Ӻ' => 'ӻ', + 'Ӽ' => 'ӽ', + 'Ӿ' => 'ӿ', + 'Ԁ' => 'ԁ', + 'Ԃ' => 'ԃ', + 'Ԅ' => 'ԅ', + 'Ԇ' => 'ԇ', + 'Ԉ' => 'ԉ', + 'Ԋ' => 'ԋ', + 'Ԍ' => 'ԍ', + 'Ԏ' => 'ԏ', + 'Ԑ' => 'ԑ', + 'Ԓ' => 'ԓ', + 'Ԕ' => 'ԕ', + 'Ԗ' => 'ԗ', + 'Ԙ' => 'ԙ', + 'Ԛ' => 'ԛ', + 'Ԝ' => 'ԝ', + 'Ԟ' => 'ԟ', + 'Ԡ' => 'ԡ', + 'Ԣ' => 'ԣ', + 'Ԥ' => 'ԥ', + 'Ԧ' => 'ԧ', + 'Ԩ' => 'ԩ', + 'Ԫ' => 'ԫ', + 'Ԭ' => 'ԭ', + 'Ԯ' => 'ԯ', + 'Ա' => 'ա', + 'Բ' => 'բ', + 'Գ' => 'գ', + 'Դ' => 'դ', + 'Ե' => 'ե', + 'Զ' => 'զ', + 'Է' => 'է', + 'Ը' => 'ը', + 'Թ' => 'թ', + 'Ժ' => 'ժ', + 'Ի' => 'ի', + 'Լ' => 'լ', + 'Խ' => 'խ', + 'Ծ' => 'ծ', + 'Կ' => 'կ', + 'Հ' => 'հ', + 'Ձ' => 'ձ', + 'Ղ' => 'ղ', + 'Ճ' => 'ճ', + 'Մ' => 'մ', + 'Յ' => 'յ', + 'Ն' => 'ն', + 'Շ' => 'շ', + 'Ո' => 'ո', + 'Չ' => 'չ', + 'Պ' => 'պ', + 'Ջ' => 'ջ', + 'Ռ' => 'ռ', + 'Ս' => 'ս', + 'Վ' => 'վ', + 'Տ' => 'տ', + 'Ր' => 'ր', + 'Ց' => 'ց', + 'Ւ' => 'ւ', + 'Փ' => 'փ', + 'Ք' => 'ք', + 'Օ' => 'օ', + 'Ֆ' => 'ֆ', + 'Ⴀ' => 'ⴀ', + 'Ⴁ' => 'ⴁ', + 'Ⴂ' => 'ⴂ', + 'Ⴃ' => 'ⴃ', + 'Ⴄ' => 'ⴄ', + 'Ⴅ' => 'ⴅ', + 'Ⴆ' => 'ⴆ', + 'Ⴇ' => 'ⴇ', + 'Ⴈ' => 'ⴈ', + 'Ⴉ' => 'ⴉ', + 'Ⴊ' => 'ⴊ', + 'Ⴋ' => 'ⴋ', + 'Ⴌ' => 'ⴌ', + 'Ⴍ' => 'ⴍ', + 'Ⴎ' => 'ⴎ', + 'Ⴏ' => 'ⴏ', + 'Ⴐ' => 'ⴐ', + 'Ⴑ' => 'ⴑ', + 'Ⴒ' => 'ⴒ', + 'Ⴓ' => 'ⴓ', + 'Ⴔ' => 'ⴔ', + 'Ⴕ' => 'ⴕ', + 'Ⴖ' => 'ⴖ', + 'Ⴗ' => 'ⴗ', + 'Ⴘ' => 'ⴘ', + 'Ⴙ' => 'ⴙ', + 'Ⴚ' => 'ⴚ', + 'Ⴛ' => 'ⴛ', + 'Ⴜ' => 'ⴜ', + 'Ⴝ' => 'ⴝ', + 'Ⴞ' => 'ⴞ', + 'Ⴟ' => 'ⴟ', + 'Ⴠ' => 'ⴠ', + 'Ⴡ' => 'ⴡ', + 'Ⴢ' => 'ⴢ', + 'Ⴣ' => 'ⴣ', + 'Ⴤ' => 'ⴤ', + 'Ⴥ' => 'ⴥ', + 'Ⴧ' => 'ⴧ', + 'Ⴭ' => 'ⴭ', + 'Ꭰ' => 'ꭰ', + 'Ꭱ' => 'ꭱ', + 'Ꭲ' => 'ꭲ', + 'Ꭳ' => 'ꭳ', + 'Ꭴ' => 'ꭴ', + 'Ꭵ' => 'ꭵ', + 'Ꭶ' => 'ꭶ', + 'Ꭷ' => 'ꭷ', + 'Ꭸ' => 'ꭸ', + 'Ꭹ' => 'ꭹ', + 'Ꭺ' => 'ꭺ', + 'Ꭻ' => 'ꭻ', + 'Ꭼ' => 'ꭼ', + 'Ꭽ' => 'ꭽ', + 'Ꭾ' => 'ꭾ', + 'Ꭿ' => 'ꭿ', + 'Ꮀ' => 'ꮀ', + 'Ꮁ' => 'ꮁ', + 'Ꮂ' => 'ꮂ', + 'Ꮃ' => 'ꮃ', + 'Ꮄ' => 'ꮄ', + 'Ꮅ' => 'ꮅ', + 'Ꮆ' => 'ꮆ', + 'Ꮇ' => 'ꮇ', + 'Ꮈ' => 'ꮈ', + 'Ꮉ' => 'ꮉ', + 'Ꮊ' => 'ꮊ', + 'Ꮋ' => 'ꮋ', + 'Ꮌ' => 'ꮌ', + 'Ꮍ' => 'ꮍ', + 'Ꮎ' => 'ꮎ', + 'Ꮏ' => 'ꮏ', + 'Ꮐ' => 'ꮐ', + 'Ꮑ' => 'ꮑ', + 'Ꮒ' => 'ꮒ', + 'Ꮓ' => 'ꮓ', + 'Ꮔ' => 'ꮔ', + 'Ꮕ' => 'ꮕ', + 'Ꮖ' => 'ꮖ', + 'Ꮗ' => 'ꮗ', + 'Ꮘ' => 'ꮘ', + 'Ꮙ' => 'ꮙ', + 'Ꮚ' => 'ꮚ', + 'Ꮛ' => 'ꮛ', + 'Ꮜ' => 'ꮜ', + 'Ꮝ' => 'ꮝ', + 'Ꮞ' => 'ꮞ', + 'Ꮟ' => 'ꮟ', + 'Ꮠ' => 'ꮠ', + 'Ꮡ' => 'ꮡ', + 'Ꮢ' => 'ꮢ', + 'Ꮣ' => 'ꮣ', + 'Ꮤ' => 'ꮤ', + 'Ꮥ' => 'ꮥ', + 'Ꮦ' => 'ꮦ', + 'Ꮧ' => 'ꮧ', + 'Ꮨ' => 'ꮨ', + 'Ꮩ' => 'ꮩ', + 'Ꮪ' => 'ꮪ', + 'Ꮫ' => 'ꮫ', + 'Ꮬ' => 'ꮬ', + 'Ꮭ' => 'ꮭ', + 'Ꮮ' => 'ꮮ', + 'Ꮯ' => 'ꮯ', + 'Ꮰ' => 'ꮰ', + 'Ꮱ' => 'ꮱ', + 'Ꮲ' => 'ꮲ', + 'Ꮳ' => 'ꮳ', + 'Ꮴ' => 'ꮴ', + 'Ꮵ' => 'ꮵ', + 'Ꮶ' => 'ꮶ', + 'Ꮷ' => 'ꮷ', + 'Ꮸ' => 'ꮸ', + 'Ꮹ' => 'ꮹ', + 'Ꮺ' => 'ꮺ', + 'Ꮻ' => 'ꮻ', + 'Ꮼ' => 'ꮼ', + 'Ꮽ' => 'ꮽ', + 'Ꮾ' => 'ꮾ', + 'Ꮿ' => 'ꮿ', + 'Ᏸ' => 'ᏸ', + 'Ᏹ' => 'ᏹ', + 'Ᏺ' => 'ᏺ', + 'Ᏻ' => 'ᏻ', + 'Ᏼ' => 'ᏼ', + 'Ᏽ' => 'ᏽ', + 'Ა' => 'ა', + 'Ბ' => 'ბ', + 'Გ' => 'გ', + 'Დ' => 'დ', + 'Ე' => 'ე', + 'Ვ' => 'ვ', + 'Ზ' => 'ზ', + 'Თ' => 'თ', + 'Ი' => 'ი', + 'Კ' => 'კ', + 'Ლ' => 'ლ', + 'Მ' => 'მ', + 'Ნ' => 'ნ', + 'Ო' => 'ო', + 'Პ' => 'პ', + 'Ჟ' => 'ჟ', + 'Რ' => 'რ', + 'Ს' => 'ს', + 'Ტ' => 'ტ', + 'Უ' => 'უ', + 'Ფ' => 'ფ', + 'Ქ' => 'ქ', + 'Ღ' => 'ღ', + 'Ყ' => 'ყ', + 'Შ' => 'შ', + 'Ჩ' => 'ჩ', + 'Ც' => 'ც', + 'Ძ' => 'ძ', + 'Წ' => 'წ', + 'Ჭ' => 'ჭ', + 'Ხ' => 'ხ', + 'Ჯ' => 'ჯ', + 'Ჰ' => 'ჰ', + 'Ჱ' => 'ჱ', + 'Ჲ' => 'ჲ', + 'Ჳ' => 'ჳ', + 'Ჴ' => 'ჴ', + 'Ჵ' => 'ჵ', + 'Ჶ' => 'ჶ', + 'Ჷ' => 'ჷ', + 'Ჸ' => 'ჸ', + 'Ჹ' => 'ჹ', + 'Ჺ' => 'ჺ', + 'Ჽ' => 'ჽ', + 'Ჾ' => 'ჾ', + 'Ჿ' => 'ჿ', + 'Ḁ' => 'ḁ', + 'Ḃ' => 'ḃ', + 'Ḅ' => 'ḅ', + 'Ḇ' => 'ḇ', + 'Ḉ' => 'ḉ', + 'Ḋ' => 'ḋ', + 'Ḍ' => 'ḍ', + 'Ḏ' => 'ḏ', + 'Ḑ' => 'ḑ', + 'Ḓ' => 'ḓ', + 'Ḕ' => 'ḕ', + 'Ḗ' => 'ḗ', + 'Ḙ' => 'ḙ', + 'Ḛ' => 'ḛ', + 'Ḝ' => 'ḝ', + 'Ḟ' => 'ḟ', + 'Ḡ' => 'ḡ', + 'Ḣ' => 'ḣ', + 'Ḥ' => 'ḥ', + 'Ḧ' => 'ḧ', + 'Ḩ' => 'ḩ', + 'Ḫ' => 'ḫ', + 'Ḭ' => 'ḭ', + 'Ḯ' => 'ḯ', + 'Ḱ' => 'ḱ', + 'Ḳ' => 'ḳ', + 'Ḵ' => 'ḵ', + 'Ḷ' => 'ḷ', + 'Ḹ' => 'ḹ', + 'Ḻ' => 'ḻ', + 'Ḽ' => 'ḽ', + 'Ḿ' => 'ḿ', + 'Ṁ' => 'ṁ', + 'Ṃ' => 'ṃ', + 'Ṅ' => 'ṅ', + 'Ṇ' => 'ṇ', + 'Ṉ' => 'ṉ', + 'Ṋ' => 'ṋ', + 'Ṍ' => 'ṍ', + 'Ṏ' => 'ṏ', + 'Ṑ' => 'ṑ', + 'Ṓ' => 'ṓ', + 'Ṕ' => 'ṕ', + 'Ṗ' => 'ṗ', + 'Ṙ' => 'ṙ', + 'Ṛ' => 'ṛ', + 'Ṝ' => 'ṝ', + 'Ṟ' => 'ṟ', + 'Ṡ' => 'ṡ', + 'Ṣ' => 'ṣ', + 'Ṥ' => 'ṥ', + 'Ṧ' => 'ṧ', + 'Ṩ' => 'ṩ', + 'Ṫ' => 'ṫ', + 'Ṭ' => 'ṭ', + 'Ṯ' => 'ṯ', + 'Ṱ' => 'ṱ', + 'Ṳ' => 'ṳ', + 'Ṵ' => 'ṵ', + 'Ṷ' => 'ṷ', + 'Ṹ' => 'ṹ', + 'Ṻ' => 'ṻ', + 'Ṽ' => 'ṽ', + 'Ṿ' => 'ṿ', + 'Ẁ' => 'ẁ', + 'Ẃ' => 'ẃ', + 'Ẅ' => 'ẅ', + 'Ẇ' => 'ẇ', + 'Ẉ' => 'ẉ', + 'Ẋ' => 'ẋ', + 'Ẍ' => 'ẍ', + 'Ẏ' => 'ẏ', + 'Ẑ' => 'ẑ', + 'Ẓ' => 'ẓ', + 'Ẕ' => 'ẕ', + 'ẞ' => 'ß', + 'Ạ' => 'ạ', + 'Ả' => 'ả', + 'Ấ' => 'ấ', + 'Ầ' => 'ầ', + 'Ẩ' => 'ẩ', + 'Ẫ' => 'ẫ', + 'Ậ' => 'ậ', + 'Ắ' => 'ắ', + 'Ằ' => 'ằ', + 'Ẳ' => 'ẳ', + 'Ẵ' => 'ẵ', + 'Ặ' => 'ặ', + 'Ẹ' => 'ẹ', + 'Ẻ' => 'ẻ', + 'Ẽ' => 'ẽ', + 'Ế' => 'ế', + 'Ề' => 'ề', + 'Ể' => 'ể', + 'Ễ' => 'ễ', + 'Ệ' => 'ệ', + 'Ỉ' => 'ỉ', + 'Ị' => 'ị', + 'Ọ' => 'ọ', + 'Ỏ' => 'ỏ', + 'Ố' => 'ố', + 'Ồ' => 'ồ', + 'Ổ' => 'ổ', + 'Ỗ' => 'ỗ', + 'Ộ' => 'ộ', + 'Ớ' => 'ớ', + 'Ờ' => 'ờ', + 'Ở' => 'ở', + 'Ỡ' => 'ỡ', + 'Ợ' => 'ợ', + 'Ụ' => 'ụ', + 'Ủ' => 'ủ', + 'Ứ' => 'ứ', + 'Ừ' => 'ừ', + 'Ử' => 'ử', + 'Ữ' => 'ữ', + 'Ự' => 'ự', + 'Ỳ' => 'ỳ', + 'Ỵ' => 'ỵ', + 'Ỷ' => 'ỷ', + 'Ỹ' => 'ỹ', + 'Ỻ' => 'ỻ', + 'Ỽ' => 'ỽ', + 'Ỿ' => 'ỿ', + 'Ἀ' => 'ἀ', + 'Ἁ' => 'ἁ', + 'Ἂ' => 'ἂ', + 'Ἃ' => 'ἃ', + 'Ἄ' => 'ἄ', + 'Ἅ' => 'ἅ', + 'Ἆ' => 'ἆ', + 'Ἇ' => 'ἇ', + 'Ἐ' => 'ἐ', + 'Ἑ' => 'ἑ', + 'Ἒ' => 'ἒ', + 'Ἓ' => 'ἓ', + 'Ἔ' => 'ἔ', + 'Ἕ' => 'ἕ', + 'Ἠ' => 'ἠ', + 'Ἡ' => 'ἡ', + 'Ἢ' => 'ἢ', + 'Ἣ' => 'ἣ', + 'Ἤ' => 'ἤ', + 'Ἥ' => 'ἥ', + 'Ἦ' => 'ἦ', + 'Ἧ' => 'ἧ', + 'Ἰ' => 'ἰ', + 'Ἱ' => 'ἱ', + 'Ἲ' => 'ἲ', + 'Ἳ' => 'ἳ', + 'Ἴ' => 'ἴ', + 'Ἵ' => 'ἵ', + 'Ἶ' => 'ἶ', + 'Ἷ' => 'ἷ', + 'Ὀ' => 'ὀ', + 'Ὁ' => 'ὁ', + 'Ὂ' => 'ὂ', + 'Ὃ' => 'ὃ', + 'Ὄ' => 'ὄ', + 'Ὅ' => 'ὅ', + 'Ὑ' => 'ὑ', + 'Ὓ' => 'ὓ', + 'Ὕ' => 'ὕ', + 'Ὗ' => 'ὗ', + 'Ὠ' => 'ὠ', + 'Ὡ' => 'ὡ', + 'Ὢ' => 'ὢ', + 'Ὣ' => 'ὣ', + 'Ὤ' => 'ὤ', + 'Ὥ' => 'ὥ', + 'Ὦ' => 'ὦ', + 'Ὧ' => 'ὧ', + 'ᾈ' => 'ᾀ', + 'ᾉ' => 'ᾁ', + 'ᾊ' => 'ᾂ', + 'ᾋ' => 'ᾃ', + 'ᾌ' => 'ᾄ', + 'ᾍ' => 'ᾅ', + 'ᾎ' => 'ᾆ', + 'ᾏ' => 'ᾇ', + 'ᾘ' => 'ᾐ', + 'ᾙ' => 'ᾑ', + 'ᾚ' => 'ᾒ', + 'ᾛ' => 'ᾓ', + 'ᾜ' => 'ᾔ', + 'ᾝ' => 'ᾕ', + 'ᾞ' => 'ᾖ', + 'ᾟ' => 'ᾗ', + 'ᾨ' => 'ᾠ', + 'ᾩ' => 'ᾡ', + 'ᾪ' => 'ᾢ', + 'ᾫ' => 'ᾣ', + 'ᾬ' => 'ᾤ', + 'ᾭ' => 'ᾥ', + 'ᾮ' => 'ᾦ', + 'ᾯ' => 'ᾧ', + 'Ᾰ' => 'ᾰ', + 'Ᾱ' => 'ᾱ', + 'Ὰ' => 'ὰ', + 'Ά' => 'ά', + 'ᾼ' => 'ᾳ', + 'Ὲ' => 'ὲ', + 'Έ' => 'έ', + 'Ὴ' => 'ὴ', + 'Ή' => 'ή', + 'ῌ' => 'ῃ', + 'Ῐ' => 'ῐ', + 'Ῑ' => 'ῑ', + 'Ὶ' => 'ὶ', + 'Ί' => 'ί', + 'Ῠ' => 'ῠ', + 'Ῡ' => 'ῡ', + 'Ὺ' => 'ὺ', + 'Ύ' => 'ύ', + 'Ῥ' => 'ῥ', + 'Ὸ' => 'ὸ', + 'Ό' => 'ό', + 'Ὼ' => 'ὼ', + 'Ώ' => 'ώ', + 'ῼ' => 'ῳ', + 'Ω' => 'ω', + 'K' => 'k', + 'Å' => 'å', + 'Ⅎ' => 'ⅎ', + 'Ⅰ' => 'ⅰ', + 'Ⅱ' => 'ⅱ', + 'Ⅲ' => 'ⅲ', + 'Ⅳ' => 'ⅳ', + 'Ⅴ' => 'ⅴ', + 'Ⅵ' => 'ⅵ', + 'Ⅶ' => 'ⅶ', + 'Ⅷ' => 'ⅷ', + 'Ⅸ' => 'ⅸ', + 'Ⅹ' => 'ⅹ', + 'Ⅺ' => 'ⅺ', + 'Ⅻ' => 'ⅻ', + 'Ⅼ' => 'ⅼ', + 'Ⅽ' => 'ⅽ', + 'Ⅾ' => 'ⅾ', + 'Ⅿ' => 'ⅿ', + 'Ↄ' => 'ↄ', + 'Ⓐ' => 'ⓐ', + 'Ⓑ' => 'ⓑ', + 'Ⓒ' => 'ⓒ', + 'Ⓓ' => 'ⓓ', + 'Ⓔ' => 'ⓔ', + 'Ⓕ' => 'ⓕ', + 'Ⓖ' => 'ⓖ', + 'Ⓗ' => 'ⓗ', + 'Ⓘ' => 'ⓘ', + 'Ⓙ' => 'ⓙ', + 'Ⓚ' => 'ⓚ', + 'Ⓛ' => 'ⓛ', + 'Ⓜ' => 'ⓜ', + 'Ⓝ' => 'ⓝ', + 'Ⓞ' => 'ⓞ', + 'Ⓟ' => 'ⓟ', + 'Ⓠ' => 'ⓠ', + 'Ⓡ' => 'ⓡ', + 'Ⓢ' => 'ⓢ', + 'Ⓣ' => 'ⓣ', + 'Ⓤ' => 'ⓤ', + 'Ⓥ' => 'ⓥ', + 'Ⓦ' => 'ⓦ', + 'Ⓧ' => 'ⓧ', + 'Ⓨ' => 'ⓨ', + 'Ⓩ' => 'ⓩ', + 'Ⰰ' => 'ⰰ', + 'Ⰱ' => 'ⰱ', + 'Ⰲ' => 'ⰲ', + 'Ⰳ' => 'ⰳ', + 'Ⰴ' => 'ⰴ', + 'Ⰵ' => 'ⰵ', + 'Ⰶ' => 'ⰶ', + 'Ⰷ' => 'ⰷ', + 'Ⰸ' => 'ⰸ', + 'Ⰹ' => 'ⰹ', + 'Ⰺ' => 'ⰺ', + 'Ⰻ' => 'ⰻ', + 'Ⰼ' => 'ⰼ', + 'Ⰽ' => 'ⰽ', + 'Ⰾ' => 'ⰾ', + 'Ⰿ' => 'ⰿ', + 'Ⱀ' => 'ⱀ', + 'Ⱁ' => 'ⱁ', + 'Ⱂ' => 'ⱂ', + 'Ⱃ' => 'ⱃ', + 'Ⱄ' => 'ⱄ', + 'Ⱅ' => 'ⱅ', + 'Ⱆ' => 'ⱆ', + 'Ⱇ' => 'ⱇ', + 'Ⱈ' => 'ⱈ', + 'Ⱉ' => 'ⱉ', + 'Ⱊ' => 'ⱊ', + 'Ⱋ' => 'ⱋ', + 'Ⱌ' => 'ⱌ', + 'Ⱍ' => 'ⱍ', + 'Ⱎ' => 'ⱎ', + 'Ⱏ' => 'ⱏ', + 'Ⱐ' => 'ⱐ', + 'Ⱑ' => 'ⱑ', + 'Ⱒ' => 'ⱒ', + 'Ⱓ' => 'ⱓ', + 'Ⱔ' => 'ⱔ', + 'Ⱕ' => 'ⱕ', + 'Ⱖ' => 'ⱖ', + 'Ⱗ' => 'ⱗ', + 'Ⱘ' => 'ⱘ', + 'Ⱙ' => 'ⱙ', + 'Ⱚ' => 'ⱚ', + 'Ⱛ' => 'ⱛ', + 'Ⱜ' => 'ⱜ', + 'Ⱝ' => 'ⱝ', + 'Ⱞ' => 'ⱞ', + 'Ⱡ' => 'ⱡ', + 'Ɫ' => 'ɫ', + 'Ᵽ' => 'ᵽ', + 'Ɽ' => 'ɽ', + 'Ⱨ' => 'ⱨ', + 'Ⱪ' => 'ⱪ', + 'Ⱬ' => 'ⱬ', + 'Ɑ' => 'ɑ', + 'Ɱ' => 'ɱ', + 'Ɐ' => 'ɐ', + 'Ɒ' => 'ɒ', + 'Ⱳ' => 'ⱳ', + 'Ⱶ' => 'ⱶ', + 'Ȿ' => 'ȿ', + 'Ɀ' => 'ɀ', + 'Ⲁ' => 'ⲁ', + 'Ⲃ' => 'ⲃ', + 'Ⲅ' => 'ⲅ', + 'Ⲇ' => 'ⲇ', + 'Ⲉ' => 'ⲉ', + 'Ⲋ' => 'ⲋ', + 'Ⲍ' => 'ⲍ', + 'Ⲏ' => 'ⲏ', + 'Ⲑ' => 'ⲑ', + 'Ⲓ' => 'ⲓ', + 'Ⲕ' => 'ⲕ', + 'Ⲗ' => 'ⲗ', + 'Ⲙ' => 'ⲙ', + 'Ⲛ' => 'ⲛ', + 'Ⲝ' => 'ⲝ', + 'Ⲟ' => 'ⲟ', + 'Ⲡ' => 'ⲡ', + 'Ⲣ' => 'ⲣ', + 'Ⲥ' => 'ⲥ', + 'Ⲧ' => 'ⲧ', + 'Ⲩ' => 'ⲩ', + 'Ⲫ' => 'ⲫ', + 'Ⲭ' => 'ⲭ', + 'Ⲯ' => 'ⲯ', + 'Ⲱ' => 'ⲱ', + 'Ⲳ' => 'ⲳ', + 'Ⲵ' => 'ⲵ', + 'Ⲷ' => 'ⲷ', + 'Ⲹ' => 'ⲹ', + 'Ⲻ' => 'ⲻ', + 'Ⲽ' => 'ⲽ', + 'Ⲿ' => 'ⲿ', + 'Ⳁ' => 'ⳁ', + 'Ⳃ' => 'ⳃ', + 'Ⳅ' => 'ⳅ', + 'Ⳇ' => 'ⳇ', + 'Ⳉ' => 'ⳉ', + 'Ⳋ' => 'ⳋ', + 'Ⳍ' => 'ⳍ', + 'Ⳏ' => 'ⳏ', + 'Ⳑ' => 'ⳑ', + 'Ⳓ' => 'ⳓ', + 'Ⳕ' => 'ⳕ', + 'Ⳗ' => 'ⳗ', + 'Ⳙ' => 'ⳙ', + 'Ⳛ' => 'ⳛ', + 'Ⳝ' => 'ⳝ', + 'Ⳟ' => 'ⳟ', + 'Ⳡ' => 'ⳡ', + 'Ⳣ' => 'ⳣ', + 'Ⳬ' => 'ⳬ', + 'Ⳮ' => 'ⳮ', + 'Ⳳ' => 'ⳳ', + 'Ꙁ' => 'ꙁ', + 'Ꙃ' => 'ꙃ', + 'Ꙅ' => 'ꙅ', + 'Ꙇ' => 'ꙇ', + 'Ꙉ' => 'ꙉ', + 'Ꙋ' => 'ꙋ', + 'Ꙍ' => 'ꙍ', + 'Ꙏ' => 'ꙏ', + 'Ꙑ' => 'ꙑ', + 'Ꙓ' => 'ꙓ', + 'Ꙕ' => 'ꙕ', + 'Ꙗ' => 'ꙗ', + 'Ꙙ' => 'ꙙ', + 'Ꙛ' => 'ꙛ', + 'Ꙝ' => 'ꙝ', + 'Ꙟ' => 'ꙟ', + 'Ꙡ' => 'ꙡ', + 'Ꙣ' => 'ꙣ', + 'Ꙥ' => 'ꙥ', + 'Ꙧ' => 'ꙧ', + 'Ꙩ' => 'ꙩ', + 'Ꙫ' => 'ꙫ', + 'Ꙭ' => 'ꙭ', + 'Ꚁ' => 'ꚁ', + 'Ꚃ' => 'ꚃ', + 'Ꚅ' => 'ꚅ', + 'Ꚇ' => 'ꚇ', + 'Ꚉ' => 'ꚉ', + 'Ꚋ' => 'ꚋ', + 'Ꚍ' => 'ꚍ', + 'Ꚏ' => 'ꚏ', + 'Ꚑ' => 'ꚑ', + 'Ꚓ' => 'ꚓ', + 'Ꚕ' => 'ꚕ', + 'Ꚗ' => 'ꚗ', + 'Ꚙ' => 'ꚙ', + 'Ꚛ' => 'ꚛ', + 'Ꜣ' => 'ꜣ', + 'Ꜥ' => 'ꜥ', + 'Ꜧ' => 'ꜧ', + 'Ꜩ' => 'ꜩ', + 'Ꜫ' => 'ꜫ', + 'Ꜭ' => 'ꜭ', + 'Ꜯ' => 'ꜯ', + 'Ꜳ' => 'ꜳ', + 'Ꜵ' => 'ꜵ', + 'Ꜷ' => 'ꜷ', + 'Ꜹ' => 'ꜹ', + 'Ꜻ' => 'ꜻ', + 'Ꜽ' => 'ꜽ', + 'Ꜿ' => 'ꜿ', + 'Ꝁ' => 'ꝁ', + 'Ꝃ' => 'ꝃ', + 'Ꝅ' => 'ꝅ', + 'Ꝇ' => 'ꝇ', + 'Ꝉ' => 'ꝉ', + 'Ꝋ' => 'ꝋ', + 'Ꝍ' => 'ꝍ', + 'Ꝏ' => 'ꝏ', + 'Ꝑ' => 'ꝑ', + 'Ꝓ' => 'ꝓ', + 'Ꝕ' => 'ꝕ', + 'Ꝗ' => 'ꝗ', + 'Ꝙ' => 'ꝙ', + 'Ꝛ' => 'ꝛ', + 'Ꝝ' => 'ꝝ', + 'Ꝟ' => 'ꝟ', + 'Ꝡ' => 'ꝡ', + 'Ꝣ' => 'ꝣ', + 'Ꝥ' => 'ꝥ', + 'Ꝧ' => 'ꝧ', + 'Ꝩ' => 'ꝩ', + 'Ꝫ' => 'ꝫ', + 'Ꝭ' => 'ꝭ', + 'Ꝯ' => 'ꝯ', + 'Ꝺ' => 'ꝺ', + 'Ꝼ' => 'ꝼ', + 'Ᵹ' => 'ᵹ', + 'Ꝿ' => 'ꝿ', + 'Ꞁ' => 'ꞁ', + 'Ꞃ' => 'ꞃ', + 'Ꞅ' => 'ꞅ', + 'Ꞇ' => 'ꞇ', + 'Ꞌ' => 'ꞌ', + 'Ɥ' => 'ɥ', + 'Ꞑ' => 'ꞑ', + 'Ꞓ' => 'ꞓ', + 'Ꞗ' => 'ꞗ', + 'Ꞙ' => 'ꞙ', + 'Ꞛ' => 'ꞛ', + 'Ꞝ' => 'ꞝ', + 'Ꞟ' => 'ꞟ', + 'Ꞡ' => 'ꞡ', + 'Ꞣ' => 'ꞣ', + 'Ꞥ' => 'ꞥ', + 'Ꞧ' => 'ꞧ', + 'Ꞩ' => 'ꞩ', + 'Ɦ' => 'ɦ', + 'Ɜ' => 'ɜ', + 'Ɡ' => 'ɡ', + 'Ɬ' => 'ɬ', + 'Ɪ' => 'ɪ', + 'Ʞ' => 'ʞ', + 'Ʇ' => 'ʇ', + 'Ʝ' => 'ʝ', + 'Ꭓ' => 'ꭓ', + 'Ꞵ' => 'ꞵ', + 'Ꞷ' => 'ꞷ', + 'Ꞹ' => 'ꞹ', + 'Ꞻ' => 'ꞻ', + 'Ꞽ' => 'ꞽ', + 'Ꞿ' => 'ꞿ', + 'Ꟃ' => 'ꟃ', + 'Ꞔ' => 'ꞔ', + 'Ʂ' => 'ʂ', + 'Ᶎ' => 'ᶎ', + 'Ꟈ' => 'ꟈ', + 'Ꟊ' => 'ꟊ', + 'Ꟶ' => 'ꟶ', + 'A' => 'a', + 'B' => 'b', + 'C' => 'c', + 'D' => 'd', + 'E' => 'e', + 'F' => 'f', + 'G' => 'g', + 'H' => 'h', + 'I' => 'i', + 'J' => 'j', + 'K' => 'k', + 'L' => 'l', + 'M' => 'm', + 'N' => 'n', + 'O' => 'o', + 'P' => 'p', + 'Q' => 'q', + 'R' => 'r', + 'S' => 's', + 'T' => 't', + 'U' => 'u', + 'V' => 'v', + 'W' => 'w', + 'X' => 'x', + 'Y' => 'y', + 'Z' => 'z', + '𐐀' => '𐐨', + '𐐁' => '𐐩', + '𐐂' => '𐐪', + '𐐃' => '𐐫', + '𐐄' => '𐐬', + '𐐅' => '𐐭', + '𐐆' => '𐐮', + '𐐇' => '𐐯', + '𐐈' => '𐐰', + '𐐉' => '𐐱', + '𐐊' => '𐐲', + '𐐋' => '𐐳', + '𐐌' => '𐐴', + '𐐍' => '𐐵', + '𐐎' => '𐐶', + '𐐏' => '𐐷', + '𐐐' => '𐐸', + '𐐑' => '𐐹', + '𐐒' => '𐐺', + '𐐓' => '𐐻', + '𐐔' => '𐐼', + '𐐕' => '𐐽', + '𐐖' => '𐐾', + '𐐗' => '𐐿', + '𐐘' => '𐑀', + '𐐙' => '𐑁', + '𐐚' => '𐑂', + '𐐛' => '𐑃', + '𐐜' => '𐑄', + '𐐝' => '𐑅', + '𐐞' => '𐑆', + '𐐟' => '𐑇', + '𐐠' => '𐑈', + '𐐡' => '𐑉', + '𐐢' => '𐑊', + '𐐣' => '𐑋', + '𐐤' => '𐑌', + '𐐥' => '𐑍', + '𐐦' => '𐑎', + '𐐧' => '𐑏', + '𐒰' => '𐓘', + '𐒱' => '𐓙', + '𐒲' => '𐓚', + '𐒳' => '𐓛', + '𐒴' => '𐓜', + '𐒵' => '𐓝', + '𐒶' => '𐓞', + '𐒷' => '𐓟', + '𐒸' => '𐓠', + '𐒹' => '𐓡', + '𐒺' => '𐓢', + '𐒻' => '𐓣', + '𐒼' => '𐓤', + '𐒽' => '𐓥', + '𐒾' => '𐓦', + '𐒿' => '𐓧', + '𐓀' => '𐓨', + '𐓁' => '𐓩', + '𐓂' => '𐓪', + '𐓃' => '𐓫', + '𐓄' => '𐓬', + '𐓅' => '𐓭', + '𐓆' => '𐓮', + '𐓇' => '𐓯', + '𐓈' => '𐓰', + '𐓉' => '𐓱', + '𐓊' => '𐓲', + '𐓋' => '𐓳', + '𐓌' => '𐓴', + '𐓍' => '𐓵', + '𐓎' => '𐓶', + '𐓏' => '𐓷', + '𐓐' => '𐓸', + '𐓑' => '𐓹', + '𐓒' => '𐓺', + '𐓓' => '𐓻', + '𐲀' => '𐳀', + '𐲁' => '𐳁', + '𐲂' => '𐳂', + '𐲃' => '𐳃', + '𐲄' => '𐳄', + '𐲅' => '𐳅', + '𐲆' => '𐳆', + '𐲇' => '𐳇', + '𐲈' => '𐳈', + '𐲉' => '𐳉', + '𐲊' => '𐳊', + '𐲋' => '𐳋', + '𐲌' => '𐳌', + '𐲍' => '𐳍', + '𐲎' => '𐳎', + '𐲏' => '𐳏', + '𐲐' => '𐳐', + '𐲑' => '𐳑', + '𐲒' => '𐳒', + '𐲓' => '𐳓', + '𐲔' => '𐳔', + '𐲕' => '𐳕', + '𐲖' => '𐳖', + '𐲗' => '𐳗', + '𐲘' => '𐳘', + '𐲙' => '𐳙', + '𐲚' => '𐳚', + '𐲛' => '𐳛', + '𐲜' => '𐳜', + '𐲝' => '𐳝', + '𐲞' => '𐳞', + '𐲟' => '𐳟', + '𐲠' => '𐳠', + '𐲡' => '𐳡', + '𐲢' => '𐳢', + '𐲣' => '𐳣', + '𐲤' => '𐳤', + '𐲥' => '𐳥', + '𐲦' => '𐳦', + '𐲧' => '𐳧', + '𐲨' => '𐳨', + '𐲩' => '𐳩', + '𐲪' => '𐳪', + '𐲫' => '𐳫', + '𐲬' => '𐳬', + '𐲭' => '𐳭', + '𐲮' => '𐳮', + '𐲯' => '𐳯', + '𐲰' => '𐳰', + '𐲱' => '𐳱', + '𐲲' => '𐳲', + '𑢠' => '𑣀', + '𑢡' => '𑣁', + '𑢢' => '𑣂', + '𑢣' => '𑣃', + '𑢤' => '𑣄', + '𑢥' => '𑣅', + '𑢦' => '𑣆', + '𑢧' => '𑣇', + '𑢨' => '𑣈', + '𑢩' => '𑣉', + '𑢪' => '𑣊', + '𑢫' => '𑣋', + '𑢬' => '𑣌', + '𑢭' => '𑣍', + '𑢮' => '𑣎', + '𑢯' => '𑣏', + '𑢰' => '𑣐', + '𑢱' => '𑣑', + '𑢲' => '𑣒', + '𑢳' => '𑣓', + '𑢴' => '𑣔', + '𑢵' => '𑣕', + '𑢶' => '𑣖', + '𑢷' => '𑣗', + '𑢸' => '𑣘', + '𑢹' => '𑣙', + '𑢺' => '𑣚', + '𑢻' => '𑣛', + '𑢼' => '𑣜', + '𑢽' => '𑣝', + '𑢾' => '𑣞', + '𑢿' => '𑣟', + '𖹀' => '𖹠', + '𖹁' => '𖹡', + '𖹂' => '𖹢', + '𖹃' => '𖹣', + '𖹄' => '𖹤', + '𖹅' => '𖹥', + '𖹆' => '𖹦', + '𖹇' => '𖹧', + '𖹈' => '𖹨', + '𖹉' => '𖹩', + '𖹊' => '𖹪', + '𖹋' => '𖹫', + '𖹌' => '𖹬', + '𖹍' => '𖹭', + '𖹎' => '𖹮', + '𖹏' => '𖹯', + '𖹐' => '𖹰', + '𖹑' => '𖹱', + '𖹒' => '𖹲', + '𖹓' => '𖹳', + '𖹔' => '𖹴', + '𖹕' => '𖹵', + '𖹖' => '𖹶', + '𖹗' => '𖹷', + '𖹘' => '𖹸', + '𖹙' => '𖹹', + '𖹚' => '𖹺', + '𖹛' => '𖹻', + '𖹜' => '𖹼', + '𖹝' => '𖹽', + '𖹞' => '𖹾', + '𖹟' => '𖹿', + '𞤀' => '𞤢', + '𞤁' => '𞤣', + '𞤂' => '𞤤', + '𞤃' => '𞤥', + '𞤄' => '𞤦', + '𞤅' => '𞤧', + '𞤆' => '𞤨', + '𞤇' => '𞤩', + '𞤈' => '𞤪', + '𞤉' => '𞤫', + '𞤊' => '𞤬', + '𞤋' => '𞤭', + '𞤌' => '𞤮', + '𞤍' => '𞤯', + '𞤎' => '𞤰', + '𞤏' => '𞤱', + '𞤐' => '𞤲', + '𞤑' => '𞤳', + '𞤒' => '𞤴', + '𞤓' => '𞤵', + '𞤔' => '𞤶', + '𞤕' => '𞤷', + '𞤖' => '𞤸', + '𞤗' => '𞤹', + '𞤘' => '𞤺', + '𞤙' => '𞤻', + '𞤚' => '𞤼', + '𞤛' => '𞤽', + '𞤜' => '𞤾', + '𞤝' => '𞤿', + '𞤞' => '𞥀', + '𞤟' => '𞥁', + '𞤠' => '𞥂', + '𞤡' => '𞥃', +); diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php new file mode 100644 index 00000000..2a8f6e73 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php @@ -0,0 +1,5 @@ + 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', + 'e' => 'E', + 'f' => 'F', + 'g' => 'G', + 'h' => 'H', + 'i' => 'I', + 'j' => 'J', + 'k' => 'K', + 'l' => 'L', + 'm' => 'M', + 'n' => 'N', + 'o' => 'O', + 'p' => 'P', + 'q' => 'Q', + 'r' => 'R', + 's' => 'S', + 't' => 'T', + 'u' => 'U', + 'v' => 'V', + 'w' => 'W', + 'x' => 'X', + 'y' => 'Y', + 'z' => 'Z', + 'µ' => 'Μ', + 'à' => 'À', + 'á' => 'Á', + 'â' => 'Â', + 'ã' => 'Ã', + 'ä' => 'Ä', + 'å' => 'Å', + 'æ' => 'Æ', + 'ç' => 'Ç', + 'è' => 'È', + 'é' => 'É', + 'ê' => 'Ê', + 'ë' => 'Ë', + 'ì' => 'Ì', + 'í' => 'Í', + 'î' => 'Î', + 'ï' => 'Ï', + 'ð' => 'Ð', + 'ñ' => 'Ñ', + 'ò' => 'Ò', + 'ó' => 'Ó', + 'ô' => 'Ô', + 'õ' => 'Õ', + 'ö' => 'Ö', + 'ø' => 'Ø', + 'ù' => 'Ù', + 'ú' => 'Ú', + 'û' => 'Û', + 'ü' => 'Ü', + 'ý' => 'Ý', + 'þ' => 'Þ', + 'ÿ' => 'Ÿ', + 'ā' => 'Ā', + 'ă' => 'Ă', + 'ą' => 'Ą', + 'ć' => 'Ć', + 'ĉ' => 'Ĉ', + 'ċ' => 'Ċ', + 'č' => 'Č', + 'ď' => 'Ď', + 'đ' => 'Đ', + 'ē' => 'Ē', + 'ĕ' => 'Ĕ', + 'ė' => 'Ė', + 'ę' => 'Ę', + 'ě' => 'Ě', + 'ĝ' => 'Ĝ', + 'ğ' => 'Ğ', + 'ġ' => 'Ġ', + 'ģ' => 'Ģ', + 'ĥ' => 'Ĥ', + 'ħ' => 'Ħ', + 'ĩ' => 'Ĩ', + 'ī' => 'Ī', + 'ĭ' => 'Ĭ', + 'į' => 'Į', + 'ı' => 'I', + 'ij' => 'IJ', + 'ĵ' => 'Ĵ', + 'ķ' => 'Ķ', + 'ĺ' => 'Ĺ', + 'ļ' => 'Ļ', + 'ľ' => 'Ľ', + 'ŀ' => 'Ŀ', + 'ł' => 'Ł', + 'ń' => 'Ń', + 'ņ' => 'Ņ', + 'ň' => 'Ň', + 'ŋ' => 'Ŋ', + 'ō' => 'Ō', + 'ŏ' => 'Ŏ', + 'ő' => 'Ő', + 'œ' => 'Œ', + 'ŕ' => 'Ŕ', + 'ŗ' => 'Ŗ', + 'ř' => 'Ř', + 'ś' => 'Ś', + 'ŝ' => 'Ŝ', + 'ş' => 'Ş', + 'š' => 'Š', + 'ţ' => 'Ţ', + 'ť' => 'Ť', + 'ŧ' => 'Ŧ', + 'ũ' => 'Ũ', + 'ū' => 'Ū', + 'ŭ' => 'Ŭ', + 'ů' => 'Ů', + 'ű' => 'Ű', + 'ų' => 'Ų', + 'ŵ' => 'Ŵ', + 'ŷ' => 'Ŷ', + 'ź' => 'Ź', + 'ż' => 'Ż', + 'ž' => 'Ž', + 'ſ' => 'S', + 'ƀ' => 'Ƀ', + 'ƃ' => 'Ƃ', + 'ƅ' => 'Ƅ', + 'ƈ' => 'Ƈ', + 'ƌ' => 'Ƌ', + 'ƒ' => 'Ƒ', + 'ƕ' => 'Ƕ', + 'ƙ' => 'Ƙ', + 'ƚ' => 'Ƚ', + 'ƞ' => 'Ƞ', + 'ơ' => 'Ơ', + 'ƣ' => 'Ƣ', + 'ƥ' => 'Ƥ', + 'ƨ' => 'Ƨ', + 'ƭ' => 'Ƭ', + 'ư' => 'Ư', + 'ƴ' => 'Ƴ', + 'ƶ' => 'Ƶ', + 'ƹ' => 'Ƹ', + 'ƽ' => 'Ƽ', + 'ƿ' => 'Ƿ', + 'Dž' => 'DŽ', + 'dž' => 'DŽ', + 'Lj' => 'LJ', + 'lj' => 'LJ', + 'Nj' => 'NJ', + 'nj' => 'NJ', + 'ǎ' => 'Ǎ', + 'ǐ' => 'Ǐ', + 'ǒ' => 'Ǒ', + 'ǔ' => 'Ǔ', + 'ǖ' => 'Ǖ', + 'ǘ' => 'Ǘ', + 'ǚ' => 'Ǚ', + 'ǜ' => 'Ǜ', + 'ǝ' => 'Ǝ', + 'ǟ' => 'Ǟ', + 'ǡ' => 'Ǡ', + 'ǣ' => 'Ǣ', + 'ǥ' => 'Ǥ', + 'ǧ' => 'Ǧ', + 'ǩ' => 'Ǩ', + 'ǫ' => 'Ǫ', + 'ǭ' => 'Ǭ', + 'ǯ' => 'Ǯ', + 'Dz' => 'DZ', + 'dz' => 'DZ', + 'ǵ' => 'Ǵ', + 'ǹ' => 'Ǹ', + 'ǻ' => 'Ǻ', + 'ǽ' => 'Ǽ', + 'ǿ' => 'Ǿ', + 'ȁ' => 'Ȁ', + 'ȃ' => 'Ȃ', + 'ȅ' => 'Ȅ', + 'ȇ' => 'Ȇ', + 'ȉ' => 'Ȉ', + 'ȋ' => 'Ȋ', + 'ȍ' => 'Ȍ', + 'ȏ' => 'Ȏ', + 'ȑ' => 'Ȑ', + 'ȓ' => 'Ȓ', + 'ȕ' => 'Ȕ', + 'ȗ' => 'Ȗ', + 'ș' => 'Ș', + 'ț' => 'Ț', + 'ȝ' => 'Ȝ', + 'ȟ' => 'Ȟ', + 'ȣ' => 'Ȣ', + 'ȥ' => 'Ȥ', + 'ȧ' => 'Ȧ', + 'ȩ' => 'Ȩ', + 'ȫ' => 'Ȫ', + 'ȭ' => 'Ȭ', + 'ȯ' => 'Ȯ', + 'ȱ' => 'Ȱ', + 'ȳ' => 'Ȳ', + 'ȼ' => 'Ȼ', + 'ȿ' => 'Ȿ', + 'ɀ' => 'Ɀ', + 'ɂ' => 'Ɂ', + 'ɇ' => 'Ɇ', + 'ɉ' => 'Ɉ', + 'ɋ' => 'Ɋ', + 'ɍ' => 'Ɍ', + 'ɏ' => 'Ɏ', + 'ɐ' => 'Ɐ', + 'ɑ' => 'Ɑ', + 'ɒ' => 'Ɒ', + 'ɓ' => 'Ɓ', + 'ɔ' => 'Ɔ', + 'ɖ' => 'Ɖ', + 'ɗ' => 'Ɗ', + 'ə' => 'Ə', + 'ɛ' => 'Ɛ', + 'ɜ' => 'Ɜ', + 'ɠ' => 'Ɠ', + 'ɡ' => 'Ɡ', + 'ɣ' => 'Ɣ', + 'ɥ' => 'Ɥ', + 'ɦ' => 'Ɦ', + 'ɨ' => 'Ɨ', + 'ɩ' => 'Ɩ', + 'ɪ' => 'Ɪ', + 'ɫ' => 'Ɫ', + 'ɬ' => 'Ɬ', + 'ɯ' => 'Ɯ', + 'ɱ' => 'Ɱ', + 'ɲ' => 'Ɲ', + 'ɵ' => 'Ɵ', + 'ɽ' => 'Ɽ', + 'ʀ' => 'Ʀ', + 'ʂ' => 'Ʂ', + 'ʃ' => 'Ʃ', + 'ʇ' => 'Ʇ', + 'ʈ' => 'Ʈ', + 'ʉ' => 'Ʉ', + 'ʊ' => 'Ʊ', + 'ʋ' => 'Ʋ', + 'ʌ' => 'Ʌ', + 'ʒ' => 'Ʒ', + 'ʝ' => 'Ʝ', + 'ʞ' => 'Ʞ', + 'ͅ' => 'Ι', + 'ͱ' => 'Ͱ', + 'ͳ' => 'Ͳ', + 'ͷ' => 'Ͷ', + 'ͻ' => 'Ͻ', + 'ͼ' => 'Ͼ', + 'ͽ' => 'Ͽ', + 'ά' => 'Ά', + 'έ' => 'Έ', + 'ή' => 'Ή', + 'ί' => 'Ί', + 'α' => 'Α', + 'β' => 'Β', + 'γ' => 'Γ', + 'δ' => 'Δ', + 'ε' => 'Ε', + 'ζ' => 'Ζ', + 'η' => 'Η', + 'θ' => 'Θ', + 'ι' => 'Ι', + 'κ' => 'Κ', + 'λ' => 'Λ', + 'μ' => 'Μ', + 'ν' => 'Ν', + 'ξ' => 'Ξ', + 'ο' => 'Ο', + 'π' => 'Π', + 'ρ' => 'Ρ', + 'ς' => 'Σ', + 'σ' => 'Σ', + 'τ' => 'Τ', + 'υ' => 'Υ', + 'φ' => 'Φ', + 'χ' => 'Χ', + 'ψ' => 'Ψ', + 'ω' => 'Ω', + 'ϊ' => 'Ϊ', + 'ϋ' => 'Ϋ', + 'ό' => 'Ό', + 'ύ' => 'Ύ', + 'ώ' => 'Ώ', + 'ϐ' => 'Β', + 'ϑ' => 'Θ', + 'ϕ' => 'Φ', + 'ϖ' => 'Π', + 'ϗ' => 'Ϗ', + 'ϙ' => 'Ϙ', + 'ϛ' => 'Ϛ', + 'ϝ' => 'Ϝ', + 'ϟ' => 'Ϟ', + 'ϡ' => 'Ϡ', + 'ϣ' => 'Ϣ', + 'ϥ' => 'Ϥ', + 'ϧ' => 'Ϧ', + 'ϩ' => 'Ϩ', + 'ϫ' => 'Ϫ', + 'ϭ' => 'Ϭ', + 'ϯ' => 'Ϯ', + 'ϰ' => 'Κ', + 'ϱ' => 'Ρ', + 'ϲ' => 'Ϲ', + 'ϳ' => 'Ϳ', + 'ϵ' => 'Ε', + 'ϸ' => 'Ϸ', + 'ϻ' => 'Ϻ', + 'а' => 'А', + 'б' => 'Б', + 'в' => 'В', + 'г' => 'Г', + 'д' => 'Д', + 'е' => 'Е', + 'ж' => 'Ж', + 'з' => 'З', + 'и' => 'И', + 'й' => 'Й', + 'к' => 'К', + 'л' => 'Л', + 'м' => 'М', + 'н' => 'Н', + 'о' => 'О', + 'п' => 'П', + 'р' => 'Р', + 'с' => 'С', + 'т' => 'Т', + 'у' => 'У', + 'ф' => 'Ф', + 'х' => 'Х', + 'ц' => 'Ц', + 'ч' => 'Ч', + 'ш' => 'Ш', + 'щ' => 'Щ', + 'ъ' => 'Ъ', + 'ы' => 'Ы', + 'ь' => 'Ь', + 'э' => 'Э', + 'ю' => 'Ю', + 'я' => 'Я', + 'ѐ' => 'Ѐ', + 'ё' => 'Ё', + 'ђ' => 'Ђ', + 'ѓ' => 'Ѓ', + 'є' => 'Є', + 'ѕ' => 'Ѕ', + 'і' => 'І', + 'ї' => 'Ї', + 'ј' => 'Ј', + 'љ' => 'Љ', + 'њ' => 'Њ', + 'ћ' => 'Ћ', + 'ќ' => 'Ќ', + 'ѝ' => 'Ѝ', + 'ў' => 'Ў', + 'џ' => 'Џ', + 'ѡ' => 'Ѡ', + 'ѣ' => 'Ѣ', + 'ѥ' => 'Ѥ', + 'ѧ' => 'Ѧ', + 'ѩ' => 'Ѩ', + 'ѫ' => 'Ѫ', + 'ѭ' => 'Ѭ', + 'ѯ' => 'Ѯ', + 'ѱ' => 'Ѱ', + 'ѳ' => 'Ѳ', + 'ѵ' => 'Ѵ', + 'ѷ' => 'Ѷ', + 'ѹ' => 'Ѹ', + 'ѻ' => 'Ѻ', + 'ѽ' => 'Ѽ', + 'ѿ' => 'Ѿ', + 'ҁ' => 'Ҁ', + 'ҋ' => 'Ҋ', + 'ҍ' => 'Ҍ', + 'ҏ' => 'Ҏ', + 'ґ' => 'Ґ', + 'ғ' => 'Ғ', + 'ҕ' => 'Ҕ', + 'җ' => 'Җ', + 'ҙ' => 'Ҙ', + 'қ' => 'Қ', + 'ҝ' => 'Ҝ', + 'ҟ' => 'Ҟ', + 'ҡ' => 'Ҡ', + 'ң' => 'Ң', + 'ҥ' => 'Ҥ', + 'ҧ' => 'Ҧ', + 'ҩ' => 'Ҩ', + 'ҫ' => 'Ҫ', + 'ҭ' => 'Ҭ', + 'ү' => 'Ү', + 'ұ' => 'Ұ', + 'ҳ' => 'Ҳ', + 'ҵ' => 'Ҵ', + 'ҷ' => 'Ҷ', + 'ҹ' => 'Ҹ', + 'һ' => 'Һ', + 'ҽ' => 'Ҽ', + 'ҿ' => 'Ҿ', + 'ӂ' => 'Ӂ', + 'ӄ' => 'Ӄ', + 'ӆ' => 'Ӆ', + 'ӈ' => 'Ӈ', + 'ӊ' => 'Ӊ', + 'ӌ' => 'Ӌ', + 'ӎ' => 'Ӎ', + 'ӏ' => 'Ӏ', + 'ӑ' => 'Ӑ', + 'ӓ' => 'Ӓ', + 'ӕ' => 'Ӕ', + 'ӗ' => 'Ӗ', + 'ә' => 'Ә', + 'ӛ' => 'Ӛ', + 'ӝ' => 'Ӝ', + 'ӟ' => 'Ӟ', + 'ӡ' => 'Ӡ', + 'ӣ' => 'Ӣ', + 'ӥ' => 'Ӥ', + 'ӧ' => 'Ӧ', + 'ө' => 'Ө', + 'ӫ' => 'Ӫ', + 'ӭ' => 'Ӭ', + 'ӯ' => 'Ӯ', + 'ӱ' => 'Ӱ', + 'ӳ' => 'Ӳ', + 'ӵ' => 'Ӵ', + 'ӷ' => 'Ӷ', + 'ӹ' => 'Ӹ', + 'ӻ' => 'Ӻ', + 'ӽ' => 'Ӽ', + 'ӿ' => 'Ӿ', + 'ԁ' => 'Ԁ', + 'ԃ' => 'Ԃ', + 'ԅ' => 'Ԅ', + 'ԇ' => 'Ԇ', + 'ԉ' => 'Ԉ', + 'ԋ' => 'Ԋ', + 'ԍ' => 'Ԍ', + 'ԏ' => 'Ԏ', + 'ԑ' => 'Ԑ', + 'ԓ' => 'Ԓ', + 'ԕ' => 'Ԕ', + 'ԗ' => 'Ԗ', + 'ԙ' => 'Ԙ', + 'ԛ' => 'Ԛ', + 'ԝ' => 'Ԝ', + 'ԟ' => 'Ԟ', + 'ԡ' => 'Ԡ', + 'ԣ' => 'Ԣ', + 'ԥ' => 'Ԥ', + 'ԧ' => 'Ԧ', + 'ԩ' => 'Ԩ', + 'ԫ' => 'Ԫ', + 'ԭ' => 'Ԭ', + 'ԯ' => 'Ԯ', + 'ա' => 'Ա', + 'բ' => 'Բ', + 'գ' => 'Գ', + 'դ' => 'Դ', + 'ե' => 'Ե', + 'զ' => 'Զ', + 'է' => 'Է', + 'ը' => 'Ը', + 'թ' => 'Թ', + 'ժ' => 'Ժ', + 'ի' => 'Ի', + 'լ' => 'Լ', + 'խ' => 'Խ', + 'ծ' => 'Ծ', + 'կ' => 'Կ', + 'հ' => 'Հ', + 'ձ' => 'Ձ', + 'ղ' => 'Ղ', + 'ճ' => 'Ճ', + 'մ' => 'Մ', + 'յ' => 'Յ', + 'ն' => 'Ն', + 'շ' => 'Շ', + 'ո' => 'Ո', + 'չ' => 'Չ', + 'պ' => 'Պ', + 'ջ' => 'Ջ', + 'ռ' => 'Ռ', + 'ս' => 'Ս', + 'վ' => 'Վ', + 'տ' => 'Տ', + 'ր' => 'Ր', + 'ց' => 'Ց', + 'ւ' => 'Ւ', + 'փ' => 'Փ', + 'ք' => 'Ք', + 'օ' => 'Օ', + 'ֆ' => 'Ֆ', + 'ა' => 'Ა', + 'ბ' => 'Ბ', + 'გ' => 'Გ', + 'დ' => 'Დ', + 'ე' => 'Ე', + 'ვ' => 'Ვ', + 'ზ' => 'Ზ', + 'თ' => 'Თ', + 'ი' => 'Ი', + 'კ' => 'Კ', + 'ლ' => 'Ლ', + 'მ' => 'Მ', + 'ნ' => 'Ნ', + 'ო' => 'Ო', + 'პ' => 'Პ', + 'ჟ' => 'Ჟ', + 'რ' => 'Რ', + 'ს' => 'Ს', + 'ტ' => 'Ტ', + 'უ' => 'Უ', + 'ფ' => 'Ფ', + 'ქ' => 'Ქ', + 'ღ' => 'Ღ', + 'ყ' => 'Ყ', + 'შ' => 'Შ', + 'ჩ' => 'Ჩ', + 'ც' => 'Ც', + 'ძ' => 'Ძ', + 'წ' => 'Წ', + 'ჭ' => 'Ჭ', + 'ხ' => 'Ხ', + 'ჯ' => 'Ჯ', + 'ჰ' => 'Ჰ', + 'ჱ' => 'Ჱ', + 'ჲ' => 'Ჲ', + 'ჳ' => 'Ჳ', + 'ჴ' => 'Ჴ', + 'ჵ' => 'Ჵ', + 'ჶ' => 'Ჶ', + 'ჷ' => 'Ჷ', + 'ჸ' => 'Ჸ', + 'ჹ' => 'Ჹ', + 'ჺ' => 'Ჺ', + 'ჽ' => 'Ჽ', + 'ჾ' => 'Ჾ', + 'ჿ' => 'Ჿ', + 'ᏸ' => 'Ᏸ', + 'ᏹ' => 'Ᏹ', + 'ᏺ' => 'Ᏺ', + 'ᏻ' => 'Ᏻ', + 'ᏼ' => 'Ᏼ', + 'ᏽ' => 'Ᏽ', + 'ᲀ' => 'В', + 'ᲁ' => 'Д', + 'ᲂ' => 'О', + 'ᲃ' => 'С', + 'ᲄ' => 'Т', + 'ᲅ' => 'Т', + 'ᲆ' => 'Ъ', + 'ᲇ' => 'Ѣ', + 'ᲈ' => 'Ꙋ', + 'ᵹ' => 'Ᵹ', + 'ᵽ' => 'Ᵽ', + 'ᶎ' => 'Ᶎ', + 'ḁ' => 'Ḁ', + 'ḃ' => 'Ḃ', + 'ḅ' => 'Ḅ', + 'ḇ' => 'Ḇ', + 'ḉ' => 'Ḉ', + 'ḋ' => 'Ḋ', + 'ḍ' => 'Ḍ', + 'ḏ' => 'Ḏ', + 'ḑ' => 'Ḑ', + 'ḓ' => 'Ḓ', + 'ḕ' => 'Ḕ', + 'ḗ' => 'Ḗ', + 'ḙ' => 'Ḙ', + 'ḛ' => 'Ḛ', + 'ḝ' => 'Ḝ', + 'ḟ' => 'Ḟ', + 'ḡ' => 'Ḡ', + 'ḣ' => 'Ḣ', + 'ḥ' => 'Ḥ', + 'ḧ' => 'Ḧ', + 'ḩ' => 'Ḩ', + 'ḫ' => 'Ḫ', + 'ḭ' => 'Ḭ', + 'ḯ' => 'Ḯ', + 'ḱ' => 'Ḱ', + 'ḳ' => 'Ḳ', + 'ḵ' => 'Ḵ', + 'ḷ' => 'Ḷ', + 'ḹ' => 'Ḹ', + 'ḻ' => 'Ḻ', + 'ḽ' => 'Ḽ', + 'ḿ' => 'Ḿ', + 'ṁ' => 'Ṁ', + 'ṃ' => 'Ṃ', + 'ṅ' => 'Ṅ', + 'ṇ' => 'Ṇ', + 'ṉ' => 'Ṉ', + 'ṋ' => 'Ṋ', + 'ṍ' => 'Ṍ', + 'ṏ' => 'Ṏ', + 'ṑ' => 'Ṑ', + 'ṓ' => 'Ṓ', + 'ṕ' => 'Ṕ', + 'ṗ' => 'Ṗ', + 'ṙ' => 'Ṙ', + 'ṛ' => 'Ṛ', + 'ṝ' => 'Ṝ', + 'ṟ' => 'Ṟ', + 'ṡ' => 'Ṡ', + 'ṣ' => 'Ṣ', + 'ṥ' => 'Ṥ', + 'ṧ' => 'Ṧ', + 'ṩ' => 'Ṩ', + 'ṫ' => 'Ṫ', + 'ṭ' => 'Ṭ', + 'ṯ' => 'Ṯ', + 'ṱ' => 'Ṱ', + 'ṳ' => 'Ṳ', + 'ṵ' => 'Ṵ', + 'ṷ' => 'Ṷ', + 'ṹ' => 'Ṹ', + 'ṻ' => 'Ṻ', + 'ṽ' => 'Ṽ', + 'ṿ' => 'Ṿ', + 'ẁ' => 'Ẁ', + 'ẃ' => 'Ẃ', + 'ẅ' => 'Ẅ', + 'ẇ' => 'Ẇ', + 'ẉ' => 'Ẉ', + 'ẋ' => 'Ẋ', + 'ẍ' => 'Ẍ', + 'ẏ' => 'Ẏ', + 'ẑ' => 'Ẑ', + 'ẓ' => 'Ẓ', + 'ẕ' => 'Ẕ', + 'ẛ' => 'Ṡ', + 'ạ' => 'Ạ', + 'ả' => 'Ả', + 'ấ' => 'Ấ', + 'ầ' => 'Ầ', + 'ẩ' => 'Ẩ', + 'ẫ' => 'Ẫ', + 'ậ' => 'Ậ', + 'ắ' => 'Ắ', + 'ằ' => 'Ằ', + 'ẳ' => 'Ẳ', + 'ẵ' => 'Ẵ', + 'ặ' => 'Ặ', + 'ẹ' => 'Ẹ', + 'ẻ' => 'Ẻ', + 'ẽ' => 'Ẽ', + 'ế' => 'Ế', + 'ề' => 'Ề', + 'ể' => 'Ể', + 'ễ' => 'Ễ', + 'ệ' => 'Ệ', + 'ỉ' => 'Ỉ', + 'ị' => 'Ị', + 'ọ' => 'Ọ', + 'ỏ' => 'Ỏ', + 'ố' => 'Ố', + 'ồ' => 'Ồ', + 'ổ' => 'Ổ', + 'ỗ' => 'Ỗ', + 'ộ' => 'Ộ', + 'ớ' => 'Ớ', + 'ờ' => 'Ờ', + 'ở' => 'Ở', + 'ỡ' => 'Ỡ', + 'ợ' => 'Ợ', + 'ụ' => 'Ụ', + 'ủ' => 'Ủ', + 'ứ' => 'Ứ', + 'ừ' => 'Ừ', + 'ử' => 'Ử', + 'ữ' => 'Ữ', + 'ự' => 'Ự', + 'ỳ' => 'Ỳ', + 'ỵ' => 'Ỵ', + 'ỷ' => 'Ỷ', + 'ỹ' => 'Ỹ', + 'ỻ' => 'Ỻ', + 'ỽ' => 'Ỽ', + 'ỿ' => 'Ỿ', + 'ἀ' => 'Ἀ', + 'ἁ' => 'Ἁ', + 'ἂ' => 'Ἂ', + 'ἃ' => 'Ἃ', + 'ἄ' => 'Ἄ', + 'ἅ' => 'Ἅ', + 'ἆ' => 'Ἆ', + 'ἇ' => 'Ἇ', + 'ἐ' => 'Ἐ', + 'ἑ' => 'Ἑ', + 'ἒ' => 'Ἒ', + 'ἓ' => 'Ἓ', + 'ἔ' => 'Ἔ', + 'ἕ' => 'Ἕ', + 'ἠ' => 'Ἠ', + 'ἡ' => 'Ἡ', + 'ἢ' => 'Ἢ', + 'ἣ' => 'Ἣ', + 'ἤ' => 'Ἤ', + 'ἥ' => 'Ἥ', + 'ἦ' => 'Ἦ', + 'ἧ' => 'Ἧ', + 'ἰ' => 'Ἰ', + 'ἱ' => 'Ἱ', + 'ἲ' => 'Ἲ', + 'ἳ' => 'Ἳ', + 'ἴ' => 'Ἴ', + 'ἵ' => 'Ἵ', + 'ἶ' => 'Ἶ', + 'ἷ' => 'Ἷ', + 'ὀ' => 'Ὀ', + 'ὁ' => 'Ὁ', + 'ὂ' => 'Ὂ', + 'ὃ' => 'Ὃ', + 'ὄ' => 'Ὄ', + 'ὅ' => 'Ὅ', + 'ὑ' => 'Ὑ', + 'ὓ' => 'Ὓ', + 'ὕ' => 'Ὕ', + 'ὗ' => 'Ὗ', + 'ὠ' => 'Ὠ', + 'ὡ' => 'Ὡ', + 'ὢ' => 'Ὢ', + 'ὣ' => 'Ὣ', + 'ὤ' => 'Ὤ', + 'ὥ' => 'Ὥ', + 'ὦ' => 'Ὦ', + 'ὧ' => 'Ὧ', + 'ὰ' => 'Ὰ', + 'ά' => 'Ά', + 'ὲ' => 'Ὲ', + 'έ' => 'Έ', + 'ὴ' => 'Ὴ', + 'ή' => 'Ή', + 'ὶ' => 'Ὶ', + 'ί' => 'Ί', + 'ὸ' => 'Ὸ', + 'ό' => 'Ό', + 'ὺ' => 'Ὺ', + 'ύ' => 'Ύ', + 'ὼ' => 'Ὼ', + 'ώ' => 'Ώ', + 'ᾀ' => 'ἈΙ', + 'ᾁ' => 'ἉΙ', + 'ᾂ' => 'ἊΙ', + 'ᾃ' => 'ἋΙ', + 'ᾄ' => 'ἌΙ', + 'ᾅ' => 'ἍΙ', + 'ᾆ' => 'ἎΙ', + 'ᾇ' => 'ἏΙ', + 'ᾐ' => 'ἨΙ', + 'ᾑ' => 'ἩΙ', + 'ᾒ' => 'ἪΙ', + 'ᾓ' => 'ἫΙ', + 'ᾔ' => 'ἬΙ', + 'ᾕ' => 'ἭΙ', + 'ᾖ' => 'ἮΙ', + 'ᾗ' => 'ἯΙ', + 'ᾠ' => 'ὨΙ', + 'ᾡ' => 'ὩΙ', + 'ᾢ' => 'ὪΙ', + 'ᾣ' => 'ὫΙ', + 'ᾤ' => 'ὬΙ', + 'ᾥ' => 'ὭΙ', + 'ᾦ' => 'ὮΙ', + 'ᾧ' => 'ὯΙ', + 'ᾰ' => 'Ᾰ', + 'ᾱ' => 'Ᾱ', + 'ᾳ' => 'ΑΙ', + 'ι' => 'Ι', + 'ῃ' => 'ΗΙ', + 'ῐ' => 'Ῐ', + 'ῑ' => 'Ῑ', + 'ῠ' => 'Ῠ', + 'ῡ' => 'Ῡ', + 'ῥ' => 'Ῥ', + 'ῳ' => 'ΩΙ', + 'ⅎ' => 'Ⅎ', + 'ⅰ' => 'Ⅰ', + 'ⅱ' => 'Ⅱ', + 'ⅲ' => 'Ⅲ', + 'ⅳ' => 'Ⅳ', + 'ⅴ' => 'Ⅴ', + 'ⅵ' => 'Ⅵ', + 'ⅶ' => 'Ⅶ', + 'ⅷ' => 'Ⅷ', + 'ⅸ' => 'Ⅸ', + 'ⅹ' => 'Ⅹ', + 'ⅺ' => 'Ⅺ', + 'ⅻ' => 'Ⅻ', + 'ⅼ' => 'Ⅼ', + 'ⅽ' => 'Ⅽ', + 'ⅾ' => 'Ⅾ', + 'ⅿ' => 'Ⅿ', + 'ↄ' => 'Ↄ', + 'ⓐ' => 'Ⓐ', + 'ⓑ' => 'Ⓑ', + 'ⓒ' => 'Ⓒ', + 'ⓓ' => 'Ⓓ', + 'ⓔ' => 'Ⓔ', + 'ⓕ' => 'Ⓕ', + 'ⓖ' => 'Ⓖ', + 'ⓗ' => 'Ⓗ', + 'ⓘ' => 'Ⓘ', + 'ⓙ' => 'Ⓙ', + 'ⓚ' => 'Ⓚ', + 'ⓛ' => 'Ⓛ', + 'ⓜ' => 'Ⓜ', + 'ⓝ' => 'Ⓝ', + 'ⓞ' => 'Ⓞ', + 'ⓟ' => 'Ⓟ', + 'ⓠ' => 'Ⓠ', + 'ⓡ' => 'Ⓡ', + 'ⓢ' => 'Ⓢ', + 'ⓣ' => 'Ⓣ', + 'ⓤ' => 'Ⓤ', + 'ⓥ' => 'Ⓥ', + 'ⓦ' => 'Ⓦ', + 'ⓧ' => 'Ⓧ', + 'ⓨ' => 'Ⓨ', + 'ⓩ' => 'Ⓩ', + 'ⰰ' => 'Ⰰ', + 'ⰱ' => 'Ⰱ', + 'ⰲ' => 'Ⰲ', + 'ⰳ' => 'Ⰳ', + 'ⰴ' => 'Ⰴ', + 'ⰵ' => 'Ⰵ', + 'ⰶ' => 'Ⰶ', + 'ⰷ' => 'Ⰷ', + 'ⰸ' => 'Ⰸ', + 'ⰹ' => 'Ⰹ', + 'ⰺ' => 'Ⰺ', + 'ⰻ' => 'Ⰻ', + 'ⰼ' => 'Ⰼ', + 'ⰽ' => 'Ⰽ', + 'ⰾ' => 'Ⰾ', + 'ⰿ' => 'Ⰿ', + 'ⱀ' => 'Ⱀ', + 'ⱁ' => 'Ⱁ', + 'ⱂ' => 'Ⱂ', + 'ⱃ' => 'Ⱃ', + 'ⱄ' => 'Ⱄ', + 'ⱅ' => 'Ⱅ', + 'ⱆ' => 'Ⱆ', + 'ⱇ' => 'Ⱇ', + 'ⱈ' => 'Ⱈ', + 'ⱉ' => 'Ⱉ', + 'ⱊ' => 'Ⱊ', + 'ⱋ' => 'Ⱋ', + 'ⱌ' => 'Ⱌ', + 'ⱍ' => 'Ⱍ', + 'ⱎ' => 'Ⱎ', + 'ⱏ' => 'Ⱏ', + 'ⱐ' => 'Ⱐ', + 'ⱑ' => 'Ⱑ', + 'ⱒ' => 'Ⱒ', + 'ⱓ' => 'Ⱓ', + 'ⱔ' => 'Ⱔ', + 'ⱕ' => 'Ⱕ', + 'ⱖ' => 'Ⱖ', + 'ⱗ' => 'Ⱗ', + 'ⱘ' => 'Ⱘ', + 'ⱙ' => 'Ⱙ', + 'ⱚ' => 'Ⱚ', + 'ⱛ' => 'Ⱛ', + 'ⱜ' => 'Ⱜ', + 'ⱝ' => 'Ⱝ', + 'ⱞ' => 'Ⱞ', + 'ⱡ' => 'Ⱡ', + 'ⱥ' => 'Ⱥ', + 'ⱦ' => 'Ⱦ', + 'ⱨ' => 'Ⱨ', + 'ⱪ' => 'Ⱪ', + 'ⱬ' => 'Ⱬ', + 'ⱳ' => 'Ⱳ', + 'ⱶ' => 'Ⱶ', + 'ⲁ' => 'Ⲁ', + 'ⲃ' => 'Ⲃ', + 'ⲅ' => 'Ⲅ', + 'ⲇ' => 'Ⲇ', + 'ⲉ' => 'Ⲉ', + 'ⲋ' => 'Ⲋ', + 'ⲍ' => 'Ⲍ', + 'ⲏ' => 'Ⲏ', + 'ⲑ' => 'Ⲑ', + 'ⲓ' => 'Ⲓ', + 'ⲕ' => 'Ⲕ', + 'ⲗ' => 'Ⲗ', + 'ⲙ' => 'Ⲙ', + 'ⲛ' => 'Ⲛ', + 'ⲝ' => 'Ⲝ', + 'ⲟ' => 'Ⲟ', + 'ⲡ' => 'Ⲡ', + 'ⲣ' => 'Ⲣ', + 'ⲥ' => 'Ⲥ', + 'ⲧ' => 'Ⲧ', + 'ⲩ' => 'Ⲩ', + 'ⲫ' => 'Ⲫ', + 'ⲭ' => 'Ⲭ', + 'ⲯ' => 'Ⲯ', + 'ⲱ' => 'Ⲱ', + 'ⲳ' => 'Ⲳ', + 'ⲵ' => 'Ⲵ', + 'ⲷ' => 'Ⲷ', + 'ⲹ' => 'Ⲹ', + 'ⲻ' => 'Ⲻ', + 'ⲽ' => 'Ⲽ', + 'ⲿ' => 'Ⲿ', + 'ⳁ' => 'Ⳁ', + 'ⳃ' => 'Ⳃ', + 'ⳅ' => 'Ⳅ', + 'ⳇ' => 'Ⳇ', + 'ⳉ' => 'Ⳉ', + 'ⳋ' => 'Ⳋ', + 'ⳍ' => 'Ⳍ', + 'ⳏ' => 'Ⳏ', + 'ⳑ' => 'Ⳑ', + 'ⳓ' => 'Ⳓ', + 'ⳕ' => 'Ⳕ', + 'ⳗ' => 'Ⳗ', + 'ⳙ' => 'Ⳙ', + 'ⳛ' => 'Ⳛ', + 'ⳝ' => 'Ⳝ', + 'ⳟ' => 'Ⳟ', + 'ⳡ' => 'Ⳡ', + 'ⳣ' => 'Ⳣ', + 'ⳬ' => 'Ⳬ', + 'ⳮ' => 'Ⳮ', + 'ⳳ' => 'Ⳳ', + 'ⴀ' => 'Ⴀ', + 'ⴁ' => 'Ⴁ', + 'ⴂ' => 'Ⴂ', + 'ⴃ' => 'Ⴃ', + 'ⴄ' => 'Ⴄ', + 'ⴅ' => 'Ⴅ', + 'ⴆ' => 'Ⴆ', + 'ⴇ' => 'Ⴇ', + 'ⴈ' => 'Ⴈ', + 'ⴉ' => 'Ⴉ', + 'ⴊ' => 'Ⴊ', + 'ⴋ' => 'Ⴋ', + 'ⴌ' => 'Ⴌ', + 'ⴍ' => 'Ⴍ', + 'ⴎ' => 'Ⴎ', + 'ⴏ' => 'Ⴏ', + 'ⴐ' => 'Ⴐ', + 'ⴑ' => 'Ⴑ', + 'ⴒ' => 'Ⴒ', + 'ⴓ' => 'Ⴓ', + 'ⴔ' => 'Ⴔ', + 'ⴕ' => 'Ⴕ', + 'ⴖ' => 'Ⴖ', + 'ⴗ' => 'Ⴗ', + 'ⴘ' => 'Ⴘ', + 'ⴙ' => 'Ⴙ', + 'ⴚ' => 'Ⴚ', + 'ⴛ' => 'Ⴛ', + 'ⴜ' => 'Ⴜ', + 'ⴝ' => 'Ⴝ', + 'ⴞ' => 'Ⴞ', + 'ⴟ' => 'Ⴟ', + 'ⴠ' => 'Ⴠ', + 'ⴡ' => 'Ⴡ', + 'ⴢ' => 'Ⴢ', + 'ⴣ' => 'Ⴣ', + 'ⴤ' => 'Ⴤ', + 'ⴥ' => 'Ⴥ', + 'ⴧ' => 'Ⴧ', + 'ⴭ' => 'Ⴭ', + 'ꙁ' => 'Ꙁ', + 'ꙃ' => 'Ꙃ', + 'ꙅ' => 'Ꙅ', + 'ꙇ' => 'Ꙇ', + 'ꙉ' => 'Ꙉ', + 'ꙋ' => 'Ꙋ', + 'ꙍ' => 'Ꙍ', + 'ꙏ' => 'Ꙏ', + 'ꙑ' => 'Ꙑ', + 'ꙓ' => 'Ꙓ', + 'ꙕ' => 'Ꙕ', + 'ꙗ' => 'Ꙗ', + 'ꙙ' => 'Ꙙ', + 'ꙛ' => 'Ꙛ', + 'ꙝ' => 'Ꙝ', + 'ꙟ' => 'Ꙟ', + 'ꙡ' => 'Ꙡ', + 'ꙣ' => 'Ꙣ', + 'ꙥ' => 'Ꙥ', + 'ꙧ' => 'Ꙧ', + 'ꙩ' => 'Ꙩ', + 'ꙫ' => 'Ꙫ', + 'ꙭ' => 'Ꙭ', + 'ꚁ' => 'Ꚁ', + 'ꚃ' => 'Ꚃ', + 'ꚅ' => 'Ꚅ', + 'ꚇ' => 'Ꚇ', + 'ꚉ' => 'Ꚉ', + 'ꚋ' => 'Ꚋ', + 'ꚍ' => 'Ꚍ', + 'ꚏ' => 'Ꚏ', + 'ꚑ' => 'Ꚑ', + 'ꚓ' => 'Ꚓ', + 'ꚕ' => 'Ꚕ', + 'ꚗ' => 'Ꚗ', + 'ꚙ' => 'Ꚙ', + 'ꚛ' => 'Ꚛ', + 'ꜣ' => 'Ꜣ', + 'ꜥ' => 'Ꜥ', + 'ꜧ' => 'Ꜧ', + 'ꜩ' => 'Ꜩ', + 'ꜫ' => 'Ꜫ', + 'ꜭ' => 'Ꜭ', + 'ꜯ' => 'Ꜯ', + 'ꜳ' => 'Ꜳ', + 'ꜵ' => 'Ꜵ', + 'ꜷ' => 'Ꜷ', + 'ꜹ' => 'Ꜹ', + 'ꜻ' => 'Ꜻ', + 'ꜽ' => 'Ꜽ', + 'ꜿ' => 'Ꜿ', + 'ꝁ' => 'Ꝁ', + 'ꝃ' => 'Ꝃ', + 'ꝅ' => 'Ꝅ', + 'ꝇ' => 'Ꝇ', + 'ꝉ' => 'Ꝉ', + 'ꝋ' => 'Ꝋ', + 'ꝍ' => 'Ꝍ', + 'ꝏ' => 'Ꝏ', + 'ꝑ' => 'Ꝑ', + 'ꝓ' => 'Ꝓ', + 'ꝕ' => 'Ꝕ', + 'ꝗ' => 'Ꝗ', + 'ꝙ' => 'Ꝙ', + 'ꝛ' => 'Ꝛ', + 'ꝝ' => 'Ꝝ', + 'ꝟ' => 'Ꝟ', + 'ꝡ' => 'Ꝡ', + 'ꝣ' => 'Ꝣ', + 'ꝥ' => 'Ꝥ', + 'ꝧ' => 'Ꝧ', + 'ꝩ' => 'Ꝩ', + 'ꝫ' => 'Ꝫ', + 'ꝭ' => 'Ꝭ', + 'ꝯ' => 'Ꝯ', + 'ꝺ' => 'Ꝺ', + 'ꝼ' => 'Ꝼ', + 'ꝿ' => 'Ꝿ', + 'ꞁ' => 'Ꞁ', + 'ꞃ' => 'Ꞃ', + 'ꞅ' => 'Ꞅ', + 'ꞇ' => 'Ꞇ', + 'ꞌ' => 'Ꞌ', + 'ꞑ' => 'Ꞑ', + 'ꞓ' => 'Ꞓ', + 'ꞔ' => 'Ꞔ', + 'ꞗ' => 'Ꞗ', + 'ꞙ' => 'Ꞙ', + 'ꞛ' => 'Ꞛ', + 'ꞝ' => 'Ꞝ', + 'ꞟ' => 'Ꞟ', + 'ꞡ' => 'Ꞡ', + 'ꞣ' => 'Ꞣ', + 'ꞥ' => 'Ꞥ', + 'ꞧ' => 'Ꞧ', + 'ꞩ' => 'Ꞩ', + 'ꞵ' => 'Ꞵ', + 'ꞷ' => 'Ꞷ', + 'ꞹ' => 'Ꞹ', + 'ꞻ' => 'Ꞻ', + 'ꞽ' => 'Ꞽ', + 'ꞿ' => 'Ꞿ', + 'ꟃ' => 'Ꟃ', + 'ꟈ' => 'Ꟈ', + 'ꟊ' => 'Ꟊ', + 'ꟶ' => 'Ꟶ', + 'ꭓ' => 'Ꭓ', + 'ꭰ' => 'Ꭰ', + 'ꭱ' => 'Ꭱ', + 'ꭲ' => 'Ꭲ', + 'ꭳ' => 'Ꭳ', + 'ꭴ' => 'Ꭴ', + 'ꭵ' => 'Ꭵ', + 'ꭶ' => 'Ꭶ', + 'ꭷ' => 'Ꭷ', + 'ꭸ' => 'Ꭸ', + 'ꭹ' => 'Ꭹ', + 'ꭺ' => 'Ꭺ', + 'ꭻ' => 'Ꭻ', + 'ꭼ' => 'Ꭼ', + 'ꭽ' => 'Ꭽ', + 'ꭾ' => 'Ꭾ', + 'ꭿ' => 'Ꭿ', + 'ꮀ' => 'Ꮀ', + 'ꮁ' => 'Ꮁ', + 'ꮂ' => 'Ꮂ', + 'ꮃ' => 'Ꮃ', + 'ꮄ' => 'Ꮄ', + 'ꮅ' => 'Ꮅ', + 'ꮆ' => 'Ꮆ', + 'ꮇ' => 'Ꮇ', + 'ꮈ' => 'Ꮈ', + 'ꮉ' => 'Ꮉ', + 'ꮊ' => 'Ꮊ', + 'ꮋ' => 'Ꮋ', + 'ꮌ' => 'Ꮌ', + 'ꮍ' => 'Ꮍ', + 'ꮎ' => 'Ꮎ', + 'ꮏ' => 'Ꮏ', + 'ꮐ' => 'Ꮐ', + 'ꮑ' => 'Ꮑ', + 'ꮒ' => 'Ꮒ', + 'ꮓ' => 'Ꮓ', + 'ꮔ' => 'Ꮔ', + 'ꮕ' => 'Ꮕ', + 'ꮖ' => 'Ꮖ', + 'ꮗ' => 'Ꮗ', + 'ꮘ' => 'Ꮘ', + 'ꮙ' => 'Ꮙ', + 'ꮚ' => 'Ꮚ', + 'ꮛ' => 'Ꮛ', + 'ꮜ' => 'Ꮜ', + 'ꮝ' => 'Ꮝ', + 'ꮞ' => 'Ꮞ', + 'ꮟ' => 'Ꮟ', + 'ꮠ' => 'Ꮠ', + 'ꮡ' => 'Ꮡ', + 'ꮢ' => 'Ꮢ', + 'ꮣ' => 'Ꮣ', + 'ꮤ' => 'Ꮤ', + 'ꮥ' => 'Ꮥ', + 'ꮦ' => 'Ꮦ', + 'ꮧ' => 'Ꮧ', + 'ꮨ' => 'Ꮨ', + 'ꮩ' => 'Ꮩ', + 'ꮪ' => 'Ꮪ', + 'ꮫ' => 'Ꮫ', + 'ꮬ' => 'Ꮬ', + 'ꮭ' => 'Ꮭ', + 'ꮮ' => 'Ꮮ', + 'ꮯ' => 'Ꮯ', + 'ꮰ' => 'Ꮰ', + 'ꮱ' => 'Ꮱ', + 'ꮲ' => 'Ꮲ', + 'ꮳ' => 'Ꮳ', + 'ꮴ' => 'Ꮴ', + 'ꮵ' => 'Ꮵ', + 'ꮶ' => 'Ꮶ', + 'ꮷ' => 'Ꮷ', + 'ꮸ' => 'Ꮸ', + 'ꮹ' => 'Ꮹ', + 'ꮺ' => 'Ꮺ', + 'ꮻ' => 'Ꮻ', + 'ꮼ' => 'Ꮼ', + 'ꮽ' => 'Ꮽ', + 'ꮾ' => 'Ꮾ', + 'ꮿ' => 'Ꮿ', + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', + 'e' => 'E', + 'f' => 'F', + 'g' => 'G', + 'h' => 'H', + 'i' => 'I', + 'j' => 'J', + 'k' => 'K', + 'l' => 'L', + 'm' => 'M', + 'n' => 'N', + 'o' => 'O', + 'p' => 'P', + 'q' => 'Q', + 'r' => 'R', + 's' => 'S', + 't' => 'T', + 'u' => 'U', + 'v' => 'V', + 'w' => 'W', + 'x' => 'X', + 'y' => 'Y', + 'z' => 'Z', + '𐐨' => '𐐀', + '𐐩' => '𐐁', + '𐐪' => '𐐂', + '𐐫' => '𐐃', + '𐐬' => '𐐄', + '𐐭' => '𐐅', + '𐐮' => '𐐆', + '𐐯' => '𐐇', + '𐐰' => '𐐈', + '𐐱' => '𐐉', + '𐐲' => '𐐊', + '𐐳' => '𐐋', + '𐐴' => '𐐌', + '𐐵' => '𐐍', + '𐐶' => '𐐎', + '𐐷' => '𐐏', + '𐐸' => '𐐐', + '𐐹' => '𐐑', + '𐐺' => '𐐒', + '𐐻' => '𐐓', + '𐐼' => '𐐔', + '𐐽' => '𐐕', + '𐐾' => '𐐖', + '𐐿' => '𐐗', + '𐑀' => '𐐘', + '𐑁' => '𐐙', + '𐑂' => '𐐚', + '𐑃' => '𐐛', + '𐑄' => '𐐜', + '𐑅' => '𐐝', + '𐑆' => '𐐞', + '𐑇' => '𐐟', + '𐑈' => '𐐠', + '𐑉' => '𐐡', + '𐑊' => '𐐢', + '𐑋' => '𐐣', + '𐑌' => '𐐤', + '𐑍' => '𐐥', + '𐑎' => '𐐦', + '𐑏' => '𐐧', + '𐓘' => '𐒰', + '𐓙' => '𐒱', + '𐓚' => '𐒲', + '𐓛' => '𐒳', + '𐓜' => '𐒴', + '𐓝' => '𐒵', + '𐓞' => '𐒶', + '𐓟' => '𐒷', + '𐓠' => '𐒸', + '𐓡' => '𐒹', + '𐓢' => '𐒺', + '𐓣' => '𐒻', + '𐓤' => '𐒼', + '𐓥' => '𐒽', + '𐓦' => '𐒾', + '𐓧' => '𐒿', + '𐓨' => '𐓀', + '𐓩' => '𐓁', + '𐓪' => '𐓂', + '𐓫' => '𐓃', + '𐓬' => '𐓄', + '𐓭' => '𐓅', + '𐓮' => '𐓆', + '𐓯' => '𐓇', + '𐓰' => '𐓈', + '𐓱' => '𐓉', + '𐓲' => '𐓊', + '𐓳' => '𐓋', + '𐓴' => '𐓌', + '𐓵' => '𐓍', + '𐓶' => '𐓎', + '𐓷' => '𐓏', + '𐓸' => '𐓐', + '𐓹' => '𐓑', + '𐓺' => '𐓒', + '𐓻' => '𐓓', + '𐳀' => '𐲀', + '𐳁' => '𐲁', + '𐳂' => '𐲂', + '𐳃' => '𐲃', + '𐳄' => '𐲄', + '𐳅' => '𐲅', + '𐳆' => '𐲆', + '𐳇' => '𐲇', + '𐳈' => '𐲈', + '𐳉' => '𐲉', + '𐳊' => '𐲊', + '𐳋' => '𐲋', + '𐳌' => '𐲌', + '𐳍' => '𐲍', + '𐳎' => '𐲎', + '𐳏' => '𐲏', + '𐳐' => '𐲐', + '𐳑' => '𐲑', + '𐳒' => '𐲒', + '𐳓' => '𐲓', + '𐳔' => '𐲔', + '𐳕' => '𐲕', + '𐳖' => '𐲖', + '𐳗' => '𐲗', + '𐳘' => '𐲘', + '𐳙' => '𐲙', + '𐳚' => '𐲚', + '𐳛' => '𐲛', + '𐳜' => '𐲜', + '𐳝' => '𐲝', + '𐳞' => '𐲞', + '𐳟' => '𐲟', + '𐳠' => '𐲠', + '𐳡' => '𐲡', + '𐳢' => '𐲢', + '𐳣' => '𐲣', + '𐳤' => '𐲤', + '𐳥' => '𐲥', + '𐳦' => '𐲦', + '𐳧' => '𐲧', + '𐳨' => '𐲨', + '𐳩' => '𐲩', + '𐳪' => '𐲪', + '𐳫' => '𐲫', + '𐳬' => '𐲬', + '𐳭' => '𐲭', + '𐳮' => '𐲮', + '𐳯' => '𐲯', + '𐳰' => '𐲰', + '𐳱' => '𐲱', + '𐳲' => '𐲲', + '𑣀' => '𑢠', + '𑣁' => '𑢡', + '𑣂' => '𑢢', + '𑣃' => '𑢣', + '𑣄' => '𑢤', + '𑣅' => '𑢥', + '𑣆' => '𑢦', + '𑣇' => '𑢧', + '𑣈' => '𑢨', + '𑣉' => '𑢩', + '𑣊' => '𑢪', + '𑣋' => '𑢫', + '𑣌' => '𑢬', + '𑣍' => '𑢭', + '𑣎' => '𑢮', + '𑣏' => '𑢯', + '𑣐' => '𑢰', + '𑣑' => '𑢱', + '𑣒' => '𑢲', + '𑣓' => '𑢳', + '𑣔' => '𑢴', + '𑣕' => '𑢵', + '𑣖' => '𑢶', + '𑣗' => '𑢷', + '𑣘' => '𑢸', + '𑣙' => '𑢹', + '𑣚' => '𑢺', + '𑣛' => '𑢻', + '𑣜' => '𑢼', + '𑣝' => '𑢽', + '𑣞' => '𑢾', + '𑣟' => '𑢿', + '𖹠' => '𖹀', + '𖹡' => '𖹁', + '𖹢' => '𖹂', + '𖹣' => '𖹃', + '𖹤' => '𖹄', + '𖹥' => '𖹅', + '𖹦' => '𖹆', + '𖹧' => '𖹇', + '𖹨' => '𖹈', + '𖹩' => '𖹉', + '𖹪' => '𖹊', + '𖹫' => '𖹋', + '𖹬' => '𖹌', + '𖹭' => '𖹍', + '𖹮' => '𖹎', + '𖹯' => '𖹏', + '𖹰' => '𖹐', + '𖹱' => '𖹑', + '𖹲' => '𖹒', + '𖹳' => '𖹓', + '𖹴' => '𖹔', + '𖹵' => '𖹕', + '𖹶' => '𖹖', + '𖹷' => '𖹗', + '𖹸' => '𖹘', + '𖹹' => '𖹙', + '𖹺' => '𖹚', + '𖹻' => '𖹛', + '𖹼' => '𖹜', + '𖹽' => '𖹝', + '𖹾' => '𖹞', + '𖹿' => '𖹟', + '𞤢' => '𞤀', + '𞤣' => '𞤁', + '𞤤' => '𞤂', + '𞤥' => '𞤃', + '𞤦' => '𞤄', + '𞤧' => '𞤅', + '𞤨' => '𞤆', + '𞤩' => '𞤇', + '𞤪' => '𞤈', + '𞤫' => '𞤉', + '𞤬' => '𞤊', + '𞤭' => '𞤋', + '𞤮' => '𞤌', + '𞤯' => '𞤍', + '𞤰' => '𞤎', + '𞤱' => '𞤏', + '𞤲' => '𞤐', + '𞤳' => '𞤑', + '𞤴' => '𞤒', + '𞤵' => '𞤓', + '𞤶' => '𞤔', + '𞤷' => '𞤕', + '𞤸' => '𞤖', + '𞤹' => '𞤗', + '𞤺' => '𞤘', + '𞤻' => '𞤙', + '𞤼' => '𞤚', + '𞤽' => '𞤛', + '𞤾' => '𞤜', + '𞤿' => '𞤝', + '𞥀' => '𞤞', + '𞥁' => '𞤟', + '𞥂' => '𞤠', + '𞥃' => '𞤡', + 'ß' => 'SS', + 'ff' => 'FF', + 'fi' => 'FI', + 'fl' => 'FL', + 'ffi' => 'FFI', + 'ffl' => 'FFL', + 'ſt' => 'ST', + 'st' => 'ST', + 'և' => 'ԵՒ', + 'ﬓ' => 'ՄՆ', + 'ﬔ' => 'ՄԵ', + 'ﬕ' => 'ՄԻ', + 'ﬖ' => 'ՎՆ', + 'ﬗ' => 'ՄԽ', + 'ʼn' => 'ʼN', + 'ΐ' => 'Ϊ́', + 'ΰ' => 'Ϋ́', + 'ǰ' => 'J̌', + 'ẖ' => 'H̱', + 'ẗ' => 'T̈', + 'ẘ' => 'W̊', + 'ẙ' => 'Y̊', + 'ẚ' => 'Aʾ', + 'ὐ' => 'Υ̓', + 'ὒ' => 'Υ̓̀', + 'ὔ' => 'Υ̓́', + 'ὖ' => 'Υ̓͂', + 'ᾶ' => 'Α͂', + 'ῆ' => 'Η͂', + 'ῒ' => 'Ϊ̀', + 'ΐ' => 'Ϊ́', + 'ῖ' => 'Ι͂', + 'ῗ' => 'Ϊ͂', + 'ῢ' => 'Ϋ̀', + 'ΰ' => 'Ϋ́', + 'ῤ' => 'Ρ̓', + 'ῦ' => 'Υ͂', + 'ῧ' => 'Ϋ͂', + 'ῶ' => 'Ω͂', + 'ᾈ' => 'ἈΙ', + 'ᾉ' => 'ἉΙ', + 'ᾊ' => 'ἊΙ', + 'ᾋ' => 'ἋΙ', + 'ᾌ' => 'ἌΙ', + 'ᾍ' => 'ἍΙ', + 'ᾎ' => 'ἎΙ', + 'ᾏ' => 'ἏΙ', + 'ᾘ' => 'ἨΙ', + 'ᾙ' => 'ἩΙ', + 'ᾚ' => 'ἪΙ', + 'ᾛ' => 'ἫΙ', + 'ᾜ' => 'ἬΙ', + 'ᾝ' => 'ἭΙ', + 'ᾞ' => 'ἮΙ', + 'ᾟ' => 'ἯΙ', + 'ᾨ' => 'ὨΙ', + 'ᾩ' => 'ὩΙ', + 'ᾪ' => 'ὪΙ', + 'ᾫ' => 'ὫΙ', + 'ᾬ' => 'ὬΙ', + 'ᾭ' => 'ὭΙ', + 'ᾮ' => 'ὮΙ', + 'ᾯ' => 'ὯΙ', + 'ᾼ' => 'ΑΙ', + 'ῌ' => 'ΗΙ', + 'ῼ' => 'ΩΙ', + 'ᾲ' => 'ᾺΙ', + 'ᾴ' => 'ΆΙ', + 'ῂ' => 'ῊΙ', + 'ῄ' => 'ΉΙ', + 'ῲ' => 'ῺΙ', + 'ῴ' => 'ΏΙ', + 'ᾷ' => 'Α͂Ι', + 'ῇ' => 'Η͂Ι', + 'ῷ' => 'Ω͂Ι', +); diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/bootstrap.php b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/bootstrap.php new file mode 100644 index 00000000..ecf1a035 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/bootstrap.php @@ -0,0 +1,151 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Mbstring as p; + +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + +if (!function_exists('mb_convert_encoding')) { + function mb_convert_encoding($string, $to_encoding, $from_encoding = null) { return p\Mbstring::mb_convert_encoding($string, $to_encoding, $from_encoding); } +} +if (!function_exists('mb_decode_mimeheader')) { + function mb_decode_mimeheader($string) { return p\Mbstring::mb_decode_mimeheader($string); } +} +if (!function_exists('mb_encode_mimeheader')) { + function mb_encode_mimeheader($string, $charset = null, $transfer_encoding = null, $newline = "\r\n", $indent = 0) { return p\Mbstring::mb_encode_mimeheader($string, $charset, $transfer_encoding, $newline, $indent); } +} +if (!function_exists('mb_decode_numericentity')) { + function mb_decode_numericentity($string, $map, $encoding = null) { return p\Mbstring::mb_decode_numericentity($string, $map, $encoding); } +} +if (!function_exists('mb_encode_numericentity')) { + function mb_encode_numericentity($string, $map, $encoding = null, $hex = false) { return p\Mbstring::mb_encode_numericentity($string, $map, $encoding, $hex); } +} +if (!function_exists('mb_convert_case')) { + function mb_convert_case($string, $mode, $encoding = null) { return p\Mbstring::mb_convert_case($string, $mode, $encoding); } +} +if (!function_exists('mb_internal_encoding')) { + function mb_internal_encoding($encoding = null) { return p\Mbstring::mb_internal_encoding($encoding); } +} +if (!function_exists('mb_language')) { + function mb_language($language = null) { return p\Mbstring::mb_language($language); } +} +if (!function_exists('mb_list_encodings')) { + function mb_list_encodings() { return p\Mbstring::mb_list_encodings(); } +} +if (!function_exists('mb_encoding_aliases')) { + function mb_encoding_aliases($encoding) { return p\Mbstring::mb_encoding_aliases($encoding); } +} +if (!function_exists('mb_check_encoding')) { + function mb_check_encoding($value = null, $encoding = null) { return p\Mbstring::mb_check_encoding($value, $encoding); } +} +if (!function_exists('mb_detect_encoding')) { + function mb_detect_encoding($string, $encodings = null, $strict = false) { return p\Mbstring::mb_detect_encoding($string, $encodings, $strict); } +} +if (!function_exists('mb_detect_order')) { + function mb_detect_order($encoding = null) { return p\Mbstring::mb_detect_order($encoding); } +} +if (!function_exists('mb_parse_str')) { + function mb_parse_str($string, &$result = []) { parse_str($string, $result); return (bool) $result; } +} +if (!function_exists('mb_strlen')) { + function mb_strlen($string, $encoding = null) { return p\Mbstring::mb_strlen($string, $encoding); } +} +if (!function_exists('mb_strpos')) { + function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strpos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_strtolower')) { + function mb_strtolower($string, $encoding = null) { return p\Mbstring::mb_strtolower($string, $encoding); } +} +if (!function_exists('mb_strtoupper')) { + function mb_strtoupper($string, $encoding = null) { return p\Mbstring::mb_strtoupper($string, $encoding); } +} +if (!function_exists('mb_substitute_character')) { + function mb_substitute_character($substitute_character = null) { return p\Mbstring::mb_substitute_character($substitute_character); } +} +if (!function_exists('mb_substr')) { + function mb_substr($string, $start, $length = 2147483647, $encoding = null) { return p\Mbstring::mb_substr($string, $start, $length, $encoding); } +} +if (!function_exists('mb_stripos')) { + function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_stripos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_stristr')) { + function mb_stristr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_stristr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_strrchr')) { + function mb_strrchr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrchr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_strrichr')) { + function mb_strrichr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrichr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_strripos')) { + function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strripos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_strrpos')) { + function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strrpos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_strstr')) { + function mb_strstr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strstr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_get_info')) { + function mb_get_info($type = 'all') { return p\Mbstring::mb_get_info($type); } +} +if (!function_exists('mb_http_output')) { + function mb_http_output($encoding = null) { return p\Mbstring::mb_http_output($encoding); } +} +if (!function_exists('mb_strwidth')) { + function mb_strwidth($string, $encoding = null) { return p\Mbstring::mb_strwidth($string, $encoding); } +} +if (!function_exists('mb_substr_count')) { + function mb_substr_count($haystack, $needle, $encoding = null) { return p\Mbstring::mb_substr_count($haystack, $needle, $encoding); } +} +if (!function_exists('mb_output_handler')) { + function mb_output_handler($string, $status) { return p\Mbstring::mb_output_handler($string, $status); } +} +if (!function_exists('mb_http_input')) { + function mb_http_input($type = null) { return p\Mbstring::mb_http_input($type); } +} + +if (!function_exists('mb_convert_variables')) { + function mb_convert_variables($to_encoding, $from_encoding, &...$vars) { return p\Mbstring::mb_convert_variables($to_encoding, $from_encoding, ...$vars); } +} + +if (!function_exists('mb_ord')) { + function mb_ord($string, $encoding = null) { return p\Mbstring::mb_ord($string, $encoding); } +} +if (!function_exists('mb_chr')) { + function mb_chr($codepoint, $encoding = null) { return p\Mbstring::mb_chr($codepoint, $encoding); } +} +if (!function_exists('mb_scrub')) { + function mb_scrub($string, $encoding = null) { $encoding = null === $encoding ? mb_internal_encoding() : $encoding; return mb_convert_encoding($string, $encoding, $encoding); } +} +if (!function_exists('mb_str_split')) { + function mb_str_split($string, $length = 1, $encoding = null) { return p\Mbstring::mb_str_split($string, $length, $encoding); } +} + +if (!function_exists('mb_str_pad')) { + function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = STR_PAD_RIGHT, ?string $encoding = null): string { return p\Mbstring::mb_str_pad($string, $length, $pad_string, $pad_type, $encoding); } +} + +if (extension_loaded('mbstring')) { + return; +} + +if (!defined('MB_CASE_UPPER')) { + define('MB_CASE_UPPER', 0); +} +if (!defined('MB_CASE_LOWER')) { + define('MB_CASE_LOWER', 1); +} +if (!defined('MB_CASE_TITLE')) { + define('MB_CASE_TITLE', 2); +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/bootstrap80.php b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/bootstrap80.php new file mode 100644 index 00000000..2f9fb5b4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/bootstrap80.php @@ -0,0 +1,147 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Mbstring as p; + +if (!function_exists('mb_convert_encoding')) { + function mb_convert_encoding(array|string|null $string, ?string $to_encoding, array|string|null $from_encoding = null): array|string|false { return p\Mbstring::mb_convert_encoding($string ?? '', (string) $to_encoding, $from_encoding); } +} +if (!function_exists('mb_decode_mimeheader')) { + function mb_decode_mimeheader(?string $string): string { return p\Mbstring::mb_decode_mimeheader((string) $string); } +} +if (!function_exists('mb_encode_mimeheader')) { + function mb_encode_mimeheader(?string $string, ?string $charset = null, ?string $transfer_encoding = null, ?string $newline = "\r\n", ?int $indent = 0): string { return p\Mbstring::mb_encode_mimeheader((string) $string, $charset, $transfer_encoding, (string) $newline, (int) $indent); } +} +if (!function_exists('mb_decode_numericentity')) { + function mb_decode_numericentity(?string $string, array $map, ?string $encoding = null): string { return p\Mbstring::mb_decode_numericentity((string) $string, $map, $encoding); } +} +if (!function_exists('mb_encode_numericentity')) { + function mb_encode_numericentity(?string $string, array $map, ?string $encoding = null, ?bool $hex = false): string { return p\Mbstring::mb_encode_numericentity((string) $string, $map, $encoding, (bool) $hex); } +} +if (!function_exists('mb_convert_case')) { + function mb_convert_case(?string $string, ?int $mode, ?string $encoding = null): string { return p\Mbstring::mb_convert_case((string) $string, (int) $mode, $encoding); } +} +if (!function_exists('mb_internal_encoding')) { + function mb_internal_encoding(?string $encoding = null): string|bool { return p\Mbstring::mb_internal_encoding($encoding); } +} +if (!function_exists('mb_language')) { + function mb_language(?string $language = null): string|bool { return p\Mbstring::mb_language($language); } +} +if (!function_exists('mb_list_encodings')) { + function mb_list_encodings(): array { return p\Mbstring::mb_list_encodings(); } +} +if (!function_exists('mb_encoding_aliases')) { + function mb_encoding_aliases(?string $encoding): array { return p\Mbstring::mb_encoding_aliases((string) $encoding); } +} +if (!function_exists('mb_check_encoding')) { + function mb_check_encoding(array|string|null $value = null, ?string $encoding = null): bool { return p\Mbstring::mb_check_encoding($value, $encoding); } +} +if (!function_exists('mb_detect_encoding')) { + function mb_detect_encoding(?string $string, array|string|null $encodings = null, ?bool $strict = false): string|false { return p\Mbstring::mb_detect_encoding((string) $string, $encodings, (bool) $strict); } +} +if (!function_exists('mb_detect_order')) { + function mb_detect_order(array|string|null $encoding = null): array|bool { return p\Mbstring::mb_detect_order($encoding); } +} +if (!function_exists('mb_parse_str')) { + function mb_parse_str(?string $string, &$result = []): bool { parse_str((string) $string, $result); return (bool) $result; } +} +if (!function_exists('mb_strlen')) { + function mb_strlen(?string $string, ?string $encoding = null): int { return p\Mbstring::mb_strlen((string) $string, $encoding); } +} +if (!function_exists('mb_strpos')) { + function mb_strpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strpos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_strtolower')) { + function mb_strtolower(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_strtolower((string) $string, $encoding); } +} +if (!function_exists('mb_strtoupper')) { + function mb_strtoupper(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_strtoupper((string) $string, $encoding); } +} +if (!function_exists('mb_substitute_character')) { + function mb_substitute_character(string|int|null $substitute_character = null): string|int|bool { return p\Mbstring::mb_substitute_character($substitute_character); } +} +if (!function_exists('mb_substr')) { + function mb_substr(?string $string, ?int $start, ?int $length = null, ?string $encoding = null): string { return p\Mbstring::mb_substr((string) $string, (int) $start, $length, $encoding); } +} +if (!function_exists('mb_stripos')) { + function mb_stripos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_stripos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_stristr')) { + function mb_stristr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_stristr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_strrchr')) { + function mb_strrchr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strrchr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_strrichr')) { + function mb_strrichr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strrichr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_strripos')) { + function mb_strripos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strripos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_strrpos')) { + function mb_strrpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strrpos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_strstr')) { + function mb_strstr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strstr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_get_info')) { + function mb_get_info(?string $type = 'all'): array|string|int|false { return p\Mbstring::mb_get_info((string) $type); } +} +if (!function_exists('mb_http_output')) { + function mb_http_output(?string $encoding = null): string|bool { return p\Mbstring::mb_http_output($encoding); } +} +if (!function_exists('mb_strwidth')) { + function mb_strwidth(?string $string, ?string $encoding = null): int { return p\Mbstring::mb_strwidth((string) $string, $encoding); } +} +if (!function_exists('mb_substr_count')) { + function mb_substr_count(?string $haystack, ?string $needle, ?string $encoding = null): int { return p\Mbstring::mb_substr_count((string) $haystack, (string) $needle, $encoding); } +} +if (!function_exists('mb_output_handler')) { + function mb_output_handler(?string $string, ?int $status): string { return p\Mbstring::mb_output_handler((string) $string, (int) $status); } +} +if (!function_exists('mb_http_input')) { + function mb_http_input(?string $type = null): array|string|false { return p\Mbstring::mb_http_input($type); } +} + +if (!function_exists('mb_convert_variables')) { + function mb_convert_variables(?string $to_encoding, array|string|null $from_encoding, mixed &$var, mixed &...$vars): string|false { return p\Mbstring::mb_convert_variables((string) $to_encoding, $from_encoding ?? '', $var, ...$vars); } +} + +if (!function_exists('mb_ord')) { + function mb_ord(?string $string, ?string $encoding = null): int|false { return p\Mbstring::mb_ord((string) $string, $encoding); } +} +if (!function_exists('mb_chr')) { + function mb_chr(?int $codepoint, ?string $encoding = null): string|false { return p\Mbstring::mb_chr((int) $codepoint, $encoding); } +} +if (!function_exists('mb_scrub')) { + function mb_scrub(?string $string, ?string $encoding = null): string { $encoding ??= mb_internal_encoding(); return mb_convert_encoding((string) $string, $encoding, $encoding); } +} +if (!function_exists('mb_str_split')) { + function mb_str_split(?string $string, ?int $length = 1, ?string $encoding = null): array { return p\Mbstring::mb_str_split((string) $string, (int) $length, $encoding); } +} + +if (!function_exists('mb_str_pad')) { + function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = STR_PAD_RIGHT, ?string $encoding = null): string { return p\Mbstring::mb_str_pad($string, $length, $pad_string, $pad_type, $encoding); } +} + +if (extension_loaded('mbstring')) { + return; +} + +if (!defined('MB_CASE_UPPER')) { + define('MB_CASE_UPPER', 0); +} +if (!defined('MB_CASE_LOWER')) { + define('MB_CASE_LOWER', 1); +} +if (!defined('MB_CASE_TITLE')) { + define('MB_CASE_TITLE', 2); +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/composer.json b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/composer.json new file mode 100644 index 00000000..943e5029 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-mbstring/composer.json @@ -0,0 +1,41 @@ +{ + "name": "symfony/polyfill-mbstring", + "type": "library", + "description": "Symfony polyfill for the Mbstring extension", + "keywords": ["polyfill", "shim", "compatibility", "portable", "mbstring"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-mbstring": "*" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Mbstring\\": "" }, + "files": [ "bootstrap.php" ] + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php80/LICENSE b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/LICENSE new file mode 100644 index 00000000..0ed3a246 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2020-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Php80.php b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Php80.php new file mode 100644 index 00000000..362dd1a9 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Php80.php @@ -0,0 +1,115 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php80; + +/** + * @author Ion Bazan + * @author Nico Oelgart + * @author Nicolas Grekas + * + * @internal + */ +final class Php80 +{ + public static function fdiv(float $dividend, float $divisor): float + { + return @($dividend / $divisor); + } + + public static function get_debug_type($value): string + { + switch (true) { + case null === $value: return 'null'; + case \is_bool($value): return 'bool'; + case \is_string($value): return 'string'; + case \is_array($value): return 'array'; + case \is_int($value): return 'int'; + case \is_float($value): return 'float'; + case \is_object($value): break; + case $value instanceof \__PHP_Incomplete_Class: return '__PHP_Incomplete_Class'; + default: + if (null === $type = @get_resource_type($value)) { + return 'unknown'; + } + + if ('Unknown' === $type) { + $type = 'closed'; + } + + return "resource ($type)"; + } + + $class = \get_class($value); + + if (false === strpos($class, '@')) { + return $class; + } + + return (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous'; + } + + public static function get_resource_id($res): int + { + if (!\is_resource($res) && null === @get_resource_type($res)) { + throw new \TypeError(sprintf('Argument 1 passed to get_resource_id() must be of the type resource, %s given', get_debug_type($res))); + } + + return (int) $res; + } + + public static function preg_last_error_msg(): string + { + switch (preg_last_error()) { + case \PREG_INTERNAL_ERROR: + return 'Internal error'; + case \PREG_BAD_UTF8_ERROR: + return 'Malformed UTF-8 characters, possibly incorrectly encoded'; + case \PREG_BAD_UTF8_OFFSET_ERROR: + return 'The offset did not correspond to the beginning of a valid UTF-8 code point'; + case \PREG_BACKTRACK_LIMIT_ERROR: + return 'Backtrack limit exhausted'; + case \PREG_RECURSION_LIMIT_ERROR: + return 'Recursion limit exhausted'; + case \PREG_JIT_STACKLIMIT_ERROR: + return 'JIT stack limit exhausted'; + case \PREG_NO_ERROR: + return 'No error'; + default: + return 'Unknown error'; + } + } + + public static function str_contains(string $haystack, string $needle): bool + { + return '' === $needle || false !== strpos($haystack, $needle); + } + + public static function str_starts_with(string $haystack, string $needle): bool + { + return 0 === strncmp($haystack, $needle, \strlen($needle)); + } + + public static function str_ends_with(string $haystack, string $needle): bool + { + if ('' === $needle || $needle === $haystack) { + return true; + } + + if ('' === $haystack) { + return false; + } + + $needleLength = \strlen($needle); + + return $needleLength <= \strlen($haystack) && 0 === substr_compare($haystack, $needle, -$needleLength); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php80/PhpToken.php b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/PhpToken.php new file mode 100644 index 00000000..fe6e6910 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/PhpToken.php @@ -0,0 +1,103 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php80; + +/** + * @author Fedonyuk Anton + * + * @internal + */ +class PhpToken implements \Stringable +{ + /** + * @var int + */ + public $id; + + /** + * @var string + */ + public $text; + + /** + * @var int + */ + public $line; + + /** + * @var int + */ + public $pos; + + public function __construct(int $id, string $text, int $line = -1, int $position = -1) + { + $this->id = $id; + $this->text = $text; + $this->line = $line; + $this->pos = $position; + } + + public function getTokenName(): ?string + { + if ('UNKNOWN' === $name = token_name($this->id)) { + $name = \strlen($this->text) > 1 || \ord($this->text) < 32 ? null : $this->text; + } + + return $name; + } + + /** + * @param int|string|array $kind + */ + public function is($kind): bool + { + foreach ((array) $kind as $value) { + if (\in_array($value, [$this->id, $this->text], true)) { + return true; + } + } + + return false; + } + + public function isIgnorable(): bool + { + return \in_array($this->id, [\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT, \T_OPEN_TAG], true); + } + + public function __toString(): string + { + return (string) $this->text; + } + + /** + * @return static[] + */ + public static function tokenize(string $code, int $flags = 0): array + { + $line = 1; + $position = 0; + $tokens = token_get_all($code, $flags); + foreach ($tokens as $index => $token) { + if (\is_string($token)) { + $id = \ord($token); + $text = $token; + } else { + [$id, $text, $line] = $token; + } + $tokens[$index] = new static($id, $text, $line, $position); + $position += \strlen($text); + } + + return $tokens; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php80/README.md b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/README.md new file mode 100644 index 00000000..3816c559 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/README.md @@ -0,0 +1,25 @@ +Symfony Polyfill / Php80 +======================== + +This component provides features added to PHP 8.0 core: + +- [`Stringable`](https://php.net/stringable) interface +- [`fdiv`](https://php.net/fdiv) +- [`ValueError`](https://php.net/valueerror) class +- [`UnhandledMatchError`](https://php.net/unhandledmatcherror) class +- `FILTER_VALIDATE_BOOL` constant +- [`get_debug_type`](https://php.net/get_debug_type) +- [`PhpToken`](https://php.net/phptoken) class +- [`preg_last_error_msg`](https://php.net/preg_last_error_msg) +- [`str_contains`](https://php.net/str_contains) +- [`str_starts_with`](https://php.net/str_starts_with) +- [`str_ends_with`](https://php.net/str_ends_with) +- [`get_resource_id`](https://php.net/get_resource_id) + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php new file mode 100644 index 00000000..2b955423 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#[Attribute(Attribute::TARGET_CLASS)] +final class Attribute +{ + public const TARGET_CLASS = 1; + public const TARGET_FUNCTION = 2; + public const TARGET_METHOD = 4; + public const TARGET_PROPERTY = 8; + public const TARGET_CLASS_CONSTANT = 16; + public const TARGET_PARAMETER = 32; + public const TARGET_ALL = 63; + public const IS_REPEATABLE = 64; + + /** @var int */ + public $flags; + + public function __construct(int $flags = self::TARGET_ALL) + { + $this->flags = $flags; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php new file mode 100644 index 00000000..bd1212f6 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000 && extension_loaded('tokenizer')) { + class PhpToken extends Symfony\Polyfill\Php80\PhpToken + { + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php new file mode 100644 index 00000000..7c62d750 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000) { + interface Stringable + { + /** + * @return string + */ + public function __toString(); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php new file mode 100644 index 00000000..01c6c6c8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000) { + class UnhandledMatchError extends Error + { + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php new file mode 100644 index 00000000..783dbc28 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000) { + class ValueError extends Error + { + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php80/bootstrap.php b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/bootstrap.php new file mode 100644 index 00000000..e5f7dbc1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/bootstrap.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Php80 as p; + +if (\PHP_VERSION_ID >= 80000) { + return; +} + +if (!defined('FILTER_VALIDATE_BOOL') && defined('FILTER_VALIDATE_BOOLEAN')) { + define('FILTER_VALIDATE_BOOL', \FILTER_VALIDATE_BOOLEAN); +} + +if (!function_exists('fdiv')) { + function fdiv(float $num1, float $num2): float { return p\Php80::fdiv($num1, $num2); } +} +if (!function_exists('preg_last_error_msg')) { + function preg_last_error_msg(): string { return p\Php80::preg_last_error_msg(); } +} +if (!function_exists('str_contains')) { + function str_contains(?string $haystack, ?string $needle): bool { return p\Php80::str_contains($haystack ?? '', $needle ?? ''); } +} +if (!function_exists('str_starts_with')) { + function str_starts_with(?string $haystack, ?string $needle): bool { return p\Php80::str_starts_with($haystack ?? '', $needle ?? ''); } +} +if (!function_exists('str_ends_with')) { + function str_ends_with(?string $haystack, ?string $needle): bool { return p\Php80::str_ends_with($haystack ?? '', $needle ?? ''); } +} +if (!function_exists('get_debug_type')) { + function get_debug_type($value): string { return p\Php80::get_debug_type($value); } +} +if (!function_exists('get_resource_id')) { + function get_resource_id($resource): int { return p\Php80::get_resource_id($resource); } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php80/composer.json b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/composer.json new file mode 100644 index 00000000..f1801f40 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php80/composer.json @@ -0,0 +1,40 @@ +{ + "name": "symfony/polyfill-php80", + "type": "library", + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "keywords": ["polyfill", "shim", "compatibility", "portable"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Php80\\": "" }, + "files": [ "bootstrap.php" ], + "classmap": [ "Resources/stubs" ] + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php81/LICENSE b/tools/php-cs-fixer/vendor/symfony/polyfill-php81/LICENSE new file mode 100644 index 00000000..99c6bdf3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php81/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2021-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php81/Php81.php b/tools/php-cs-fixer/vendor/symfony/polyfill-php81/Php81.php new file mode 100644 index 00000000..f0507b76 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php81/Php81.php @@ -0,0 +1,37 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php81; + +/** + * @author Nicolas Grekas + * + * @internal + */ +final class Php81 +{ + public static function array_is_list(array $array): bool + { + if ([] === $array || $array === array_values($array)) { + return true; + } + + $nextKey = -1; + + foreach ($array as $k => $v) { + if ($k !== ++$nextKey) { + return false; + } + } + + return true; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php81/README.md b/tools/php-cs-fixer/vendor/symfony/polyfill-php81/README.md new file mode 100644 index 00000000..c07ef782 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php81/README.md @@ -0,0 +1,18 @@ +Symfony Polyfill / Php81 +======================== + +This component provides features added to PHP 8.1 core: + +- [`array_is_list`](https://php.net/array_is_list) +- [`enum_exists`](https://php.net/enum-exists) +- [`MYSQLI_REFRESH_REPLICA`](https://php.net/mysqli.constants#constantmysqli-refresh-replica) constant +- [`ReturnTypeWillChange`](https://wiki.php.net/rfc/internal_method_return_types) +- [`CURLStringFile`](https://php.net/CURLStringFile) (but only if PHP >= 7.4 is used) + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php81/Resources/stubs/CURLStringFile.php b/tools/php-cs-fixer/vendor/symfony/polyfill-php81/Resources/stubs/CURLStringFile.php new file mode 100644 index 00000000..eb5952ee --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php81/Resources/stubs/CURLStringFile.php @@ -0,0 +1,51 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID >= 70400 && extension_loaded('curl')) { + /** + * @property string $data + */ + class CURLStringFile extends CURLFile + { + private $data; + + public function __construct(string $data, string $postname, string $mime = 'application/octet-stream') + { + $this->data = $data; + parent::__construct('data://application/octet-stream;base64,'.base64_encode($data), $mime, $postname); + } + + public function __set(string $name, $value): void + { + if ('data' !== $name) { + $this->$name = $value; + + return; + } + + if (is_object($value) ? !method_exists($value, '__toString') : !is_scalar($value)) { + throw new \TypeError('Cannot assign '.gettype($value).' to property CURLStringFile::$data of type string'); + } + + $this->name = 'data://application/octet-stream;base64,'.base64_encode($value); + } + + public function __isset(string $name): bool + { + return isset($this->$name); + } + + public function &__get(string $name) + { + return $this->$name; + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php81/Resources/stubs/ReturnTypeWillChange.php b/tools/php-cs-fixer/vendor/symfony/polyfill-php81/Resources/stubs/ReturnTypeWillChange.php new file mode 100644 index 00000000..cb7720a8 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php81/Resources/stubs/ReturnTypeWillChange.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80100) { + #[Attribute(Attribute::TARGET_METHOD)] + final class ReturnTypeWillChange + { + public function __construct() + { + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php81/bootstrap.php b/tools/php-cs-fixer/vendor/symfony/polyfill-php81/bootstrap.php new file mode 100644 index 00000000..9f872e02 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php81/bootstrap.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Php81 as p; + +if (\PHP_VERSION_ID >= 80100) { + return; +} + +if (defined('MYSQLI_REFRESH_SLAVE') && !defined('MYSQLI_REFRESH_REPLICA')) { + define('MYSQLI_REFRESH_REPLICA', 64); +} + +if (!function_exists('array_is_list')) { + function array_is_list(array $array): bool { return p\Php81::array_is_list($array); } +} + +if (!function_exists('enum_exists')) { + function enum_exists(string $enum, bool $autoload = true): bool { return $autoload && class_exists($enum) && false; } +} diff --git a/tools/php-cs-fixer/vendor/symfony/polyfill-php81/composer.json b/tools/php-cs-fixer/vendor/symfony/polyfill-php81/composer.json new file mode 100644 index 00000000..e02d673d --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/polyfill-php81/composer.json @@ -0,0 +1,36 @@ +{ + "name": "symfony/polyfill-php81", + "type": "library", + "description": "Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions", + "keywords": ["polyfill", "shim", "compatibility", "portable"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Php81\\": "" }, + "files": [ "bootstrap.php" ], + "classmap": [ "Resources/stubs" ] + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/CHANGELOG.md b/tools/php-cs-fixer/vendor/symfony/process/CHANGELOG.md new file mode 100644 index 00000000..e26819b5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/CHANGELOG.md @@ -0,0 +1,124 @@ +CHANGELOG +========= + +6.4 +--- + + * Add `PhpSubprocess` to handle PHP subprocesses that take over the + configuration from their parent + * Add `RunProcessMessage` and `RunProcessMessageHandler` + * Support using `Process::findExecutable()` independently of `open_basedir` + +5.2.0 +----- + + * added `Process::setOptions()` to set `Process` specific options + * added option `create_new_console` to allow a subprocess to continue + to run after the main script exited, both on Linux and on Windows + +5.1.0 +----- + + * added `Process::getStartTime()` to retrieve the start time of the process as float + +5.0.0 +----- + + * removed `Process::inheritEnvironmentVariables()` + * removed `PhpProcess::setPhpBinary()` + * `Process` must be instantiated with a command array, use `Process::fromShellCommandline()` when the command should be parsed by the shell + * removed `Process::setCommandLine()` + +4.4.0 +----- + + * deprecated `Process::inheritEnvironmentVariables()`: env variables are always inherited. + * added `Process::getLastOutputTime()` method + +4.2.0 +----- + + * added the `Process::fromShellCommandline()` to run commands in a shell wrapper + * deprecated passing a command as string when creating a `Process` instance + * deprecated the `Process::setCommandline()` and the `PhpProcess::setPhpBinary()` methods + * added the `Process::waitUntil()` method to wait for the process only for a + specific output, then continue the normal execution of your application + +4.1.0 +----- + + * added the `Process::isTtySupported()` method that allows to check for TTY support + * made `PhpExecutableFinder` look for the `PHP_BINARY` env var when searching the php binary + * added the `ProcessSignaledException` class to properly catch signaled process errors + +4.0.0 +----- + + * environment variables will always be inherited + * added a second `array $env = []` argument to the `start()`, `run()`, + `mustRun()`, and `restart()` methods of the `Process` class + * added a second `array $env = []` argument to the `start()` method of the + `PhpProcess` class + * the `ProcessUtils::escapeArgument()` method has been removed + * the `areEnvironmentVariablesInherited()`, `getOptions()`, and `setOptions()` + methods of the `Process` class have been removed + * support for passing `proc_open()` options has been removed + * removed the `ProcessBuilder` class, use the `Process` class instead + * removed the `getEnhanceWindowsCompatibility()` and `setEnhanceWindowsCompatibility()` methods of the `Process` class + * passing a not existing working directory to the constructor of the `Symfony\Component\Process\Process` class is not + supported anymore + +3.4.0 +----- + + * deprecated the ProcessBuilder class + * deprecated calling `Process::start()` without setting a valid working directory beforehand (via `setWorkingDirectory()` or constructor) + +3.3.0 +----- + + * added command line arrays in the `Process` class + * added `$env` argument to `Process::start()`, `run()`, `mustRun()` and `restart()` methods + * deprecated the `ProcessUtils::escapeArgument()` method + * deprecated not inheriting environment variables + * deprecated configuring `proc_open()` options + * deprecated configuring enhanced Windows compatibility + * deprecated configuring enhanced sigchild compatibility + +2.5.0 +----- + + * added support for PTY mode + * added the convenience method "mustRun" + * deprecation: Process::setStdin() is deprecated in favor of Process::setInput() + * deprecation: Process::getStdin() is deprecated in favor of Process::getInput() + * deprecation: Process::setInput() and ProcessBuilder::setInput() do not accept non-scalar types + +2.4.0 +----- + + * added the ability to define an idle timeout + +2.3.0 +----- + + * added ProcessUtils::escapeArgument() to fix the bug in escapeshellarg() function on Windows + * added Process::signal() + * added Process::getPid() + * added support for a TTY mode + +2.2.0 +----- + + * added ProcessBuilder::setArguments() to reset the arguments on a builder + * added a way to retrieve the standard and error output incrementally + * added Process:restart() + +2.1.0 +----- + + * added support for non-blocking processes (start(), wait(), isRunning(), stop()) + * enhanced Windows compatibility + * added Process::getExitCodeText() that returns a string representation for + the exit code returned by the process + * added ProcessBuilder diff --git a/tools/php-cs-fixer/vendor/symfony/process/Exception/ExceptionInterface.php b/tools/php-cs-fixer/vendor/symfony/process/Exception/ExceptionInterface.php new file mode 100644 index 00000000..bd4a6040 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Exception/ExceptionInterface.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Exception; + +/** + * Marker Interface for the Process Component. + * + * @author Johannes M. Schmitt + */ +interface ExceptionInterface extends \Throwable +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/Exception/InvalidArgumentException.php b/tools/php-cs-fixer/vendor/symfony/process/Exception/InvalidArgumentException.php new file mode 100644 index 00000000..926ee211 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Exception/InvalidArgumentException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Exception; + +/** + * InvalidArgumentException for the Process Component. + * + * @author Romain Neutron + */ +class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/Exception/LogicException.php b/tools/php-cs-fixer/vendor/symfony/process/Exception/LogicException.php new file mode 100644 index 00000000..be3d490d --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Exception/LogicException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Exception; + +/** + * LogicException for the Process Component. + * + * @author Romain Neutron + */ +class LogicException extends \LogicException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/Exception/ProcessFailedException.php b/tools/php-cs-fixer/vendor/symfony/process/Exception/ProcessFailedException.php new file mode 100644 index 00000000..499809ee --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Exception/ProcessFailedException.php @@ -0,0 +1,54 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Exception; + +use Symfony\Component\Process\Process; + +/** + * Exception for failed processes. + * + * @author Johannes M. Schmitt + */ +class ProcessFailedException extends RuntimeException +{ + private Process $process; + + public function __construct(Process $process) + { + if ($process->isSuccessful()) { + throw new InvalidArgumentException('Expected a failed process, but the given process was successful.'); + } + + $error = sprintf('The command "%s" failed.'."\n\nExit Code: %s(%s)\n\nWorking directory: %s", + $process->getCommandLine(), + $process->getExitCode(), + $process->getExitCodeText(), + $process->getWorkingDirectory() + ); + + if (!$process->isOutputDisabled()) { + $error .= sprintf("\n\nOutput:\n================\n%s\n\nError Output:\n================\n%s", + $process->getOutput(), + $process->getErrorOutput() + ); + } + + parent::__construct($error); + + $this->process = $process; + } + + public function getProcess(): Process + { + return $this->process; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/Exception/ProcessSignaledException.php b/tools/php-cs-fixer/vendor/symfony/process/Exception/ProcessSignaledException.php new file mode 100644 index 00000000..0fed8ac3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Exception/ProcessSignaledException.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Exception; + +use Symfony\Component\Process\Process; + +/** + * Exception that is thrown when a process has been signaled. + * + * @author Sullivan Senechal + */ +final class ProcessSignaledException extends RuntimeException +{ + private Process $process; + + public function __construct(Process $process) + { + $this->process = $process; + + parent::__construct(sprintf('The process has been signaled with signal "%s".', $process->getTermSignal())); + } + + public function getProcess(): Process + { + return $this->process; + } + + public function getSignal(): int + { + return $this->getProcess()->getTermSignal(); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/Exception/ProcessTimedOutException.php b/tools/php-cs-fixer/vendor/symfony/process/Exception/ProcessTimedOutException.php new file mode 100644 index 00000000..252e1112 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Exception/ProcessTimedOutException.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Exception; + +use Symfony\Component\Process\Process; + +/** + * Exception that is thrown when a process times out. + * + * @author Johannes M. Schmitt + */ +class ProcessTimedOutException extends RuntimeException +{ + public const TYPE_GENERAL = 1; + public const TYPE_IDLE = 2; + + private Process $process; + private int $timeoutType; + + public function __construct(Process $process, int $timeoutType) + { + $this->process = $process; + $this->timeoutType = $timeoutType; + + parent::__construct(sprintf( + 'The process "%s" exceeded the timeout of %s seconds.', + $process->getCommandLine(), + $this->getExceededTimeout() + )); + } + + public function getProcess(): Process + { + return $this->process; + } + + public function isGeneralTimeout(): bool + { + return self::TYPE_GENERAL === $this->timeoutType; + } + + public function isIdleTimeout(): bool + { + return self::TYPE_IDLE === $this->timeoutType; + } + + public function getExceededTimeout(): ?float + { + return match ($this->timeoutType) { + self::TYPE_GENERAL => $this->process->getTimeout(), + self::TYPE_IDLE => $this->process->getIdleTimeout(), + default => throw new \LogicException(sprintf('Unknown timeout type "%d".', $this->timeoutType)), + }; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/Exception/RunProcessFailedException.php b/tools/php-cs-fixer/vendor/symfony/process/Exception/RunProcessFailedException.php new file mode 100644 index 00000000..e7219d35 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Exception/RunProcessFailedException.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Exception; + +use Symfony\Component\Process\Messenger\RunProcessContext; + +/** + * @author Kevin Bond + */ +final class RunProcessFailedException extends RuntimeException +{ + public function __construct(ProcessFailedException $exception, public readonly RunProcessContext $context) + { + parent::__construct($exception->getMessage(), $exception->getCode()); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/Exception/RuntimeException.php b/tools/php-cs-fixer/vendor/symfony/process/Exception/RuntimeException.php new file mode 100644 index 00000000..adead253 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Exception/RuntimeException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Exception; + +/** + * RuntimeException for the Process Component. + * + * @author Johannes M. Schmitt + */ +class RuntimeException extends \RuntimeException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/ExecutableFinder.php b/tools/php-cs-fixer/vendor/symfony/process/ExecutableFinder.php new file mode 100644 index 00000000..f044ebc0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/ExecutableFinder.php @@ -0,0 +1,78 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process; + +/** + * Generic executable finder. + * + * @author Fabien Potencier + * @author Johannes M. Schmitt + */ +class ExecutableFinder +{ + private array $suffixes = ['.exe', '.bat', '.cmd', '.com']; + + /** + * Replaces default suffixes of executable. + */ + public function setSuffixes(array $suffixes): void + { + $this->suffixes = $suffixes; + } + + /** + * Adds new possible suffix to check for executable. + */ + public function addSuffix(string $suffix): void + { + $this->suffixes[] = $suffix; + } + + /** + * Finds an executable by name. + * + * @param string $name The executable name (without the extension) + * @param string|null $default The default to return if no executable is found + * @param array $extraDirs Additional dirs to check into + */ + public function find(string $name, string $default = null, array $extraDirs = []): ?string + { + $dirs = array_merge( + explode(\PATH_SEPARATOR, getenv('PATH') ?: getenv('Path')), + $extraDirs + ); + + $suffixes = ['']; + if ('\\' === \DIRECTORY_SEPARATOR) { + $pathExt = getenv('PATHEXT'); + $suffixes = array_merge($pathExt ? explode(\PATH_SEPARATOR, $pathExt) : $this->suffixes, $suffixes); + } + foreach ($suffixes as $suffix) { + foreach ($dirs as $dir) { + if (@is_file($file = $dir.\DIRECTORY_SEPARATOR.$name.$suffix) && ('\\' === \DIRECTORY_SEPARATOR || @is_executable($file))) { + return $file; + } + + if (!@is_dir($dir) && basename($dir) === $name.$suffix && @is_executable($dir)) { + return $dir; + } + } + } + + $command = '\\' === \DIRECTORY_SEPARATOR ? 'where' : 'command -v'; + if (\function_exists('exec') && ($executablePath = strtok(@exec($command.' '.escapeshellarg($name)), \PHP_EOL)) && is_executable($executablePath)) { + return $executablePath; + } + + return $default; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/InputStream.php b/tools/php-cs-fixer/vendor/symfony/process/InputStream.php new file mode 100644 index 00000000..d0517de2 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/InputStream.php @@ -0,0 +1,91 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process; + +use Symfony\Component\Process\Exception\RuntimeException; + +/** + * Provides a way to continuously write to the input of a Process until the InputStream is closed. + * + * @author Nicolas Grekas + * + * @implements \IteratorAggregate + */ +class InputStream implements \IteratorAggregate +{ + private ?\Closure $onEmpty = null; + private array $input = []; + private bool $open = true; + + /** + * Sets a callback that is called when the write buffer becomes empty. + */ + public function onEmpty(callable $onEmpty = null): void + { + $this->onEmpty = null !== $onEmpty ? $onEmpty(...) : null; + } + + /** + * Appends an input to the write buffer. + * + * @param resource|string|int|float|bool|\Traversable|null $input The input to append as scalar, + * stream resource or \Traversable + */ + public function write(mixed $input): void + { + if (null === $input) { + return; + } + if ($this->isClosed()) { + throw new RuntimeException(sprintf('"%s" is closed.', static::class)); + } + $this->input[] = ProcessUtils::validateInput(__METHOD__, $input); + } + + /** + * Closes the write buffer. + */ + public function close(): void + { + $this->open = false; + } + + /** + * Tells whether the write buffer is closed or not. + */ + public function isClosed(): bool + { + return !$this->open; + } + + public function getIterator(): \Traversable + { + $this->open = true; + + while ($this->open || $this->input) { + if (!$this->input) { + yield ''; + continue; + } + $current = array_shift($this->input); + + if ($current instanceof \Iterator) { + yield from $current; + } else { + yield $current; + } + if (!$this->input && $this->open && null !== $onEmpty = $this->onEmpty) { + $this->write($onEmpty($this)); + } + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/LICENSE b/tools/php-cs-fixer/vendor/symfony/process/LICENSE new file mode 100644 index 00000000..0138f8f0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/process/Messenger/RunProcessContext.php b/tools/php-cs-fixer/vendor/symfony/process/Messenger/RunProcessContext.php new file mode 100644 index 00000000..b5ade072 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Messenger/RunProcessContext.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Messenger; + +use Symfony\Component\Process\Process; + +/** + * @author Kevin Bond + */ +final class RunProcessContext +{ + public readonly ?int $exitCode; + public readonly ?string $output; + public readonly ?string $errorOutput; + + public function __construct( + public readonly RunProcessMessage $message, + Process $process, + ) { + $this->exitCode = $process->getExitCode(); + $this->output = $process->isOutputDisabled() ? null : $process->getOutput(); + $this->errorOutput = $process->isOutputDisabled() ? null : $process->getErrorOutput(); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/Messenger/RunProcessMessage.php b/tools/php-cs-fixer/vendor/symfony/process/Messenger/RunProcessMessage.php new file mode 100644 index 00000000..b2c33fe3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Messenger/RunProcessMessage.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Messenger; + +/** + * @author Kevin Bond + */ +class RunProcessMessage implements \Stringable +{ + public function __construct( + public readonly array $command, + public readonly ?string $cwd = null, + public readonly ?array $env = null, + public readonly mixed $input = null, + public readonly ?float $timeout = 60.0, + ) { + } + + public function __toString(): string + { + return implode(' ', $this->command); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/Messenger/RunProcessMessageHandler.php b/tools/php-cs-fixer/vendor/symfony/process/Messenger/RunProcessMessageHandler.php new file mode 100644 index 00000000..41c1934c --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Messenger/RunProcessMessageHandler.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Messenger; + +use Symfony\Component\Process\Exception\ProcessFailedException; +use Symfony\Component\Process\Exception\RunProcessFailedException; +use Symfony\Component\Process\Process; + +/** + * @author Kevin Bond + */ +final class RunProcessMessageHandler +{ + public function __invoke(RunProcessMessage $message): RunProcessContext + { + $process = new Process($message->command, $message->cwd, $message->env, $message->input, $message->timeout); + + try { + return new RunProcessContext($message, $process->mustRun()); + } catch (ProcessFailedException $e) { + throw new RunProcessFailedException($e, new RunProcessContext($message, $e->getProcess())); + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/PhpExecutableFinder.php b/tools/php-cs-fixer/vendor/symfony/process/PhpExecutableFinder.php new file mode 100644 index 00000000..ae053641 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/PhpExecutableFinder.php @@ -0,0 +1,99 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process; + +/** + * An executable finder specifically designed for the PHP executable. + * + * @author Fabien Potencier + * @author Johannes M. Schmitt + */ +class PhpExecutableFinder +{ + private ExecutableFinder $executableFinder; + + public function __construct() + { + $this->executableFinder = new ExecutableFinder(); + } + + /** + * Finds The PHP executable. + */ + public function find(bool $includeArgs = true): string|false + { + if ($php = getenv('PHP_BINARY')) { + if (!is_executable($php)) { + $command = '\\' === \DIRECTORY_SEPARATOR ? 'where' : 'command -v'; + if (\function_exists('exec') && $php = strtok(exec($command.' '.escapeshellarg($php)), \PHP_EOL)) { + if (!is_executable($php)) { + return false; + } + } else { + return false; + } + } + + if (@is_dir($php)) { + return false; + } + + return $php; + } + + $args = $this->findArguments(); + $args = $includeArgs && $args ? ' '.implode(' ', $args) : ''; + + // PHP_BINARY return the current sapi executable + if (\PHP_BINARY && \in_array(\PHP_SAPI, ['cli', 'cli-server', 'phpdbg'], true)) { + return \PHP_BINARY.$args; + } + + if ($php = getenv('PHP_PATH')) { + if (!@is_executable($php) || @is_dir($php)) { + return false; + } + + return $php; + } + + if ($php = getenv('PHP_PEAR_PHP_BIN')) { + if (@is_executable($php) && !@is_dir($php)) { + return $php; + } + } + + if (@is_executable($php = \PHP_BINDIR.('\\' === \DIRECTORY_SEPARATOR ? '\\php.exe' : '/php')) && !@is_dir($php)) { + return $php; + } + + $dirs = [\PHP_BINDIR]; + if ('\\' === \DIRECTORY_SEPARATOR) { + $dirs[] = 'C:\xampp\php\\'; + } + + return $this->executableFinder->find('php', false, $dirs); + } + + /** + * Finds the PHP executable arguments. + */ + public function findArguments(): array + { + $arguments = []; + if ('phpdbg' === \PHP_SAPI) { + $arguments[] = '-qrr'; + } + + return $arguments; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/PhpProcess.php b/tools/php-cs-fixer/vendor/symfony/process/PhpProcess.php new file mode 100644 index 00000000..0d31e26f --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/PhpProcess.php @@ -0,0 +1,66 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process; + +use Symfony\Component\Process\Exception\LogicException; +use Symfony\Component\Process\Exception\RuntimeException; + +/** + * PhpProcess runs a PHP script in an independent process. + * + * $p = new PhpProcess(''); + * $p->run(); + * print $p->getOutput()."\n"; + * + * @author Fabien Potencier + */ +class PhpProcess extends Process +{ + /** + * @param string $script The PHP script to run (as a string) + * @param string|null $cwd The working directory or null to use the working dir of the current PHP process + * @param array|null $env The environment variables or null to use the same environment as the current PHP process + * @param int $timeout The timeout in seconds + * @param array|null $php Path to the PHP binary to use with any additional arguments + */ + public function __construct(string $script, string $cwd = null, array $env = null, int $timeout = 60, array $php = null) + { + if (null === $php) { + $executableFinder = new PhpExecutableFinder(); + $php = $executableFinder->find(false); + $php = false === $php ? null : array_merge([$php], $executableFinder->findArguments()); + } + if ('phpdbg' === \PHP_SAPI) { + $file = tempnam(sys_get_temp_dir(), 'dbg'); + file_put_contents($file, $script); + register_shutdown_function('unlink', $file); + $php[] = $file; + $script = null; + } + + parent::__construct($php, $cwd, $env, $script, $timeout); + } + + public static function fromShellCommandline(string $command, string $cwd = null, array $env = null, mixed $input = null, ?float $timeout = 60): static + { + throw new LogicException(sprintf('The "%s()" method cannot be called when using "%s".', __METHOD__, self::class)); + } + + public function start(callable $callback = null, array $env = []): void + { + if (null === $this->getCommandLine()) { + throw new RuntimeException('Unable to find the PHP executable.'); + } + + parent::start($callback, $env); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/PhpSubprocess.php b/tools/php-cs-fixer/vendor/symfony/process/PhpSubprocess.php new file mode 100644 index 00000000..0720520f --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/PhpSubprocess.php @@ -0,0 +1,164 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process; + +use Symfony\Component\Process\Exception\LogicException; +use Symfony\Component\Process\Exception\RuntimeException; + +/** + * PhpSubprocess runs a PHP command as a subprocess while keeping the original php.ini settings. + * + * For this, it generates a temporary php.ini file taking over all the current settings and disables + * loading additional .ini files. Basically, your command gets prefixed using "php -n -c /tmp/temp.ini". + * + * Given your php.ini contains "memory_limit=-1" and you have a "MemoryTest.php" with the following content: + * + * run(); + * print $p->getOutput()."\n"; + * + * This will output "string(2) "-1", because the process is started with the default php.ini settings. + * + * $p = new PhpSubprocess(['MemoryTest.php'], null, null, 60, ['php', '-d', 'memory_limit=256M']); + * $p->run(); + * print $p->getOutput()."\n"; + * + * This will output "string(4) "256M"", because the process is started with the temporarily created php.ini settings. + * + * @author Yanick Witschi + * @author Partially copied and heavily inspired from composer/xdebug-handler by John Stevenson + */ +class PhpSubprocess extends Process +{ + /** + * @param array $command The command to run and its arguments listed as separate entries. They will automatically + * get prefixed with the PHP binary + * @param string|null $cwd The working directory or null to use the working dir of the current PHP process + * @param array|null $env The environment variables or null to use the same environment as the current PHP process + * @param int $timeout The timeout in seconds + * @param array|null $php Path to the PHP binary to use with any additional arguments + */ + public function __construct(array $command, string $cwd = null, array $env = null, int $timeout = 60, array $php = null) + { + if (null === $php) { + $executableFinder = new PhpExecutableFinder(); + $php = $executableFinder->find(false); + $php = false === $php ? null : array_merge([$php], $executableFinder->findArguments()); + } + + if (null === $php) { + throw new RuntimeException('Unable to find PHP binary.'); + } + + $tmpIni = $this->writeTmpIni($this->getAllIniFiles(), sys_get_temp_dir()); + + $php = array_merge($php, ['-n', '-c', $tmpIni]); + register_shutdown_function('unlink', $tmpIni); + + $command = array_merge($php, $command); + + parent::__construct($command, $cwd, $env, null, $timeout); + } + + public static function fromShellCommandline(string $command, string $cwd = null, array $env = null, mixed $input = null, ?float $timeout = 60): static + { + throw new LogicException(sprintf('The "%s()" method cannot be called when using "%s".', __METHOD__, self::class)); + } + + public function start(callable $callback = null, array $env = []): void + { + if (null === $this->getCommandLine()) { + throw new RuntimeException('Unable to find the PHP executable.'); + } + + parent::start($callback, $env); + } + + private function writeTmpIni(array $iniFiles, string $tmpDir): string + { + if (false === $tmpfile = @tempnam($tmpDir, '')) { + throw new RuntimeException('Unable to create temporary ini file.'); + } + + // $iniFiles has at least one item and it may be empty + if ('' === $iniFiles[0]) { + array_shift($iniFiles); + } + + $content = ''; + + foreach ($iniFiles as $file) { + // Check for inaccessible ini files + if (($data = @file_get_contents($file)) === false) { + throw new RuntimeException('Unable to read ini: '.$file); + } + // Check and remove directives after HOST and PATH sections + if (preg_match('/^\s*\[(?:PATH|HOST)\s*=/mi', $data, $matches)) { + $data = substr($data, 0, $matches[0][1]); + } + + $content .= $data."\n"; + } + + // Merge loaded settings into our ini content, if it is valid + $config = parse_ini_string($content); + $loaded = ini_get_all(null, false); + + if (false === $config || false === $loaded) { + throw new RuntimeException('Unable to parse ini data.'); + } + + $content .= $this->mergeLoadedConfig($loaded, $config); + + // Work-around for https://bugs.php.net/bug.php?id=75932 + $content .= "opcache.enable_cli=0\n"; + + if (false === @file_put_contents($tmpfile, $content)) { + throw new RuntimeException('Unable to write temporary ini file.'); + } + + return $tmpfile; + } + + private function mergeLoadedConfig(array $loadedConfig, array $iniConfig): string + { + $content = ''; + + foreach ($loadedConfig as $name => $value) { + if (!\is_string($value)) { + continue; + } + + if (!isset($iniConfig[$name]) || $iniConfig[$name] !== $value) { + // Double-quote escape each value + $content .= $name.'="'.addcslashes($value, '\\"')."\"\n"; + } + } + + return $content; + } + + private function getAllIniFiles(): array + { + $paths = [(string) php_ini_loaded_file()]; + + if (false !== $scanned = php_ini_scanned_files()) { + $paths = array_merge($paths, array_map('trim', explode(',', $scanned))); + } + + return $paths; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/Pipes/AbstractPipes.php b/tools/php-cs-fixer/vendor/symfony/process/Pipes/AbstractPipes.php new file mode 100644 index 00000000..cbbb7277 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Pipes/AbstractPipes.php @@ -0,0 +1,176 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Pipes; + +use Symfony\Component\Process\Exception\InvalidArgumentException; + +/** + * @author Romain Neutron + * + * @internal + */ +abstract class AbstractPipes implements PipesInterface +{ + public array $pipes = []; + + private string $inputBuffer = ''; + /** @var resource|string|\Iterator */ + private $input; + private bool $blocked = true; + private ?string $lastError = null; + + /** + * @param resource|string|\Iterator $input + */ + public function __construct($input) + { + if (\is_resource($input) || $input instanceof \Iterator) { + $this->input = $input; + } else { + $this->inputBuffer = (string) $input; + } + } + + public function close(): void + { + foreach ($this->pipes as $pipe) { + if (\is_resource($pipe)) { + fclose($pipe); + } + } + $this->pipes = []; + } + + /** + * Returns true if a system call has been interrupted. + */ + protected function hasSystemCallBeenInterrupted(): bool + { + $lastError = $this->lastError; + $this->lastError = null; + + // stream_select returns false when the `select` system call is interrupted by an incoming signal + return null !== $lastError && false !== stripos($lastError, 'interrupted system call'); + } + + /** + * Unblocks streams. + */ + protected function unblock(): void + { + if (!$this->blocked) { + return; + } + + foreach ($this->pipes as $pipe) { + stream_set_blocking($pipe, 0); + } + if (\is_resource($this->input)) { + stream_set_blocking($this->input, 0); + } + + $this->blocked = false; + } + + /** + * Writes input to stdin. + * + * @throws InvalidArgumentException When an input iterator yields a non supported value + */ + protected function write(): ?array + { + if (!isset($this->pipes[0])) { + return null; + } + $input = $this->input; + + if ($input instanceof \Iterator) { + if (!$input->valid()) { + $input = null; + } elseif (\is_resource($input = $input->current())) { + stream_set_blocking($input, 0); + } elseif (!isset($this->inputBuffer[0])) { + if (!\is_string($input)) { + if (!\is_scalar($input)) { + throw new InvalidArgumentException(sprintf('"%s" yielded a value of type "%s", but only scalars and stream resources are supported.', get_debug_type($this->input), get_debug_type($input))); + } + $input = (string) $input; + } + $this->inputBuffer = $input; + $this->input->next(); + $input = null; + } else { + $input = null; + } + } + + $r = $e = []; + $w = [$this->pipes[0]]; + + // let's have a look if something changed in streams + if (false === @stream_select($r, $w, $e, 0, 0)) { + return null; + } + + foreach ($w as $stdin) { + if (isset($this->inputBuffer[0])) { + $written = fwrite($stdin, $this->inputBuffer); + $this->inputBuffer = substr($this->inputBuffer, $written); + if (isset($this->inputBuffer[0])) { + return [$this->pipes[0]]; + } + } + + if ($input) { + while (true) { + $data = fread($input, self::CHUNK_SIZE); + if (!isset($data[0])) { + break; + } + $written = fwrite($stdin, $data); + $data = substr($data, $written); + if (isset($data[0])) { + $this->inputBuffer = $data; + + return [$this->pipes[0]]; + } + } + if (feof($input)) { + if ($this->input instanceof \Iterator) { + $this->input->next(); + } else { + $this->input = null; + } + } + } + } + + // no input to read on resource, buffer is empty + if (!isset($this->inputBuffer[0]) && !($this->input instanceof \Iterator ? $this->input->valid() : $this->input)) { + $this->input = null; + fclose($this->pipes[0]); + unset($this->pipes[0]); + } elseif (!$w) { + return [$this->pipes[0]]; + } + + return null; + } + + /** + * @internal + */ + public function handleError(int $type, string $msg): void + { + $this->lastError = $msg; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/Pipes/PipesInterface.php b/tools/php-cs-fixer/vendor/symfony/process/Pipes/PipesInterface.php new file mode 100644 index 00000000..967f8de7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Pipes/PipesInterface.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Pipes; + +/** + * PipesInterface manages descriptors and pipes for the use of proc_open. + * + * @author Romain Neutron + * + * @internal + */ +interface PipesInterface +{ + public const CHUNK_SIZE = 16384; + + /** + * Returns an array of descriptors for the use of proc_open. + */ + public function getDescriptors(): array; + + /** + * Returns an array of filenames indexed by their related stream in case these pipes use temporary files. + * + * @return string[] + */ + public function getFiles(): array; + + /** + * Reads data in file handles and pipes. + * + * @param bool $blocking Whether to use blocking calls or not + * @param bool $close Whether to close pipes if they've reached EOF + * + * @return string[] An array of read data indexed by their fd + */ + public function readAndWrite(bool $blocking, bool $close = false): array; + + /** + * Returns if the current state has open file handles or pipes. + */ + public function areOpen(): bool; + + /** + * Returns if pipes are able to read output. + */ + public function haveReadSupport(): bool; + + /** + * Closes file handles and pipes. + */ + public function close(): void; +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/Pipes/UnixPipes.php b/tools/php-cs-fixer/vendor/symfony/process/Pipes/UnixPipes.php new file mode 100644 index 00000000..7bd0db0e --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Pipes/UnixPipes.php @@ -0,0 +1,148 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Pipes; + +use Symfony\Component\Process\Process; + +/** + * UnixPipes implementation uses unix pipes as handles. + * + * @author Romain Neutron + * + * @internal + */ +class UnixPipes extends AbstractPipes +{ + private ?bool $ttyMode; + private bool $ptyMode; + private bool $haveReadSupport; + + public function __construct(?bool $ttyMode, bool $ptyMode, mixed $input, bool $haveReadSupport) + { + $this->ttyMode = $ttyMode; + $this->ptyMode = $ptyMode; + $this->haveReadSupport = $haveReadSupport; + + parent::__construct($input); + } + + public function __sleep(): array + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + public function __wakeup(): void + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + public function __destruct() + { + $this->close(); + } + + public function getDescriptors(): array + { + if (!$this->haveReadSupport) { + $nullstream = fopen('/dev/null', 'c'); + + return [ + ['pipe', 'r'], + $nullstream, + $nullstream, + ]; + } + + if ($this->ttyMode) { + return [ + ['file', '/dev/tty', 'r'], + ['file', '/dev/tty', 'w'], + ['file', '/dev/tty', 'w'], + ]; + } + + if ($this->ptyMode && Process::isPtySupported()) { + return [ + ['pty'], + ['pty'], + ['pty'], + ]; + } + + return [ + ['pipe', 'r'], + ['pipe', 'w'], // stdout + ['pipe', 'w'], // stderr + ]; + } + + public function getFiles(): array + { + return []; + } + + public function readAndWrite(bool $blocking, bool $close = false): array + { + $this->unblock(); + $w = $this->write(); + + $read = $e = []; + $r = $this->pipes; + unset($r[0]); + + // let's have a look if something changed in streams + set_error_handler($this->handleError(...)); + if (($r || $w) && false === stream_select($r, $w, $e, 0, $blocking ? Process::TIMEOUT_PRECISION * 1E6 : 0)) { + restore_error_handler(); + // if a system call has been interrupted, forget about it, let's try again + // otherwise, an error occurred, let's reset pipes + if (!$this->hasSystemCallBeenInterrupted()) { + $this->pipes = []; + } + + return $read; + } + restore_error_handler(); + + foreach ($r as $pipe) { + // prior PHP 5.4 the array passed to stream_select is modified and + // lose key association, we have to find back the key + $read[$type = array_search($pipe, $this->pipes, true)] = ''; + + do { + $data = @fread($pipe, self::CHUNK_SIZE); + $read[$type] .= $data; + } while (isset($data[0]) && ($close || isset($data[self::CHUNK_SIZE - 1]))); + + if (!isset($read[$type][0])) { + unset($read[$type]); + } + + if ($close && feof($pipe)) { + fclose($pipe); + unset($this->pipes[$type]); + } + } + + return $read; + } + + public function haveReadSupport(): bool + { + return $this->haveReadSupport; + } + + public function areOpen(): bool + { + return (bool) $this->pipes; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/Pipes/WindowsPipes.php b/tools/php-cs-fixer/vendor/symfony/process/Pipes/WindowsPipes.php new file mode 100644 index 00000000..637c8f38 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Pipes/WindowsPipes.php @@ -0,0 +1,186 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process\Pipes; + +use Symfony\Component\Process\Exception\RuntimeException; +use Symfony\Component\Process\Process; + +/** + * WindowsPipes implementation uses temporary files as handles. + * + * @see https://bugs.php.net/51800 + * @see https://bugs.php.net/65650 + * + * @author Romain Neutron + * + * @internal + */ +class WindowsPipes extends AbstractPipes +{ + private array $files = []; + private array $fileHandles = []; + private array $lockHandles = []; + private array $readBytes = [ + Process::STDOUT => 0, + Process::STDERR => 0, + ]; + private bool $haveReadSupport; + + public function __construct(mixed $input, bool $haveReadSupport) + { + $this->haveReadSupport = $haveReadSupport; + + if ($this->haveReadSupport) { + // Fix for PHP bug #51800: reading from STDOUT pipe hangs forever on Windows if the output is too big. + // Workaround for this problem is to use temporary files instead of pipes on Windows platform. + // + // @see https://bugs.php.net/51800 + $pipes = [ + Process::STDOUT => Process::OUT, + Process::STDERR => Process::ERR, + ]; + $tmpDir = sys_get_temp_dir(); + $lastError = 'unknown reason'; + set_error_handler(function ($type, $msg) use (&$lastError) { $lastError = $msg; }); + for ($i = 0;; ++$i) { + foreach ($pipes as $pipe => $name) { + $file = sprintf('%s\\sf_proc_%02X.%s', $tmpDir, $i, $name); + + if (!$h = fopen($file.'.lock', 'w')) { + if (file_exists($file.'.lock')) { + continue 2; + } + restore_error_handler(); + throw new RuntimeException('A temporary file could not be opened to write the process output: '.$lastError); + } + if (!flock($h, \LOCK_EX | \LOCK_NB)) { + continue 2; + } + if (isset($this->lockHandles[$pipe])) { + flock($this->lockHandles[$pipe], \LOCK_UN); + fclose($this->lockHandles[$pipe]); + } + $this->lockHandles[$pipe] = $h; + + if (!($h = fopen($file, 'w')) || !fclose($h) || !$h = fopen($file, 'r')) { + flock($this->lockHandles[$pipe], \LOCK_UN); + fclose($this->lockHandles[$pipe]); + unset($this->lockHandles[$pipe]); + continue 2; + } + $this->fileHandles[$pipe] = $h; + $this->files[$pipe] = $file; + } + break; + } + restore_error_handler(); + } + + parent::__construct($input); + } + + public function __sleep(): array + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + public function __wakeup(): void + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + public function __destruct() + { + $this->close(); + } + + public function getDescriptors(): array + { + if (!$this->haveReadSupport) { + $nullstream = fopen('NUL', 'c'); + + return [ + ['pipe', 'r'], + $nullstream, + $nullstream, + ]; + } + + // We're not using pipe on Windows platform as it hangs (https://bugs.php.net/51800) + // We're not using file handles as it can produce corrupted output https://bugs.php.net/65650 + // So we redirect output within the commandline and pass the nul device to the process + return [ + ['pipe', 'r'], + ['file', 'NUL', 'w'], + ['file', 'NUL', 'w'], + ]; + } + + public function getFiles(): array + { + return $this->files; + } + + public function readAndWrite(bool $blocking, bool $close = false): array + { + $this->unblock(); + $w = $this->write(); + $read = $r = $e = []; + + if ($blocking) { + if ($w) { + @stream_select($r, $w, $e, 0, Process::TIMEOUT_PRECISION * 1E6); + } elseif ($this->fileHandles) { + usleep(Process::TIMEOUT_PRECISION * 1E6); + } + } + foreach ($this->fileHandles as $type => $fileHandle) { + $data = stream_get_contents($fileHandle, -1, $this->readBytes[$type]); + + if (isset($data[0])) { + $this->readBytes[$type] += \strlen($data); + $read[$type] = $data; + } + if ($close) { + ftruncate($fileHandle, 0); + fclose($fileHandle); + flock($this->lockHandles[$type], \LOCK_UN); + fclose($this->lockHandles[$type]); + unset($this->fileHandles[$type], $this->lockHandles[$type]); + } + } + + return $read; + } + + public function haveReadSupport(): bool + { + return $this->haveReadSupport; + } + + public function areOpen(): bool + { + return $this->pipes && $this->fileHandles; + } + + public function close(): void + { + parent::close(); + foreach ($this->fileHandles as $type => $handle) { + ftruncate($handle, 0); + fclose($handle); + flock($this->lockHandles[$type], \LOCK_UN); + fclose($this->lockHandles[$type]); + } + $this->fileHandles = $this->lockHandles = []; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/Process.php b/tools/php-cs-fixer/vendor/symfony/process/Process.php new file mode 100644 index 00000000..6b73c31d --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/Process.php @@ -0,0 +1,1585 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process; + +use Symfony\Component\Process\Exception\InvalidArgumentException; +use Symfony\Component\Process\Exception\LogicException; +use Symfony\Component\Process\Exception\ProcessFailedException; +use Symfony\Component\Process\Exception\ProcessSignaledException; +use Symfony\Component\Process\Exception\ProcessTimedOutException; +use Symfony\Component\Process\Exception\RuntimeException; +use Symfony\Component\Process\Pipes\UnixPipes; +use Symfony\Component\Process\Pipes\WindowsPipes; + +/** + * Process is a thin wrapper around proc_* functions to easily + * start independent PHP processes. + * + * @author Fabien Potencier + * @author Romain Neutron + * + * @implements \IteratorAggregate + */ +class Process implements \IteratorAggregate +{ + public const ERR = 'err'; + public const OUT = 'out'; + + public const STATUS_READY = 'ready'; + public const STATUS_STARTED = 'started'; + public const STATUS_TERMINATED = 'terminated'; + + public const STDIN = 0; + public const STDOUT = 1; + public const STDERR = 2; + + // Timeout Precision in seconds. + public const TIMEOUT_PRECISION = 0.2; + + public const ITER_NON_BLOCKING = 1; // By default, iterating over outputs is a blocking call, use this flag to make it non-blocking + public const ITER_KEEP_OUTPUT = 2; // By default, outputs are cleared while iterating, use this flag to keep them in memory + public const ITER_SKIP_OUT = 4; // Use this flag to skip STDOUT while iterating + public const ITER_SKIP_ERR = 8; // Use this flag to skip STDERR while iterating + + private ?\Closure $callback = null; + private array|string $commandline; + private ?string $cwd; + private array $env = []; + /** @var resource|string|\Iterator|null */ + private $input; + private ?float $starttime = null; + private ?float $lastOutputTime = null; + private ?float $timeout = null; + private ?float $idleTimeout = null; + private ?int $exitcode = null; + private array $fallbackStatus = []; + private array $processInformation; + private bool $outputDisabled = false; + /** @var resource */ + private $stdout; + /** @var resource */ + private $stderr; + /** @var resource|null */ + private $process; + private string $status = self::STATUS_READY; + private int $incrementalOutputOffset = 0; + private int $incrementalErrorOutputOffset = 0; + private bool $tty = false; + private bool $pty; + private array $options = ['suppress_errors' => true, 'bypass_shell' => true]; + + private WindowsPipes|UnixPipes $processPipes; + + private ?int $latestSignal = null; + + private static ?bool $sigchild = null; + + /** + * Exit codes translation table. + * + * User-defined errors must use exit codes in the 64-113 range. + */ + public static array $exitCodes = [ + 0 => 'OK', + 1 => 'General error', + 2 => 'Misuse of shell builtins', + + 126 => 'Invoked command cannot execute', + 127 => 'Command not found', + 128 => 'Invalid exit argument', + + // signals + 129 => 'Hangup', + 130 => 'Interrupt', + 131 => 'Quit and dump core', + 132 => 'Illegal instruction', + 133 => 'Trace/breakpoint trap', + 134 => 'Process aborted', + 135 => 'Bus error: "access to undefined portion of memory object"', + 136 => 'Floating point exception: "erroneous arithmetic operation"', + 137 => 'Kill (terminate immediately)', + 138 => 'User-defined 1', + 139 => 'Segmentation violation', + 140 => 'User-defined 2', + 141 => 'Write to pipe with no one reading', + 142 => 'Signal raised by alarm', + 143 => 'Termination (request to terminate)', + // 144 - not defined + 145 => 'Child process terminated, stopped (or continued*)', + 146 => 'Continue if stopped', + 147 => 'Stop executing temporarily', + 148 => 'Terminal stop signal', + 149 => 'Background process attempting to read from tty ("in")', + 150 => 'Background process attempting to write to tty ("out")', + 151 => 'Urgent data available on socket', + 152 => 'CPU time limit exceeded', + 153 => 'File size limit exceeded', + 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"', + 155 => 'Profiling timer expired', + // 156 - not defined + 157 => 'Pollable event', + // 158 - not defined + 159 => 'Bad syscall', + ]; + + /** + * @param array $command The command to run and its arguments listed as separate entries + * @param string|null $cwd The working directory or null to use the working dir of the current PHP process + * @param array|null $env The environment variables or null to use the same environment as the current PHP process + * @param mixed $input The input as stream resource, scalar or \Traversable, or null for no input + * @param int|float|null $timeout The timeout in seconds or null to disable + * + * @throws LogicException When proc_open is not installed + */ + public function __construct(array $command, string $cwd = null, array $env = null, mixed $input = null, ?float $timeout = 60) + { + if (!\function_exists('proc_open')) { + throw new LogicException('The Process class relies on proc_open, which is not available on your PHP installation.'); + } + + $this->commandline = $command; + $this->cwd = $cwd; + + // on Windows, if the cwd changed via chdir(), proc_open defaults to the dir where PHP was started + // on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected + // @see : https://bugs.php.net/51800 + // @see : https://bugs.php.net/50524 + if (null === $this->cwd && (\defined('ZEND_THREAD_SAFE') || '\\' === \DIRECTORY_SEPARATOR)) { + $this->cwd = getcwd(); + } + if (null !== $env) { + $this->setEnv($env); + } + + $this->setInput($input); + $this->setTimeout($timeout); + $this->pty = false; + } + + /** + * Creates a Process instance as a command-line to be run in a shell wrapper. + * + * Command-lines are parsed by the shell of your OS (/bin/sh on Unix-like, cmd.exe on Windows.) + * This allows using e.g. pipes or conditional execution. In this mode, signals are sent to the + * shell wrapper and not to your commands. + * + * In order to inject dynamic values into command-lines, we strongly recommend using placeholders. + * This will save escaping values, which is not portable nor secure anyway: + * + * $process = Process::fromShellCommandline('my_command "${:MY_VAR}"'); + * $process->run(null, ['MY_VAR' => $theValue]); + * + * @param string $command The command line to pass to the shell of the OS + * @param string|null $cwd The working directory or null to use the working dir of the current PHP process + * @param array|null $env The environment variables or null to use the same environment as the current PHP process + * @param mixed $input The input as stream resource, scalar or \Traversable, or null for no input + * @param int|float|null $timeout The timeout in seconds or null to disable + * + * @throws LogicException When proc_open is not installed + */ + public static function fromShellCommandline(string $command, string $cwd = null, array $env = null, mixed $input = null, ?float $timeout = 60): static + { + $process = new static([], $cwd, $env, $input, $timeout); + $process->commandline = $command; + + return $process; + } + + public function __sleep(): array + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + public function __wakeup(): void + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + public function __destruct() + { + if ($this->options['create_new_console'] ?? false) { + $this->processPipes->close(); + } else { + $this->stop(0); + } + } + + public function __clone() + { + $this->resetProcessData(); + } + + /** + * Runs the process. + * + * The callback receives the type of output (out or err) and + * some bytes from the output in real-time. It allows to have feedback + * from the independent process during execution. + * + * The STDOUT and STDERR are also available after the process is finished + * via the getOutput() and getErrorOutput() methods. + * + * @param callable|null $callback A PHP callback to run whenever there is some + * output available on STDOUT or STDERR + * + * @return int The exit status code + * + * @throws RuntimeException When process can't be launched + * @throws RuntimeException When process is already running + * @throws ProcessTimedOutException When process timed out + * @throws ProcessSignaledException When process stopped after receiving signal + * @throws LogicException In case a callback is provided and output has been disabled + * + * @final + */ + public function run(callable $callback = null, array $env = []): int + { + $this->start($callback, $env); + + return $this->wait(); + } + + /** + * Runs the process. + * + * This is identical to run() except that an exception is thrown if the process + * exits with a non-zero exit code. + * + * @return $this + * + * @throws ProcessFailedException if the process didn't terminate successfully + * + * @final + */ + public function mustRun(callable $callback = null, array $env = []): static + { + if (0 !== $this->run($callback, $env)) { + throw new ProcessFailedException($this); + } + + return $this; + } + + /** + * Starts the process and returns after writing the input to STDIN. + * + * This method blocks until all STDIN data is sent to the process then it + * returns while the process runs in the background. + * + * The termination of the process can be awaited with wait(). + * + * The callback receives the type of output (out or err) and some bytes from + * the output in real-time while writing the standard input to the process. + * It allows to have feedback from the independent process during execution. + * + * @param callable|null $callback A PHP callback to run whenever there is some + * output available on STDOUT or STDERR + * + * @throws RuntimeException When process can't be launched + * @throws RuntimeException When process is already running + * @throws LogicException In case a callback is provided and output has been disabled + */ + public function start(callable $callback = null, array $env = []): void + { + if ($this->isRunning()) { + throw new RuntimeException('Process is already running.'); + } + + $this->resetProcessData(); + $this->starttime = $this->lastOutputTime = microtime(true); + $this->callback = $this->buildCallback($callback); + $descriptors = $this->getDescriptors(null !== $callback); + + if ($this->env) { + $env += '\\' === \DIRECTORY_SEPARATOR ? array_diff_ukey($this->env, $env, 'strcasecmp') : $this->env; + } + + $env += '\\' === \DIRECTORY_SEPARATOR ? array_diff_ukey($this->getDefaultEnv(), $env, 'strcasecmp') : $this->getDefaultEnv(); + + if (\is_array($commandline = $this->commandline)) { + $commandline = implode(' ', array_map($this->escapeArgument(...), $commandline)); + + if ('\\' !== \DIRECTORY_SEPARATOR) { + // exec is mandatory to deal with sending a signal to the process + $commandline = 'exec '.$commandline; + } + } else { + $commandline = $this->replacePlaceholders($commandline, $env); + } + + if ('\\' === \DIRECTORY_SEPARATOR) { + $commandline = $this->prepareWindowsCommandLine($commandline, $env); + } elseif ($this->isSigchildEnabled()) { + // last exit code is output on the fourth pipe and caught to work around --enable-sigchild + $descriptors[3] = ['pipe', 'w']; + + // See https://unix.stackexchange.com/questions/71205/background-process-pipe-input + $commandline = '{ ('.$commandline.') <&3 3<&- 3>/dev/null & } 3<&0;'; + $commandline .= 'pid=$!; echo $pid >&3; wait $pid 2>/dev/null; code=$?; echo $code >&3; exit $code'; + } + + $envPairs = []; + foreach ($env as $k => $v) { + if (false !== $v && false === \in_array($k, ['argc', 'argv', 'ARGC', 'ARGV'], true)) { + $envPairs[] = $k.'='.$v; + } + } + + if (!is_dir($this->cwd)) { + throw new RuntimeException(sprintf('The provided cwd "%s" does not exist.', $this->cwd)); + } + + $process = @proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $envPairs, $this->options); + + if (!\is_resource($process)) { + throw new RuntimeException('Unable to launch a new process.'); + } + $this->process = $process; + $this->status = self::STATUS_STARTED; + + if (isset($descriptors[3])) { + $this->fallbackStatus['pid'] = (int) fgets($this->processPipes->pipes[3]); + } + + if ($this->tty) { + return; + } + + $this->updateStatus(false); + $this->checkTimeout(); + } + + /** + * Restarts the process. + * + * Be warned that the process is cloned before being started. + * + * @param callable|null $callback A PHP callback to run whenever there is some + * output available on STDOUT or STDERR + * + * @throws RuntimeException When process can't be launched + * @throws RuntimeException When process is already running + * + * @see start() + * + * @final + */ + public function restart(callable $callback = null, array $env = []): static + { + if ($this->isRunning()) { + throw new RuntimeException('Process is already running.'); + } + + $process = clone $this; + $process->start($callback, $env); + + return $process; + } + + /** + * Waits for the process to terminate. + * + * The callback receives the type of output (out or err) and some bytes + * from the output in real-time while writing the standard input to the process. + * It allows to have feedback from the independent process during execution. + * + * @param callable|null $callback A valid PHP callback + * + * @return int The exitcode of the process + * + * @throws ProcessTimedOutException When process timed out + * @throws ProcessSignaledException When process stopped after receiving signal + * @throws LogicException When process is not yet started + */ + public function wait(callable $callback = null): int + { + $this->requireProcessIsStarted(__FUNCTION__); + + $this->updateStatus(false); + + if (null !== $callback) { + if (!$this->processPipes->haveReadSupport()) { + $this->stop(0); + throw new LogicException('Pass the callback to the "Process::start" method or call enableOutput to use a callback with "Process::wait".'); + } + $this->callback = $this->buildCallback($callback); + } + + do { + $this->checkTimeout(); + $running = $this->isRunning() && ('\\' === \DIRECTORY_SEPARATOR || $this->processPipes->areOpen()); + $this->readPipes($running, '\\' !== \DIRECTORY_SEPARATOR || !$running); + } while ($running); + + while ($this->isRunning()) { + $this->checkTimeout(); + usleep(1000); + } + + if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) { + throw new ProcessSignaledException($this); + } + + return $this->exitcode; + } + + /** + * Waits until the callback returns true. + * + * The callback receives the type of output (out or err) and some bytes + * from the output in real-time while writing the standard input to the process. + * It allows to have feedback from the independent process during execution. + * + * @throws RuntimeException When process timed out + * @throws LogicException When process is not yet started + * @throws ProcessTimedOutException In case the timeout was reached + */ + public function waitUntil(callable $callback): bool + { + $this->requireProcessIsStarted(__FUNCTION__); + $this->updateStatus(false); + + if (!$this->processPipes->haveReadSupport()) { + $this->stop(0); + throw new LogicException('Pass the callback to the "Process::start" method or call enableOutput to use a callback with "Process::waitUntil".'); + } + $callback = $this->buildCallback($callback); + + $ready = false; + while (true) { + $this->checkTimeout(); + $running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen(); + $output = $this->processPipes->readAndWrite($running, '\\' !== \DIRECTORY_SEPARATOR || !$running); + + foreach ($output as $type => $data) { + if (3 !== $type) { + $ready = $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data) || $ready; + } elseif (!isset($this->fallbackStatus['signaled'])) { + $this->fallbackStatus['exitcode'] = (int) $data; + } + } + if ($ready) { + return true; + } + if (!$running) { + return false; + } + + usleep(1000); + } + } + + /** + * Returns the Pid (process identifier), if applicable. + * + * @return int|null The process id if running, null otherwise + */ + public function getPid(): ?int + { + return $this->isRunning() ? $this->processInformation['pid'] : null; + } + + /** + * Sends a POSIX signal to the process. + * + * @param int $signal A valid POSIX signal (see https://php.net/pcntl.constants) + * + * @return $this + * + * @throws LogicException In case the process is not running + * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed + * @throws RuntimeException In case of failure + */ + public function signal(int $signal): static + { + $this->doSignal($signal, true); + + return $this; + } + + /** + * Disables fetching output and error output from the underlying process. + * + * @return $this + * + * @throws RuntimeException In case the process is already running + * @throws LogicException if an idle timeout is set + */ + public function disableOutput(): static + { + if ($this->isRunning()) { + throw new RuntimeException('Disabling output while the process is running is not possible.'); + } + if (null !== $this->idleTimeout) { + throw new LogicException('Output cannot be disabled while an idle timeout is set.'); + } + + $this->outputDisabled = true; + + return $this; + } + + /** + * Enables fetching output and error output from the underlying process. + * + * @return $this + * + * @throws RuntimeException In case the process is already running + */ + public function enableOutput(): static + { + if ($this->isRunning()) { + throw new RuntimeException('Enabling output while the process is running is not possible.'); + } + + $this->outputDisabled = false; + + return $this; + } + + /** + * Returns true in case the output is disabled, false otherwise. + */ + public function isOutputDisabled(): bool + { + return $this->outputDisabled; + } + + /** + * Returns the current output of the process (STDOUT). + * + * @throws LogicException in case the output has been disabled + * @throws LogicException In case the process is not started + */ + public function getOutput(): string + { + $this->readPipesForOutput(__FUNCTION__); + + if (false === $ret = stream_get_contents($this->stdout, -1, 0)) { + return ''; + } + + return $ret; + } + + /** + * Returns the output incrementally. + * + * In comparison with the getOutput method which always return the whole + * output, this one returns the new output since the last call. + * + * @throws LogicException in case the output has been disabled + * @throws LogicException In case the process is not started + */ + public function getIncrementalOutput(): string + { + $this->readPipesForOutput(__FUNCTION__); + + $latest = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset); + $this->incrementalOutputOffset = ftell($this->stdout); + + if (false === $latest) { + return ''; + } + + return $latest; + } + + /** + * Returns an iterator to the output of the process, with the output type as keys (Process::OUT/ERR). + * + * @param int $flags A bit field of Process::ITER_* flags + * + * @return \Generator + * + * @throws LogicException in case the output has been disabled + * @throws LogicException In case the process is not started + */ + public function getIterator(int $flags = 0): \Generator + { + $this->readPipesForOutput(__FUNCTION__, false); + + $clearOutput = !(self::ITER_KEEP_OUTPUT & $flags); + $blocking = !(self::ITER_NON_BLOCKING & $flags); + $yieldOut = !(self::ITER_SKIP_OUT & $flags); + $yieldErr = !(self::ITER_SKIP_ERR & $flags); + + while (null !== $this->callback || ($yieldOut && !feof($this->stdout)) || ($yieldErr && !feof($this->stderr))) { + if ($yieldOut) { + $out = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset); + + if (isset($out[0])) { + if ($clearOutput) { + $this->clearOutput(); + } else { + $this->incrementalOutputOffset = ftell($this->stdout); + } + + yield self::OUT => $out; + } + } + + if ($yieldErr) { + $err = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset); + + if (isset($err[0])) { + if ($clearOutput) { + $this->clearErrorOutput(); + } else { + $this->incrementalErrorOutputOffset = ftell($this->stderr); + } + + yield self::ERR => $err; + } + } + + if (!$blocking && !isset($out[0]) && !isset($err[0])) { + yield self::OUT => ''; + } + + $this->checkTimeout(); + $this->readPipesForOutput(__FUNCTION__, $blocking); + } + } + + /** + * Clears the process output. + * + * @return $this + */ + public function clearOutput(): static + { + ftruncate($this->stdout, 0); + fseek($this->stdout, 0); + $this->incrementalOutputOffset = 0; + + return $this; + } + + /** + * Returns the current error output of the process (STDERR). + * + * @throws LogicException in case the output has been disabled + * @throws LogicException In case the process is not started + */ + public function getErrorOutput(): string + { + $this->readPipesForOutput(__FUNCTION__); + + if (false === $ret = stream_get_contents($this->stderr, -1, 0)) { + return ''; + } + + return $ret; + } + + /** + * Returns the errorOutput incrementally. + * + * In comparison with the getErrorOutput method which always return the + * whole error output, this one returns the new error output since the last + * call. + * + * @throws LogicException in case the output has been disabled + * @throws LogicException In case the process is not started + */ + public function getIncrementalErrorOutput(): string + { + $this->readPipesForOutput(__FUNCTION__); + + $latest = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset); + $this->incrementalErrorOutputOffset = ftell($this->stderr); + + if (false === $latest) { + return ''; + } + + return $latest; + } + + /** + * Clears the process output. + * + * @return $this + */ + public function clearErrorOutput(): static + { + ftruncate($this->stderr, 0); + fseek($this->stderr, 0); + $this->incrementalErrorOutputOffset = 0; + + return $this; + } + + /** + * Returns the exit code returned by the process. + * + * @return int|null The exit status code, null if the Process is not terminated + */ + public function getExitCode(): ?int + { + $this->updateStatus(false); + + return $this->exitcode; + } + + /** + * Returns a string representation for the exit code returned by the process. + * + * This method relies on the Unix exit code status standardization + * and might not be relevant for other operating systems. + * + * @return string|null A string representation for the exit status code, null if the Process is not terminated + * + * @see http://tldp.org/LDP/abs/html/exitcodes.html + * @see http://en.wikipedia.org/wiki/Unix_signal + */ + public function getExitCodeText(): ?string + { + if (null === $exitcode = $this->getExitCode()) { + return null; + } + + return self::$exitCodes[$exitcode] ?? 'Unknown error'; + } + + /** + * Checks if the process ended successfully. + */ + public function isSuccessful(): bool + { + return 0 === $this->getExitCode(); + } + + /** + * Returns true if the child process has been terminated by an uncaught signal. + * + * It always returns false on Windows. + * + * @throws LogicException In case the process is not terminated + */ + public function hasBeenSignaled(): bool + { + $this->requireProcessIsTerminated(__FUNCTION__); + + return $this->processInformation['signaled']; + } + + /** + * Returns the number of the signal that caused the child process to terminate its execution. + * + * It is only meaningful if hasBeenSignaled() returns true. + * + * @throws RuntimeException In case --enable-sigchild is activated + * @throws LogicException In case the process is not terminated + */ + public function getTermSignal(): int + { + $this->requireProcessIsTerminated(__FUNCTION__); + + if ($this->isSigchildEnabled() && -1 === $this->processInformation['termsig']) { + throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal cannot be retrieved.'); + } + + return $this->processInformation['termsig']; + } + + /** + * Returns true if the child process has been stopped by a signal. + * + * It always returns false on Windows. + * + * @throws LogicException In case the process is not terminated + */ + public function hasBeenStopped(): bool + { + $this->requireProcessIsTerminated(__FUNCTION__); + + return $this->processInformation['stopped']; + } + + /** + * Returns the number of the signal that caused the child process to stop its execution. + * + * It is only meaningful if hasBeenStopped() returns true. + * + * @throws LogicException In case the process is not terminated + */ + public function getStopSignal(): int + { + $this->requireProcessIsTerminated(__FUNCTION__); + + return $this->processInformation['stopsig']; + } + + /** + * Checks if the process is currently running. + */ + public function isRunning(): bool + { + if (self::STATUS_STARTED !== $this->status) { + return false; + } + + $this->updateStatus(false); + + return $this->processInformation['running']; + } + + /** + * Checks if the process has been started with no regard to the current state. + */ + public function isStarted(): bool + { + return self::STATUS_READY != $this->status; + } + + /** + * Checks if the process is terminated. + */ + public function isTerminated(): bool + { + $this->updateStatus(false); + + return self::STATUS_TERMINATED == $this->status; + } + + /** + * Gets the process status. + * + * The status is one of: ready, started, terminated. + */ + public function getStatus(): string + { + $this->updateStatus(false); + + return $this->status; + } + + /** + * Stops the process. + * + * @param int|float $timeout The timeout in seconds + * @param int|null $signal A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL (9) + * + * @return int|null The exit-code of the process or null if it's not running + */ + public function stop(float $timeout = 10, int $signal = null): ?int + { + $timeoutMicro = microtime(true) + $timeout; + if ($this->isRunning()) { + // given SIGTERM may not be defined and that "proc_terminate" uses the constant value and not the constant itself, we use the same here + $this->doSignal(15, false); + do { + usleep(1000); + } while ($this->isRunning() && microtime(true) < $timeoutMicro); + + if ($this->isRunning()) { + // Avoid exception here: process is supposed to be running, but it might have stopped just + // after this line. In any case, let's silently discard the error, we cannot do anything. + $this->doSignal($signal ?: 9, false); + } + } + + if ($this->isRunning()) { + if (isset($this->fallbackStatus['pid'])) { + unset($this->fallbackStatus['pid']); + + return $this->stop(0, $signal); + } + $this->close(); + } + + return $this->exitcode; + } + + /** + * Adds a line to the STDOUT stream. + * + * @internal + */ + public function addOutput(string $line): void + { + $this->lastOutputTime = microtime(true); + + fseek($this->stdout, 0, \SEEK_END); + fwrite($this->stdout, $line); + fseek($this->stdout, $this->incrementalOutputOffset); + } + + /** + * Adds a line to the STDERR stream. + * + * @internal + */ + public function addErrorOutput(string $line): void + { + $this->lastOutputTime = microtime(true); + + fseek($this->stderr, 0, \SEEK_END); + fwrite($this->stderr, $line); + fseek($this->stderr, $this->incrementalErrorOutputOffset); + } + + /** + * Gets the last output time in seconds. + */ + public function getLastOutputTime(): ?float + { + return $this->lastOutputTime; + } + + /** + * Gets the command line to be executed. + */ + public function getCommandLine(): string + { + return \is_array($this->commandline) ? implode(' ', array_map($this->escapeArgument(...), $this->commandline)) : $this->commandline; + } + + /** + * Gets the process timeout in seconds (max. runtime). + */ + public function getTimeout(): ?float + { + return $this->timeout; + } + + /** + * Gets the process idle timeout in seconds (max. time since last output). + */ + public function getIdleTimeout(): ?float + { + return $this->idleTimeout; + } + + /** + * Sets the process timeout (max. runtime) in seconds. + * + * To disable the timeout, set this value to null. + * + * @return $this + * + * @throws InvalidArgumentException if the timeout is negative + */ + public function setTimeout(?float $timeout): static + { + $this->timeout = $this->validateTimeout($timeout); + + return $this; + } + + /** + * Sets the process idle timeout (max. time since last output) in seconds. + * + * To disable the timeout, set this value to null. + * + * @return $this + * + * @throws LogicException if the output is disabled + * @throws InvalidArgumentException if the timeout is negative + */ + public function setIdleTimeout(?float $timeout): static + { + if (null !== $timeout && $this->outputDisabled) { + throw new LogicException('Idle timeout cannot be set while the output is disabled.'); + } + + $this->idleTimeout = $this->validateTimeout($timeout); + + return $this; + } + + /** + * Enables or disables the TTY mode. + * + * @return $this + * + * @throws RuntimeException In case the TTY mode is not supported + */ + public function setTty(bool $tty): static + { + if ('\\' === \DIRECTORY_SEPARATOR && $tty) { + throw new RuntimeException('TTY mode is not supported on Windows platform.'); + } + + if ($tty && !self::isTtySupported()) { + throw new RuntimeException('TTY mode requires /dev/tty to be read/writable.'); + } + + $this->tty = $tty; + + return $this; + } + + /** + * Checks if the TTY mode is enabled. + */ + public function isTty(): bool + { + return $this->tty; + } + + /** + * Sets PTY mode. + * + * @return $this + */ + public function setPty(bool $bool): static + { + $this->pty = $bool; + + return $this; + } + + /** + * Returns PTY state. + */ + public function isPty(): bool + { + return $this->pty; + } + + /** + * Gets the working directory. + */ + public function getWorkingDirectory(): ?string + { + if (null === $this->cwd) { + // getcwd() will return false if any one of the parent directories does not have + // the readable or search mode set, even if the current directory does + return getcwd() ?: null; + } + + return $this->cwd; + } + + /** + * Sets the current working directory. + * + * @return $this + */ + public function setWorkingDirectory(string $cwd): static + { + $this->cwd = $cwd; + + return $this; + } + + /** + * Gets the environment variables. + */ + public function getEnv(): array + { + return $this->env; + } + + /** + * Sets the environment variables. + * + * @param array $env The new environment variables + * + * @return $this + */ + public function setEnv(array $env): static + { + $this->env = $env; + + return $this; + } + + /** + * Gets the Process input. + * + * @return resource|string|\Iterator|null + */ + public function getInput() + { + return $this->input; + } + + /** + * Sets the input. + * + * This content will be passed to the underlying process standard input. + * + * @param string|resource|\Traversable|self|null $input The content + * + * @return $this + * + * @throws LogicException In case the process is running + */ + public function setInput(mixed $input): static + { + if ($this->isRunning()) { + throw new LogicException('Input cannot be set while the process is running.'); + } + + $this->input = ProcessUtils::validateInput(__METHOD__, $input); + + return $this; + } + + /** + * Performs a check between the timeout definition and the time the process started. + * + * In case you run a background process (with the start method), you should + * trigger this method regularly to ensure the process timeout + * + * @throws ProcessTimedOutException In case the timeout was reached + */ + public function checkTimeout(): void + { + if (self::STATUS_STARTED !== $this->status) { + return; + } + + if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) { + $this->stop(0); + + throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL); + } + + if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) { + $this->stop(0); + + throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE); + } + } + + /** + * @throws LogicException in case process is not started + */ + public function getStartTime(): float + { + if (!$this->isStarted()) { + throw new LogicException('Start time is only available after process start.'); + } + + return $this->starttime; + } + + /** + * Defines options to pass to the underlying proc_open(). + * + * @see https://php.net/proc_open for the options supported by PHP. + * + * Enabling the "create_new_console" option allows a subprocess to continue + * to run after the main process exited, on both Windows and *nix + */ + public function setOptions(array $options): void + { + if ($this->isRunning()) { + throw new RuntimeException('Setting options while the process is running is not possible.'); + } + + $defaultOptions = $this->options; + $existingOptions = ['blocking_pipes', 'create_process_group', 'create_new_console']; + + foreach ($options as $key => $value) { + if (!\in_array($key, $existingOptions)) { + $this->options = $defaultOptions; + throw new LogicException(sprintf('Invalid option "%s" passed to "%s()". Supported options are "%s".', $key, __METHOD__, implode('", "', $existingOptions))); + } + $this->options[$key] = $value; + } + } + + /** + * Returns whether TTY is supported on the current operating system. + */ + public static function isTtySupported(): bool + { + static $isTtySupported; + + return $isTtySupported ??= ('/' === \DIRECTORY_SEPARATOR && stream_isatty(\STDOUT)); + } + + /** + * Returns whether PTY is supported on the current operating system. + */ + public static function isPtySupported(): bool + { + static $result; + + if (null !== $result) { + return $result; + } + + if ('\\' === \DIRECTORY_SEPARATOR) { + return $result = false; + } + + return $result = (bool) @proc_open('echo 1 >/dev/null', [['pty'], ['pty'], ['pty']], $pipes); + } + + /** + * Creates the descriptors needed by the proc_open. + */ + private function getDescriptors(bool $hasCallback): array + { + if ($this->input instanceof \Iterator) { + $this->input->rewind(); + } + if ('\\' === \DIRECTORY_SEPARATOR) { + $this->processPipes = new WindowsPipes($this->input, !$this->outputDisabled || $hasCallback); + } else { + $this->processPipes = new UnixPipes($this->isTty(), $this->isPty(), $this->input, !$this->outputDisabled || $hasCallback); + } + + return $this->processPipes->getDescriptors(); + } + + /** + * Builds up the callback used by wait(). + * + * The callbacks adds all occurred output to the specific buffer and calls + * the user callback (if present) with the received output. + * + * @param callable|null $callback The user defined PHP callback + */ + protected function buildCallback(callable $callback = null): \Closure + { + if ($this->outputDisabled) { + return fn ($type, $data): bool => null !== $callback && $callback($type, $data); + } + + $out = self::OUT; + + return function ($type, $data) use ($callback, $out): bool { + if ($out == $type) { + $this->addOutput($data); + } else { + $this->addErrorOutput($data); + } + + return null !== $callback && $callback($type, $data); + }; + } + + /** + * Updates the status of the process, reads pipes. + * + * @param bool $blocking Whether to use a blocking read call + */ + protected function updateStatus(bool $blocking): void + { + if (self::STATUS_STARTED !== $this->status) { + return; + } + + $this->processInformation = proc_get_status($this->process); + $running = $this->processInformation['running']; + + $this->readPipes($running && $blocking, '\\' !== \DIRECTORY_SEPARATOR || !$running); + + if ($this->fallbackStatus && $this->isSigchildEnabled()) { + $this->processInformation = $this->fallbackStatus + $this->processInformation; + } + + if (!$running) { + $this->close(); + } + } + + /** + * Returns whether PHP has been compiled with the '--enable-sigchild' option or not. + */ + protected function isSigchildEnabled(): bool + { + if (null !== self::$sigchild) { + return self::$sigchild; + } + + if (!\function_exists('phpinfo')) { + return self::$sigchild = false; + } + + ob_start(); + phpinfo(\INFO_GENERAL); + + return self::$sigchild = str_contains(ob_get_clean(), '--enable-sigchild'); + } + + /** + * Reads pipes for the freshest output. + * + * @param string $caller The name of the method that needs fresh outputs + * @param bool $blocking Whether to use blocking calls or not + * + * @throws LogicException in case output has been disabled or process is not started + */ + private function readPipesForOutput(string $caller, bool $blocking = false): void + { + if ($this->outputDisabled) { + throw new LogicException('Output has been disabled.'); + } + + $this->requireProcessIsStarted($caller); + + $this->updateStatus($blocking); + } + + /** + * Validates and returns the filtered timeout. + * + * @throws InvalidArgumentException if the given timeout is a negative number + */ + private function validateTimeout(?float $timeout): ?float + { + $timeout = (float) $timeout; + + if (0.0 === $timeout) { + $timeout = null; + } elseif ($timeout < 0) { + throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.'); + } + + return $timeout; + } + + /** + * Reads pipes, executes callback. + * + * @param bool $blocking Whether to use blocking calls or not + * @param bool $close Whether to close file handles or not + */ + private function readPipes(bool $blocking, bool $close): void + { + $result = $this->processPipes->readAndWrite($blocking, $close); + + $callback = $this->callback; + foreach ($result as $type => $data) { + if (3 !== $type) { + $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data); + } elseif (!isset($this->fallbackStatus['signaled'])) { + $this->fallbackStatus['exitcode'] = (int) $data; + } + } + } + + /** + * Closes process resource, closes file handles, sets the exitcode. + * + * @return int The exitcode + */ + private function close(): int + { + $this->processPipes->close(); + if (\is_resource($this->process)) { + proc_close($this->process); + } + $this->exitcode = $this->processInformation['exitcode']; + $this->status = self::STATUS_TERMINATED; + + if (-1 === $this->exitcode) { + if ($this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) { + // if process has been signaled, no exitcode but a valid termsig, apply Unix convention + $this->exitcode = 128 + $this->processInformation['termsig']; + } elseif ($this->isSigchildEnabled()) { + $this->processInformation['signaled'] = true; + $this->processInformation['termsig'] = -1; + } + } + + // Free memory from self-reference callback created by buildCallback + // Doing so in other contexts like __destruct or by garbage collector is ineffective + // Now pipes are closed, so the callback is no longer necessary + $this->callback = null; + + return $this->exitcode; + } + + /** + * Resets data related to the latest run of the process. + */ + private function resetProcessData(): void + { + $this->starttime = null; + $this->callback = null; + $this->exitcode = null; + $this->fallbackStatus = []; + $this->processInformation = []; + $this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+'); + $this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+'); + $this->process = null; + $this->latestSignal = null; + $this->status = self::STATUS_READY; + $this->incrementalOutputOffset = 0; + $this->incrementalErrorOutputOffset = 0; + } + + /** + * Sends a POSIX signal to the process. + * + * @param int $signal A valid POSIX signal (see https://php.net/pcntl.constants) + * @param bool $throwException Whether to throw exception in case signal failed + * + * @throws LogicException In case the process is not running + * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed + * @throws RuntimeException In case of failure + */ + private function doSignal(int $signal, bool $throwException): bool + { + if (null === $pid = $this->getPid()) { + if ($throwException) { + throw new LogicException('Cannot send signal on a non running process.'); + } + + return false; + } + + if ('\\' === \DIRECTORY_SEPARATOR) { + exec(sprintf('taskkill /F /T /PID %d 2>&1', $pid), $output, $exitCode); + if ($exitCode && $this->isRunning()) { + if ($throwException) { + throw new RuntimeException(sprintf('Unable to kill the process (%s).', implode(' ', $output))); + } + + return false; + } + } else { + if (!$this->isSigchildEnabled()) { + $ok = @proc_terminate($this->process, $signal); + } elseif (\function_exists('posix_kill')) { + $ok = @posix_kill($pid, $signal); + } elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), [2 => ['pipe', 'w']], $pipes)) { + $ok = false === fgets($pipes[2]); + } + if (!$ok) { + if ($throwException) { + throw new RuntimeException(sprintf('Error while sending signal "%s".', $signal)); + } + + return false; + } + } + + $this->latestSignal = $signal; + $this->fallbackStatus['signaled'] = true; + $this->fallbackStatus['exitcode'] = -1; + $this->fallbackStatus['termsig'] = $this->latestSignal; + + return true; + } + + private function prepareWindowsCommandLine(string $cmd, array &$env): string + { + $uid = uniqid('', true); + $cmd = preg_replace_callback( + '/"(?:( + [^"%!^]*+ + (?: + (?: !LF! | "(?:\^[%!^])?+" ) + [^"%!^]*+ + )++ + ) | [^"]*+ )"/x', + function ($m) use (&$env, $uid) { + static $varCount = 0; + static $varCache = []; + if (!isset($m[1])) { + return $m[0]; + } + if (isset($varCache[$m[0]])) { + return $varCache[$m[0]]; + } + if (str_contains($value = $m[1], "\0")) { + $value = str_replace("\0", '?', $value); + } + if (false === strpbrk($value, "\"%!\n")) { + return '"'.$value.'"'; + } + + $value = str_replace(['!LF!', '"^!"', '"^%"', '"^^"', '""'], ["\n", '!', '%', '^', '"'], $value); + $value = '"'.preg_replace('/(\\\\*)"/', '$1$1\\"', $value).'"'; + $var = $uid.++$varCount; + + $env[$var] = $value; + + return $varCache[$m[0]] = '!'.$var.'!'; + }, + $cmd + ); + + $cmd = 'cmd /V:ON /E:ON /D /C ('.str_replace("\n", ' ', $cmd).')'; + foreach ($this->processPipes->getFiles() as $offset => $filename) { + $cmd .= ' '.$offset.'>"'.$filename.'"'; + } + + return $cmd; + } + + /** + * Ensures the process is running or terminated, throws a LogicException if the process has a not started. + * + * @throws LogicException if the process has not run + */ + private function requireProcessIsStarted(string $functionName): void + { + if (!$this->isStarted()) { + throw new LogicException(sprintf('Process must be started before calling "%s()".', $functionName)); + } + } + + /** + * Ensures the process is terminated, throws a LogicException if the process has a status different than "terminated". + * + * @throws LogicException if the process is not yet terminated + */ + private function requireProcessIsTerminated(string $functionName): void + { + if (!$this->isTerminated()) { + throw new LogicException(sprintf('Process must be terminated before calling "%s()".', $functionName)); + } + } + + /** + * Escapes a string to be used as a shell argument. + */ + private function escapeArgument(?string $argument): string + { + if ('' === $argument || null === $argument) { + return '""'; + } + if ('\\' !== \DIRECTORY_SEPARATOR) { + return "'".str_replace("'", "'\\''", $argument)."'"; + } + if (str_contains($argument, "\0")) { + $argument = str_replace("\0", '?', $argument); + } + if (!preg_match('/[\/()%!^"<>&|\s]/', $argument)) { + return $argument; + } + $argument = preg_replace('/(\\\\+)$/', '$1$1', $argument); + + return '"'.str_replace(['"', '^', '%', '!', "\n"], ['""', '"^^"', '"^%"', '"^!"', '!LF!'], $argument).'"'; + } + + private function replacePlaceholders(string $commandline, array $env): string + { + return preg_replace_callback('/"\$\{:([_a-zA-Z]++[_a-zA-Z0-9]*+)\}"/', function ($matches) use ($commandline, $env) { + if (!isset($env[$matches[1]]) || false === $env[$matches[1]]) { + throw new InvalidArgumentException(sprintf('Command line is missing a value for parameter "%s": ', $matches[1]).$commandline); + } + + return $this->escapeArgument($env[$matches[1]]); + }, $commandline); + } + + private function getDefaultEnv(): array + { + $env = getenv(); + $env = ('\\' === \DIRECTORY_SEPARATOR ? array_intersect_ukey($env, $_SERVER, 'strcasecmp') : array_intersect_key($env, $_SERVER)) ?: $env; + + return $_ENV + ('\\' === \DIRECTORY_SEPARATOR ? array_diff_ukey($env, $_ENV, 'strcasecmp') : $env); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/ProcessUtils.php b/tools/php-cs-fixer/vendor/symfony/process/ProcessUtils.php new file mode 100644 index 00000000..092c5ccf --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/ProcessUtils.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Process; + +use Symfony\Component\Process\Exception\InvalidArgumentException; + +/** + * ProcessUtils is a bunch of utility methods. + * + * This class contains static methods only and is not meant to be instantiated. + * + * @author Martin Hasoň + */ +class ProcessUtils +{ + /** + * This class should not be instantiated. + */ + private function __construct() + { + } + + /** + * Validates and normalizes a Process input. + * + * @param string $caller The name of method call that validates the input + * @param mixed $input The input to validate + * + * @throws InvalidArgumentException In case the input is not valid + */ + public static function validateInput(string $caller, mixed $input): mixed + { + if (null !== $input) { + if (\is_resource($input)) { + return $input; + } + if (\is_scalar($input)) { + return (string) $input; + } + if ($input instanceof Process) { + return $input->getIterator($input::ITER_SKIP_ERR); + } + if ($input instanceof \Iterator) { + return $input; + } + if ($input instanceof \Traversable) { + return new \IteratorIterator($input); + } + + throw new InvalidArgumentException(sprintf('"%s" only accepts strings, Traversable objects or stream resources.', $caller)); + } + + return $input; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/process/README.md b/tools/php-cs-fixer/vendor/symfony/process/README.md new file mode 100644 index 00000000..afce5e45 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/README.md @@ -0,0 +1,13 @@ +Process Component +================= + +The Process component executes commands in sub-processes. + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/process.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/tools/php-cs-fixer/vendor/symfony/process/composer.json b/tools/php-cs-fixer/vendor/symfony/process/composer.json new file mode 100644 index 00000000..dda5575e --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/process/composer.json @@ -0,0 +1,28 @@ +{ + "name": "symfony/process", + "type": "library", + "description": "Executes commands in sub-processes", + "keywords": [], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.2" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\Process\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/tools/php-cs-fixer/vendor/symfony/service-contracts/Attribute/Required.php b/tools/php-cs-fixer/vendor/symfony/service-contracts/Attribute/Required.php new file mode 100644 index 00000000..9df85118 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/service-contracts/Attribute/Required.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service\Attribute; + +/** + * A required dependency. + * + * This attribute indicates that a property holds a required dependency. The annotated property or method should be + * considered during the instantiation process of the containing class. + * + * @author Alexander M. Turek + */ +#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::TARGET_PROPERTY)] +final class Required +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/service-contracts/Attribute/SubscribedService.php b/tools/php-cs-fixer/vendor/symfony/service-contracts/Attribute/SubscribedService.php new file mode 100644 index 00000000..d98e1dfd --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/service-contracts/Attribute/SubscribedService.php @@ -0,0 +1,47 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service\Attribute; + +use Symfony\Contracts\Service\ServiceSubscriberInterface; +use Symfony\Contracts\Service\ServiceSubscriberTrait; + +/** + * For use as the return value for {@see ServiceSubscriberInterface}. + * + * @example new SubscribedService('http_client', HttpClientInterface::class, false, new Target('githubApi')) + * + * Use with {@see ServiceSubscriberTrait} to mark a method's return type + * as a subscribed service. + * + * @author Kevin Bond + */ +#[\Attribute(\Attribute::TARGET_METHOD)] +final class SubscribedService +{ + /** @var object[] */ + public array $attributes; + + /** + * @param string|null $key The key to use for the service + * @param class-string|null $type The service class + * @param bool $nullable Whether the service is optional + * @param object|object[] $attributes One or more dependency injection attributes to use + */ + public function __construct( + public ?string $key = null, + public ?string $type = null, + public bool $nullable = false, + array|object $attributes = [], + ) { + $this->attributes = \is_array($attributes) ? $attributes : [$attributes]; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/service-contracts/CHANGELOG.md b/tools/php-cs-fixer/vendor/symfony/service-contracts/CHANGELOG.md new file mode 100644 index 00000000..7932e261 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/service-contracts/CHANGELOG.md @@ -0,0 +1,5 @@ +CHANGELOG +========= + +The changelog is maintained for all Symfony contracts at the following URL: +https://github.com/symfony/contracts/blob/main/CHANGELOG.md diff --git a/tools/php-cs-fixer/vendor/symfony/service-contracts/LICENSE b/tools/php-cs-fixer/vendor/symfony/service-contracts/LICENSE new file mode 100644 index 00000000..7536caea --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/service-contracts/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2018-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/service-contracts/README.md b/tools/php-cs-fixer/vendor/symfony/service-contracts/README.md new file mode 100644 index 00000000..42841a57 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/service-contracts/README.md @@ -0,0 +1,9 @@ +Symfony Service Contracts +========================= + +A set of abstractions extracted out of the Symfony components. + +Can be used to build on semantics that the Symfony components proved useful and +that already have battle tested implementations. + +See https://github.com/symfony/contracts/blob/main/README.md for more information. diff --git a/tools/php-cs-fixer/vendor/symfony/service-contracts/ResetInterface.php b/tools/php-cs-fixer/vendor/symfony/service-contracts/ResetInterface.php new file mode 100644 index 00000000..a4f389b0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/service-contracts/ResetInterface.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service; + +/** + * Provides a way to reset an object to its initial state. + * + * When calling the "reset()" method on an object, it should be put back to its + * initial state. This usually means clearing any internal buffers and forwarding + * the call to internal dependencies. All properties of the object should be put + * back to the same state it had when it was first ready to use. + * + * This method could be called, for example, to recycle objects that are used as + * services, so that they can be used to handle several requests in the same + * process loop (note that we advise making your services stateless instead of + * implementing this interface when possible.) + */ +interface ResetInterface +{ + /** + * @return void + */ + public function reset(); +} diff --git a/tools/php-cs-fixer/vendor/symfony/service-contracts/ServiceLocatorTrait.php b/tools/php-cs-fixer/vendor/symfony/service-contracts/ServiceLocatorTrait.php new file mode 100644 index 00000000..b62ec3e5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/service-contracts/ServiceLocatorTrait.php @@ -0,0 +1,115 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service; + +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; + +// Help opcache.preload discover always-needed symbols +class_exists(ContainerExceptionInterface::class); +class_exists(NotFoundExceptionInterface::class); + +/** + * A trait to help implement ServiceProviderInterface. + * + * @author Robin Chalas + * @author Nicolas Grekas + */ +trait ServiceLocatorTrait +{ + private array $factories; + private array $loading = []; + private array $providedTypes; + + /** + * @param array $factories + */ + public function __construct(array $factories) + { + $this->factories = $factories; + } + + public function has(string $id): bool + { + return isset($this->factories[$id]); + } + + public function get(string $id): mixed + { + if (!isset($this->factories[$id])) { + throw $this->createNotFoundException($id); + } + + if (isset($this->loading[$id])) { + $ids = array_values($this->loading); + $ids = \array_slice($this->loading, array_search($id, $ids)); + $ids[] = $id; + + throw $this->createCircularReferenceException($id, $ids); + } + + $this->loading[$id] = $id; + try { + return $this->factories[$id]($this); + } finally { + unset($this->loading[$id]); + } + } + + public function getProvidedServices(): array + { + if (!isset($this->providedTypes)) { + $this->providedTypes = []; + + foreach ($this->factories as $name => $factory) { + if (!\is_callable($factory)) { + $this->providedTypes[$name] = '?'; + } else { + $type = (new \ReflectionFunction($factory))->getReturnType(); + + $this->providedTypes[$name] = $type ? ($type->allowsNull() ? '?' : '').($type instanceof \ReflectionNamedType ? $type->getName() : $type) : '?'; + } + } + } + + return $this->providedTypes; + } + + private function createNotFoundException(string $id): NotFoundExceptionInterface + { + if (!$alternatives = array_keys($this->factories)) { + $message = 'is empty...'; + } else { + $last = array_pop($alternatives); + if ($alternatives) { + $message = sprintf('only knows about the "%s" and "%s" services.', implode('", "', $alternatives), $last); + } else { + $message = sprintf('only knows about the "%s" service.', $last); + } + } + + if ($this->loading) { + $message = sprintf('The service "%s" has a dependency on a non-existent service "%s". This locator %s', end($this->loading), $id, $message); + } else { + $message = sprintf('Service "%s" not found: the current service locator %s', $id, $message); + } + + return new class($message) extends \InvalidArgumentException implements NotFoundExceptionInterface { + }; + } + + private function createCircularReferenceException(string $id, array $path): ContainerExceptionInterface + { + return new class(sprintf('Circular reference detected for service "%s", path: "%s".', $id, implode(' -> ', $path))) extends \RuntimeException implements ContainerExceptionInterface { + }; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/service-contracts/ServiceProviderInterface.php b/tools/php-cs-fixer/vendor/symfony/service-contracts/ServiceProviderInterface.php new file mode 100644 index 00000000..2e71f00c --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/service-contracts/ServiceProviderInterface.php @@ -0,0 +1,45 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service; + +use Psr\Container\ContainerInterface; + +/** + * A ServiceProviderInterface exposes the identifiers and the types of services provided by a container. + * + * @author Nicolas Grekas + * @author Mateusz Sip + * + * @template-covariant T of mixed + */ +interface ServiceProviderInterface extends ContainerInterface +{ + /** + * @return T + */ + public function get(string $id): mixed; + + public function has(string $id): bool; + + /** + * Returns an associative array of service types keyed by the identifiers provided by the current container. + * + * Examples: + * + * * ['logger' => 'Psr\Log\LoggerInterface'] means the object provides a service named "logger" that implements Psr\Log\LoggerInterface + * * ['foo' => '?'] means the container provides service name "foo" of unspecified type + * * ['bar' => '?Bar\Baz'] means the container provides a service "bar" of type Bar\Baz|null + * + * @return array The provided service types, keyed by service names + */ + public function getProvidedServices(): array; +} diff --git a/tools/php-cs-fixer/vendor/symfony/service-contracts/ServiceSubscriberInterface.php b/tools/php-cs-fixer/vendor/symfony/service-contracts/ServiceSubscriberInterface.php new file mode 100644 index 00000000..3da19169 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/service-contracts/ServiceSubscriberInterface.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service; + +use Symfony\Contracts\Service\Attribute\SubscribedService; + +/** + * A ServiceSubscriber exposes its dependencies via the static {@link getSubscribedServices} method. + * + * The getSubscribedServices method returns an array of service types required by such instances, + * optionally keyed by the service names used internally. Service types that start with an interrogation + * mark "?" are optional, while the other ones are mandatory service dependencies. + * + * The injected service locators SHOULD NOT allow access to any other services not specified by the method. + * + * It is expected that ServiceSubscriber instances consume PSR-11-based service locators internally. + * This interface does not dictate any injection method for these service locators, although constructor + * injection is recommended. + * + * @author Nicolas Grekas + */ +interface ServiceSubscriberInterface +{ + /** + * Returns an array of service types (or {@see SubscribedService} objects) required + * by such instances, optionally keyed by the service names used internally. + * + * For mandatory dependencies: + * + * * ['logger' => 'Psr\Log\LoggerInterface'] means the objects use the "logger" name + * internally to fetch a service which must implement Psr\Log\LoggerInterface. + * * ['loggers' => 'Psr\Log\LoggerInterface[]'] means the objects use the "loggers" name + * internally to fetch an iterable of Psr\Log\LoggerInterface instances. + * * ['Psr\Log\LoggerInterface'] is a shortcut for + * * ['Psr\Log\LoggerInterface' => 'Psr\Log\LoggerInterface'] + * + * otherwise: + * + * * ['logger' => '?Psr\Log\LoggerInterface'] denotes an optional dependency + * * ['loggers' => '?Psr\Log\LoggerInterface[]'] denotes an optional iterable dependency + * * ['?Psr\Log\LoggerInterface'] is a shortcut for + * * ['Psr\Log\LoggerInterface' => '?Psr\Log\LoggerInterface'] + * + * additionally, an array of {@see SubscribedService}'s can be returned: + * + * * [new SubscribedService('logger', Psr\Log\LoggerInterface::class)] + * * [new SubscribedService(type: Psr\Log\LoggerInterface::class, nullable: true)] + * * [new SubscribedService('http_client', HttpClientInterface::class, attributes: new Target('githubApi'))] + * + * @return string[]|SubscribedService[] The required service types, optionally keyed by service names + */ + public static function getSubscribedServices(): array; +} diff --git a/tools/php-cs-fixer/vendor/symfony/service-contracts/ServiceSubscriberTrait.php b/tools/php-cs-fixer/vendor/symfony/service-contracts/ServiceSubscriberTrait.php new file mode 100644 index 00000000..f3b450cd --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/service-contracts/ServiceSubscriberTrait.php @@ -0,0 +1,78 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service; + +use Psr\Container\ContainerInterface; +use Symfony\Contracts\Service\Attribute\Required; +use Symfony\Contracts\Service\Attribute\SubscribedService; + +/** + * Implementation of ServiceSubscriberInterface that determines subscribed services from + * method return types. Service ids are available as "ClassName::methodName". + * + * @author Kevin Bond + */ +trait ServiceSubscriberTrait +{ + /** @var ContainerInterface */ + protected $container; + + public static function getSubscribedServices(): array + { + $services = method_exists(get_parent_class(self::class) ?: '', __FUNCTION__) ? parent::getSubscribedServices() : []; + + foreach ((new \ReflectionClass(self::class))->getMethods() as $method) { + if (self::class !== $method->getDeclaringClass()->name) { + continue; + } + + if (!$attribute = $method->getAttributes(SubscribedService::class)[0] ?? null) { + continue; + } + + if ($method->isStatic() || $method->isAbstract() || $method->isGenerator() || $method->isInternal() || $method->getNumberOfRequiredParameters()) { + throw new \LogicException(sprintf('Cannot use "%s" on method "%s::%s()" (can only be used on non-static, non-abstract methods with no parameters).', SubscribedService::class, self::class, $method->name)); + } + + if (!$returnType = $method->getReturnType()) { + throw new \LogicException(sprintf('Cannot use "%s" on methods without a return type in "%s::%s()".', SubscribedService::class, $method->name, self::class)); + } + + /* @var SubscribedService $attribute */ + $attribute = $attribute->newInstance(); + $attribute->key ??= self::class.'::'.$method->name; + $attribute->type ??= $returnType instanceof \ReflectionNamedType ? $returnType->getName() : (string) $returnType; + $attribute->nullable = $returnType->allowsNull(); + + if ($attribute->attributes) { + $services[] = $attribute; + } else { + $services[$attribute->key] = ($attribute->nullable ? '?' : '').$attribute->type; + } + } + + return $services; + } + + #[Required] + public function setContainer(ContainerInterface $container): ?ContainerInterface + { + $ret = null; + if (method_exists(get_parent_class(self::class) ?: '', __FUNCTION__)) { + $ret = parent::setContainer($container); + } + + $this->container = $container; + + return $ret; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/service-contracts/Test/ServiceLocatorTest.php b/tools/php-cs-fixer/vendor/symfony/service-contracts/Test/ServiceLocatorTest.php new file mode 100644 index 00000000..07d12b4a --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/service-contracts/Test/ServiceLocatorTest.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service\Test; + +class_alias(ServiceLocatorTestCase::class, ServiceLocatorTest::class); + +if (false) { + /** + * @deprecated since PHPUnit 9.6 + */ + class ServiceLocatorTest + { + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/service-contracts/Test/ServiceLocatorTestCase.php b/tools/php-cs-fixer/vendor/symfony/service-contracts/Test/ServiceLocatorTestCase.php new file mode 100644 index 00000000..583f72a7 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/service-contracts/Test/ServiceLocatorTestCase.php @@ -0,0 +1,92 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Contracts\Service\Test; + +use PHPUnit\Framework\TestCase; +use Psr\Container\ContainerInterface; +use Symfony\Contracts\Service\ServiceLocatorTrait; + +abstract class ServiceLocatorTestCase extends TestCase +{ + protected function getServiceLocator(array $factories): ContainerInterface + { + return new class($factories) implements ContainerInterface { + use ServiceLocatorTrait; + }; + } + + public function testHas() + { + $locator = $this->getServiceLocator([ + 'foo' => fn () => 'bar', + 'bar' => fn () => 'baz', + fn () => 'dummy', + ]); + + $this->assertTrue($locator->has('foo')); + $this->assertTrue($locator->has('bar')); + $this->assertFalse($locator->has('dummy')); + } + + public function testGet() + { + $locator = $this->getServiceLocator([ + 'foo' => fn () => 'bar', + 'bar' => fn () => 'baz', + ]); + + $this->assertSame('bar', $locator->get('foo')); + $this->assertSame('baz', $locator->get('bar')); + } + + public function testGetDoesNotMemoize() + { + $i = 0; + $locator = $this->getServiceLocator([ + 'foo' => function () use (&$i) { + ++$i; + + return 'bar'; + }, + ]); + + $this->assertSame('bar', $locator->get('foo')); + $this->assertSame('bar', $locator->get('foo')); + $this->assertSame(2, $i); + } + + public function testThrowsOnUndefinedInternalService() + { + if (!$this->getExpectedException()) { + $this->expectException(\Psr\Container\NotFoundExceptionInterface::class); + $this->expectExceptionMessage('The service "foo" has a dependency on a non-existent service "bar". This locator only knows about the "foo" service.'); + } + $locator = $this->getServiceLocator([ + 'foo' => function () use (&$locator) { return $locator->get('bar'); }, + ]); + + $locator->get('foo'); + } + + public function testThrowsOnCircularReference() + { + $this->expectException(\Psr\Container\ContainerExceptionInterface::class); + $this->expectExceptionMessage('Circular reference detected for service "bar", path: "bar -> baz -> bar".'); + $locator = $this->getServiceLocator([ + 'foo' => function () use (&$locator) { return $locator->get('bar'); }, + 'bar' => function () use (&$locator) { return $locator->get('baz'); }, + 'baz' => function () use (&$locator) { return $locator->get('bar'); }, + ]); + + $locator->get('foo'); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/service-contracts/composer.json b/tools/php-cs-fixer/vendor/symfony/service-contracts/composer.json new file mode 100644 index 00000000..a64188b5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/service-contracts/composer.json @@ -0,0 +1,41 @@ +{ + "name": "symfony/service-contracts", + "type": "library", + "description": "Generic abstractions related to writing services", + "keywords": ["abstractions", "contracts", "decoupling", "interfaces", "interoperability", "standards"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.1", + "psr/container": "^2.0" + }, + "conflict": { + "ext-psr": "<1.1|>=2" + }, + "autoload": { + "psr-4": { "Symfony\\Contracts\\Service\\": "" }, + "exclude-from-classmap": [ + "/Test/" + ] + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/stopwatch/CHANGELOG.md b/tools/php-cs-fixer/vendor/symfony/stopwatch/CHANGELOG.md new file mode 100644 index 00000000..f2fd7d0f --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/stopwatch/CHANGELOG.md @@ -0,0 +1,24 @@ +CHANGELOG +========= + +5.2 +--- + + * Add `name` argument to the `StopWatchEvent` constructor, accessible via a new `StopwatchEvent::getName()` + +5.0.0 +----- + + * Removed support for passing `null` as 1st (`$id`) argument of `Section::get()` method, pass a valid child section identifier instead. + +4.4.0 +----- + + * Deprecated passing `null` as 1st (`$id`) argument of `Section::get()` method, pass a valid child section identifier instead. + +3.4.0 +----- + + * added the `Stopwatch::reset()` method + * allowed to measure sub-millisecond times by introducing an argument to the + constructor of `Stopwatch` diff --git a/tools/php-cs-fixer/vendor/symfony/stopwatch/LICENSE b/tools/php-cs-fixer/vendor/symfony/stopwatch/LICENSE new file mode 100644 index 00000000..0138f8f0 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/stopwatch/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/stopwatch/README.md b/tools/php-cs-fixer/vendor/symfony/stopwatch/README.md new file mode 100644 index 00000000..13a9dfa5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/stopwatch/README.md @@ -0,0 +1,42 @@ +Stopwatch Component +=================== + +The Stopwatch component provides a way to profile code. + +Getting Started +--------------- + +``` +$ composer require symfony/stopwatch +``` + +```php +use Symfony\Component\Stopwatch\Stopwatch; + +$stopwatch = new Stopwatch(); + +// optionally group events into sections (e.g. phases of the execution) +$stopwatch->openSection(); + +// starts event named 'eventName' +$stopwatch->start('eventName'); + +// ... run your code here + +// optionally, start a new "lap" time +$stopwatch->lap('foo'); + +// ... run your code here + +$event = $stopwatch->stop('eventName'); + +$stopwatch->stopSection('phase_1'); +``` + +Resources +--------- + + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/tools/php-cs-fixer/vendor/symfony/stopwatch/Section.php b/tools/php-cs-fixer/vendor/symfony/stopwatch/Section.php new file mode 100644 index 00000000..28003673 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/stopwatch/Section.php @@ -0,0 +1,157 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Stopwatch; + +/** + * Stopwatch section. + * + * @author Fabien Potencier + */ +class Section +{ + /** + * @var StopwatchEvent[] + */ + private array $events = []; + + private ?float $origin; + private bool $morePrecision; + private ?string $id = null; + + /** + * @var Section[] + */ + private array $children = []; + + /** + * @param float|null $origin Set the origin of the events in this section, use null to set their origin to their start time + * @param bool $morePrecision If true, time is stored as float to keep the original microsecond precision + */ + public function __construct(float $origin = null, bool $morePrecision = false) + { + $this->origin = $origin; + $this->morePrecision = $morePrecision; + } + + /** + * Returns the child section. + */ + public function get(string $id): ?self + { + foreach ($this->children as $child) { + if ($id === $child->getId()) { + return $child; + } + } + + return null; + } + + /** + * Creates or re-opens a child section. + * + * @param string|null $id Null to create a new section, the identifier to re-open an existing one + */ + public function open(?string $id): self + { + if (null === $id || null === $session = $this->get($id)) { + $session = $this->children[] = new self(microtime(true) * 1000, $this->morePrecision); + } + + return $session; + } + + public function getId(): ?string + { + return $this->id; + } + + /** + * Sets the session identifier. + * + * @return $this + */ + public function setId(string $id): static + { + $this->id = $id; + + return $this; + } + + /** + * Starts an event. + */ + public function startEvent(string $name, ?string $category): StopwatchEvent + { + if (!isset($this->events[$name])) { + $this->events[$name] = new StopwatchEvent($this->origin ?: microtime(true) * 1000, $category, $this->morePrecision, $name); + } + + return $this->events[$name]->start(); + } + + /** + * Checks if the event was started. + */ + public function isEventStarted(string $name): bool + { + return isset($this->events[$name]) && $this->events[$name]->isStarted(); + } + + /** + * Stops an event. + * + * @throws \LogicException When the event has not been started + */ + public function stopEvent(string $name): StopwatchEvent + { + if (!isset($this->events[$name])) { + throw new \LogicException(sprintf('Event "%s" is not started.', $name)); + } + + return $this->events[$name]->stop(); + } + + /** + * Stops then restarts an event. + * + * @throws \LogicException When the event has not been started + */ + public function lap(string $name): StopwatchEvent + { + return $this->stopEvent($name)->start(); + } + + /** + * Returns a specific event by name. + * + * @throws \LogicException When the event is not known + */ + public function getEvent(string $name): StopwatchEvent + { + if (!isset($this->events[$name])) { + throw new \LogicException(sprintf('Event "%s" is not known.', $name)); + } + + return $this->events[$name]; + } + + /** + * Returns the events from this section. + * + * @return StopwatchEvent[] + */ + public function getEvents(): array + { + return $this->events; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/stopwatch/Stopwatch.php b/tools/php-cs-fixer/vendor/symfony/stopwatch/Stopwatch.php new file mode 100644 index 00000000..bf65ac3f --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/stopwatch/Stopwatch.php @@ -0,0 +1,153 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Stopwatch; + +use Symfony\Contracts\Service\ResetInterface; + +// Help opcache.preload discover always-needed symbols +class_exists(Section::class); + +/** + * Stopwatch provides a way to profile code. + * + * @author Fabien Potencier + */ +class Stopwatch implements ResetInterface +{ + private bool $morePrecision; + + /** + * @var Section[] + */ + private array $sections; + + /** + * @var Section[] + */ + private array $activeSections; + + /** + * @param bool $morePrecision If true, time is stored as float to keep the original microsecond precision + */ + public function __construct(bool $morePrecision = false) + { + $this->morePrecision = $morePrecision; + $this->reset(); + } + + /** + * @return Section[] + */ + public function getSections(): array + { + return $this->sections; + } + + /** + * Creates a new section or re-opens an existing section. + * + * @param string|null $id The id of the session to re-open, null to create a new one + * + * @throws \LogicException When the section to re-open is not reachable + */ + public function openSection(string $id = null): void + { + $current = end($this->activeSections); + + if (null !== $id && null === $current->get($id)) { + throw new \LogicException(sprintf('The section "%s" has been started at an other level and cannot be opened.', $id)); + } + + $this->start('__section__.child', 'section'); + $this->activeSections[] = $current->open($id); + $this->start('__section__'); + } + + /** + * Stops the last started section. + * + * The id parameter is used to retrieve the events from this section. + * + * @see getSectionEvents() + * + * @throws \LogicException When there's no started section to be stopped + */ + public function stopSection(string $id): void + { + $this->stop('__section__'); + + if (1 == \count($this->activeSections)) { + throw new \LogicException('There is no started section to stop.'); + } + + $this->sections[$id] = array_pop($this->activeSections)->setId($id); + $this->stop('__section__.child'); + } + + /** + * Starts an event. + */ + public function start(string $name, string $category = null): StopwatchEvent + { + return end($this->activeSections)->startEvent($name, $category); + } + + /** + * Checks if the event was started. + */ + public function isStarted(string $name): bool + { + return end($this->activeSections)->isEventStarted($name); + } + + /** + * Stops an event. + */ + public function stop(string $name): StopwatchEvent + { + return end($this->activeSections)->stopEvent($name); + } + + /** + * Stops then restarts an event. + */ + public function lap(string $name): StopwatchEvent + { + return end($this->activeSections)->stopEvent($name)->start(); + } + + /** + * Returns a specific event by name. + */ + public function getEvent(string $name): StopwatchEvent + { + return end($this->activeSections)->getEvent($name); + } + + /** + * Gets all events for a given section. + * + * @return StopwatchEvent[] + */ + public function getSectionEvents(string $id): array + { + return isset($this->sections[$id]) ? $this->sections[$id]->getEvents() : []; + } + + /** + * Resets the stopwatch to its original state. + */ + public function reset(): void + { + $this->sections = $this->activeSections = ['__root__' => new Section(null, $this->morePrecision)]; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/stopwatch/StopwatchEvent.php b/tools/php-cs-fixer/vendor/symfony/stopwatch/StopwatchEvent.php new file mode 100644 index 00000000..4492d2d1 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/stopwatch/StopwatchEvent.php @@ -0,0 +1,228 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Stopwatch; + +/** + * Represents an Event managed by Stopwatch. + * + * @author Fabien Potencier + */ +class StopwatchEvent +{ + /** + * @var StopwatchPeriod[] + */ + private array $periods = []; + + private float $origin; + private string $category; + private bool $morePrecision; + + /** + * @var float[] + */ + private array $started = []; + + private string $name; + + /** + * @param float $origin The origin time in milliseconds + * @param string|null $category The event category or null to use the default + * @param bool $morePrecision If true, time is stored as float to keep the original microsecond precision + * @param string|null $name The event name or null to define the name as default + * + * @throws \InvalidArgumentException When the raw time is not valid + */ + public function __construct(float $origin, string $category = null, bool $morePrecision = false, string $name = null) + { + $this->origin = $this->formatTime($origin); + $this->category = \is_string($category) ? $category : 'default'; + $this->morePrecision = $morePrecision; + $this->name = $name ?? 'default'; + } + + /** + * Gets the category. + */ + public function getCategory(): string + { + return $this->category; + } + + /** + * Gets the origin in milliseconds. + */ + public function getOrigin(): float + { + return $this->origin; + } + + /** + * Starts a new event period. + * + * @return $this + */ + public function start(): static + { + $this->started[] = $this->getNow(); + + return $this; + } + + /** + * Stops the last started event period. + * + * @return $this + * + * @throws \LogicException When stop() is called without a matching call to start() + */ + public function stop(): static + { + if (!\count($this->started)) { + throw new \LogicException('stop() called but start() has not been called before.'); + } + + $this->periods[] = new StopwatchPeriod(array_pop($this->started), $this->getNow(), $this->morePrecision); + + return $this; + } + + /** + * Checks if the event was started. + */ + public function isStarted(): bool + { + return !empty($this->started); + } + + /** + * Stops the current period and then starts a new one. + * + * @return $this + */ + public function lap(): static + { + return $this->stop()->start(); + } + + /** + * Stops all non already stopped periods. + */ + public function ensureStopped(): void + { + while (\count($this->started)) { + $this->stop(); + } + } + + /** + * Gets all event periods. + * + * @return StopwatchPeriod[] + */ + public function getPeriods(): array + { + return $this->periods; + } + + /** + * Gets the relative time of the start of the first period in milliseconds. + */ + public function getStartTime(): int|float + { + if (isset($this->periods[0])) { + return $this->periods[0]->getStartTime(); + } + + if ($this->started) { + return $this->started[0]; + } + + return 0; + } + + /** + * Gets the relative time of the end of the last period in milliseconds. + */ + public function getEndTime(): int|float + { + $count = \count($this->periods); + + return $count ? $this->periods[$count - 1]->getEndTime() : 0; + } + + /** + * Gets the duration of the events in milliseconds (including all periods). + */ + public function getDuration(): int|float + { + $periods = $this->periods; + $left = \count($this->started); + + for ($i = $left - 1; $i >= 0; --$i) { + $periods[] = new StopwatchPeriod($this->started[$i], $this->getNow(), $this->morePrecision); + } + + $total = 0; + foreach ($periods as $period) { + $total += $period->getDuration(); + } + + return $total; + } + + /** + * Gets the max memory usage of all periods in bytes. + */ + public function getMemory(): int + { + $memory = 0; + foreach ($this->periods as $period) { + if ($period->getMemory() > $memory) { + $memory = $period->getMemory(); + } + } + + return $memory; + } + + /** + * Return the current time relative to origin in milliseconds. + */ + protected function getNow(): float + { + return $this->formatTime(microtime(true) * 1000 - $this->origin); + } + + /** + * Formats a time. + * + * @throws \InvalidArgumentException When the raw time is not valid + */ + private function formatTime(float $time): float + { + return round($time, 1); + } + + /** + * Gets the event name. + */ + public function getName(): string + { + return $this->name; + } + + public function __toString(): string + { + return sprintf('%s/%s: %.2F MiB - %d ms', $this->getCategory(), $this->getName(), $this->getMemory() / 1024 / 1024, $this->getDuration()); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/stopwatch/StopwatchPeriod.php b/tools/php-cs-fixer/vendor/symfony/stopwatch/StopwatchPeriod.php new file mode 100644 index 00000000..41e8dccb --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/stopwatch/StopwatchPeriod.php @@ -0,0 +1,73 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Stopwatch; + +/** + * Represents an Period for an Event. + * + * @author Fabien Potencier + */ +class StopwatchPeriod +{ + private int|float $start; + private int|float $end; + private int $memory; + + /** + * @param int|float $start The relative time of the start of the period (in milliseconds) + * @param int|float $end The relative time of the end of the period (in milliseconds) + * @param bool $morePrecision If true, time is stored as float to keep the original microsecond precision + */ + public function __construct(int|float $start, int|float $end, bool $morePrecision = false) + { + $this->start = $morePrecision ? (float) $start : (int) $start; + $this->end = $morePrecision ? (float) $end : (int) $end; + $this->memory = memory_get_usage(true); + } + + /** + * Gets the relative time of the start of the period in milliseconds. + */ + public function getStartTime(): int|float + { + return $this->start; + } + + /** + * Gets the relative time of the end of the period in milliseconds. + */ + public function getEndTime(): int|float + { + return $this->end; + } + + /** + * Gets the time spent in this period in milliseconds. + */ + public function getDuration(): int|float + { + return $this->end - $this->start; + } + + /** + * Gets the memory usage in bytes. + */ + public function getMemory(): int + { + return $this->memory; + } + + public function __toString(): string + { + return sprintf('%.2F MiB - %d ms', $this->getMemory() / 1024 / 1024, $this->getDuration()); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/stopwatch/composer.json b/tools/php-cs-fixer/vendor/symfony/stopwatch/composer.json new file mode 100644 index 00000000..35568695 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/stopwatch/composer.json @@ -0,0 +1,29 @@ +{ + "name": "symfony/stopwatch", + "type": "library", + "description": "Provides a way to profile code", + "keywords": [], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.2", + "symfony/service-contracts": "^2.5|^3" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\Stopwatch\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/AbstractString.php b/tools/php-cs-fixer/vendor/symfony/string/AbstractString.php new file mode 100644 index 00000000..10231a21 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/AbstractString.php @@ -0,0 +1,702 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String; + +use Symfony\Component\String\Exception\ExceptionInterface; +use Symfony\Component\String\Exception\InvalidArgumentException; +use Symfony\Component\String\Exception\RuntimeException; + +/** + * Represents a string of abstract characters. + * + * Unicode defines 3 types of "characters" (bytes, code points and grapheme clusters). + * This class is the abstract type to use as a type-hint when the logic you want to + * implement doesn't care about the exact variant it deals with. + * + * @author Nicolas Grekas + * @author Hugo Hamon + * + * @throws ExceptionInterface + */ +abstract class AbstractString implements \Stringable, \JsonSerializable +{ + public const PREG_PATTERN_ORDER = \PREG_PATTERN_ORDER; + public const PREG_SET_ORDER = \PREG_SET_ORDER; + public const PREG_OFFSET_CAPTURE = \PREG_OFFSET_CAPTURE; + public const PREG_UNMATCHED_AS_NULL = \PREG_UNMATCHED_AS_NULL; + + public const PREG_SPLIT = 0; + public const PREG_SPLIT_NO_EMPTY = \PREG_SPLIT_NO_EMPTY; + public const PREG_SPLIT_DELIM_CAPTURE = \PREG_SPLIT_DELIM_CAPTURE; + public const PREG_SPLIT_OFFSET_CAPTURE = \PREG_SPLIT_OFFSET_CAPTURE; + + protected string $string = ''; + protected ?bool $ignoreCase = false; + + abstract public function __construct(string $string = ''); + + /** + * Unwraps instances of AbstractString back to strings. + * + * @return string[]|array + */ + public static function unwrap(array $values): array + { + foreach ($values as $k => $v) { + if ($v instanceof self) { + $values[$k] = $v->__toString(); + } elseif (\is_array($v) && $values[$k] !== $v = static::unwrap($v)) { + $values[$k] = $v; + } + } + + return $values; + } + + /** + * Wraps (and normalizes) strings in instances of AbstractString. + * + * @return static[]|array + */ + public static function wrap(array $values): array + { + $i = 0; + $keys = null; + + foreach ($values as $k => $v) { + if (\is_string($k) && '' !== $k && $k !== $j = (string) new static($k)) { + $keys ??= array_keys($values); + $keys[$i] = $j; + } + + if (\is_string($v)) { + $values[$k] = new static($v); + } elseif (\is_array($v) && $values[$k] !== $v = static::wrap($v)) { + $values[$k] = $v; + } + + ++$i; + } + + return null !== $keys ? array_combine($keys, $values) : $values; + } + + /** + * @param string|string[] $needle + */ + public function after(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static + { + $str = clone $this; + $i = \PHP_INT_MAX; + + if (\is_string($needle)) { + $needle = [$needle]; + } + + foreach ($needle as $n) { + $n = (string) $n; + $j = $this->indexOf($n, $offset); + + if (null !== $j && $j < $i) { + $i = $j; + $str->string = $n; + } + } + + if (\PHP_INT_MAX === $i) { + return $str; + } + + if (!$includeNeedle) { + $i += $str->length(); + } + + return $this->slice($i); + } + + /** + * @param string|string[] $needle + */ + public function afterLast(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static + { + $str = clone $this; + $i = null; + + if (\is_string($needle)) { + $needle = [$needle]; + } + + foreach ($needle as $n) { + $n = (string) $n; + $j = $this->indexOfLast($n, $offset); + + if (null !== $j && $j >= $i) { + $i = $offset = $j; + $str->string = $n; + } + } + + if (null === $i) { + return $str; + } + + if (!$includeNeedle) { + $i += $str->length(); + } + + return $this->slice($i); + } + + abstract public function append(string ...$suffix): static; + + /** + * @param string|string[] $needle + */ + public function before(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static + { + $str = clone $this; + $i = \PHP_INT_MAX; + + if (\is_string($needle)) { + $needle = [$needle]; + } + + foreach ($needle as $n) { + $n = (string) $n; + $j = $this->indexOf($n, $offset); + + if (null !== $j && $j < $i) { + $i = $j; + $str->string = $n; + } + } + + if (\PHP_INT_MAX === $i) { + return $str; + } + + if ($includeNeedle) { + $i += $str->length(); + } + + return $this->slice(0, $i); + } + + /** + * @param string|string[] $needle + */ + public function beforeLast(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static + { + $str = clone $this; + $i = null; + + if (\is_string($needle)) { + $needle = [$needle]; + } + + foreach ($needle as $n) { + $n = (string) $n; + $j = $this->indexOfLast($n, $offset); + + if (null !== $j && $j >= $i) { + $i = $offset = $j; + $str->string = $n; + } + } + + if (null === $i) { + return $str; + } + + if ($includeNeedle) { + $i += $str->length(); + } + + return $this->slice(0, $i); + } + + /** + * @return int[] + */ + public function bytesAt(int $offset): array + { + $str = $this->slice($offset, 1); + + return '' === $str->string ? [] : array_values(unpack('C*', $str->string)); + } + + abstract public function camel(): static; + + /** + * @return static[] + */ + abstract public function chunk(int $length = 1): array; + + public function collapseWhitespace(): static + { + $str = clone $this; + $str->string = trim(preg_replace("/(?:[ \n\r\t\x0C]{2,}+|[\n\r\t\x0C])/", ' ', $str->string), " \n\r\t\x0C"); + + return $str; + } + + /** + * @param string|string[] $needle + */ + public function containsAny(string|iterable $needle): bool + { + return null !== $this->indexOf($needle); + } + + /** + * @param string|string[] $suffix + */ + public function endsWith(string|iterable $suffix): bool + { + if (\is_string($suffix)) { + throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class)); + } + + foreach ($suffix as $s) { + if ($this->endsWith((string) $s)) { + return true; + } + } + + return false; + } + + public function ensureEnd(string $suffix): static + { + if (!$this->endsWith($suffix)) { + return $this->append($suffix); + } + + $suffix = preg_quote($suffix); + $regex = '{('.$suffix.')(?:'.$suffix.')++$}D'; + + return $this->replaceMatches($regex.($this->ignoreCase ? 'i' : ''), '$1'); + } + + public function ensureStart(string $prefix): static + { + $prefix = new static($prefix); + + if (!$this->startsWith($prefix)) { + return $this->prepend($prefix); + } + + $str = clone $this; + $i = $prefixLen = $prefix->length(); + + while ($this->indexOf($prefix, $i) === $i) { + $str = $str->slice($prefixLen); + $i += $prefixLen; + } + + return $str; + } + + /** + * @param string|string[] $string + */ + public function equalsTo(string|iterable $string): bool + { + if (\is_string($string)) { + throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class)); + } + + foreach ($string as $s) { + if ($this->equalsTo((string) $s)) { + return true; + } + } + + return false; + } + + abstract public function folded(): static; + + public function ignoreCase(): static + { + $str = clone $this; + $str->ignoreCase = true; + + return $str; + } + + /** + * @param string|string[] $needle + */ + public function indexOf(string|iterable $needle, int $offset = 0): ?int + { + if (\is_string($needle)) { + throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class)); + } + + $i = \PHP_INT_MAX; + + foreach ($needle as $n) { + $j = $this->indexOf((string) $n, $offset); + + if (null !== $j && $j < $i) { + $i = $j; + } + } + + return \PHP_INT_MAX === $i ? null : $i; + } + + /** + * @param string|string[] $needle + */ + public function indexOfLast(string|iterable $needle, int $offset = 0): ?int + { + if (\is_string($needle)) { + throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class)); + } + + $i = null; + + foreach ($needle as $n) { + $j = $this->indexOfLast((string) $n, $offset); + + if (null !== $j && $j >= $i) { + $i = $offset = $j; + } + } + + return $i; + } + + public function isEmpty(): bool + { + return '' === $this->string; + } + + abstract public function join(array $strings, string $lastGlue = null): static; + + public function jsonSerialize(): string + { + return $this->string; + } + + abstract public function length(): int; + + abstract public function lower(): static; + + /** + * Matches the string using a regular expression. + * + * Pass PREG_PATTERN_ORDER or PREG_SET_ORDER as $flags to get all occurrences matching the regular expression. + * + * @return array All matches in a multi-dimensional array ordered according to flags + */ + abstract public function match(string $regexp, int $flags = 0, int $offset = 0): array; + + abstract public function padBoth(int $length, string $padStr = ' '): static; + + abstract public function padEnd(int $length, string $padStr = ' '): static; + + abstract public function padStart(int $length, string $padStr = ' '): static; + + abstract public function prepend(string ...$prefix): static; + + public function repeat(int $multiplier): static + { + if (0 > $multiplier) { + throw new InvalidArgumentException(sprintf('Multiplier must be positive, %d given.', $multiplier)); + } + + $str = clone $this; + $str->string = str_repeat($str->string, $multiplier); + + return $str; + } + + abstract public function replace(string $from, string $to): static; + + abstract public function replaceMatches(string $fromRegexp, string|callable $to): static; + + abstract public function reverse(): static; + + abstract public function slice(int $start = 0, int $length = null): static; + + abstract public function snake(): static; + + abstract public function splice(string $replacement, int $start = 0, int $length = null): static; + + /** + * @return static[] + */ + public function split(string $delimiter, int $limit = null, int $flags = null): array + { + if (null === $flags) { + throw new \TypeError('Split behavior when $flags is null must be implemented by child classes.'); + } + + if ($this->ignoreCase) { + $delimiter .= 'i'; + } + + set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m)); + + try { + if (false === $chunks = preg_split($delimiter, $this->string, $limit, $flags)) { + throw new RuntimeException('Splitting failed with error: '.preg_last_error_msg()); + } + } finally { + restore_error_handler(); + } + + $str = clone $this; + + if (self::PREG_SPLIT_OFFSET_CAPTURE & $flags) { + foreach ($chunks as &$chunk) { + $str->string = $chunk[0]; + $chunk[0] = clone $str; + } + } else { + foreach ($chunks as &$chunk) { + $str->string = $chunk; + $chunk = clone $str; + } + } + + return $chunks; + } + + /** + * @param string|string[] $prefix + */ + public function startsWith(string|iterable $prefix): bool + { + if (\is_string($prefix)) { + throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class)); + } + + foreach ($prefix as $prefix) { + if ($this->startsWith((string) $prefix)) { + return true; + } + } + + return false; + } + + abstract public function title(bool $allWords = false): static; + + public function toByteString(string $toEncoding = null): ByteString + { + $b = new ByteString(); + + $toEncoding = \in_array($toEncoding, ['utf8', 'utf-8', 'UTF8'], true) ? 'UTF-8' : $toEncoding; + + if (null === $toEncoding || $toEncoding === $fromEncoding = $this instanceof AbstractUnicodeString || preg_match('//u', $b->string) ? 'UTF-8' : 'Windows-1252') { + $b->string = $this->string; + + return $b; + } + + try { + $b->string = mb_convert_encoding($this->string, $toEncoding, 'UTF-8'); + } catch (\ValueError $e) { + if (!\function_exists('iconv')) { + throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); + } + + $b->string = iconv('UTF-8', $toEncoding, $this->string); + } + + return $b; + } + + public function toCodePointString(): CodePointString + { + return new CodePointString($this->string); + } + + public function toString(): string + { + return $this->string; + } + + public function toUnicodeString(): UnicodeString + { + return new UnicodeString($this->string); + } + + abstract public function trim(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static; + + abstract public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static; + + /** + * @param string|string[] $prefix + */ + public function trimPrefix($prefix): static + { + if (\is_array($prefix) || $prefix instanceof \Traversable) { // don't use is_iterable(), it's slow + foreach ($prefix as $s) { + $t = $this->trimPrefix($s); + + if ($t->string !== $this->string) { + return $t; + } + } + + return clone $this; + } + + $str = clone $this; + + if ($prefix instanceof self) { + $prefix = $prefix->string; + } else { + $prefix = (string) $prefix; + } + + if ('' !== $prefix && \strlen($this->string) >= \strlen($prefix) && 0 === substr_compare($this->string, $prefix, 0, \strlen($prefix), $this->ignoreCase)) { + $str->string = substr($this->string, \strlen($prefix)); + } + + return $str; + } + + abstract public function trimStart(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static; + + /** + * @param string|string[] $suffix + */ + public function trimSuffix($suffix): static + { + if (\is_array($suffix) || $suffix instanceof \Traversable) { // don't use is_iterable(), it's slow + foreach ($suffix as $s) { + $t = $this->trimSuffix($s); + + if ($t->string !== $this->string) { + return $t; + } + } + + return clone $this; + } + + $str = clone $this; + + if ($suffix instanceof self) { + $suffix = $suffix->string; + } else { + $suffix = (string) $suffix; + } + + if ('' !== $suffix && \strlen($this->string) >= \strlen($suffix) && 0 === substr_compare($this->string, $suffix, -\strlen($suffix), null, $this->ignoreCase)) { + $str->string = substr($this->string, 0, -\strlen($suffix)); + } + + return $str; + } + + public function truncate(int $length, string $ellipsis = '', bool $cut = true): static + { + $stringLength = $this->length(); + + if ($stringLength <= $length) { + return clone $this; + } + + $ellipsisLength = '' !== $ellipsis ? (new static($ellipsis))->length() : 0; + + if ($length < $ellipsisLength) { + $ellipsisLength = 0; + } + + if (!$cut) { + if (null === $length = $this->indexOf([' ', "\r", "\n", "\t"], ($length ?: 1) - 1)) { + return clone $this; + } + + $length += $ellipsisLength; + } + + $str = $this->slice(0, $length - $ellipsisLength); + + return $ellipsisLength ? $str->trimEnd()->append($ellipsis) : $str; + } + + abstract public function upper(): static; + + /** + * Returns the printable length on a terminal. + */ + abstract public function width(bool $ignoreAnsiDecoration = true): int; + + public function wordwrap(int $width = 75, string $break = "\n", bool $cut = false): static + { + $lines = '' !== $break ? $this->split($break) : [clone $this]; + $chars = []; + $mask = ''; + + if (1 === \count($lines) && '' === $lines[0]->string) { + return $lines[0]; + } + + foreach ($lines as $i => $line) { + if ($i) { + $chars[] = $break; + $mask .= '#'; + } + + foreach ($line->chunk() as $char) { + $chars[] = $char->string; + $mask .= ' ' === $char->string ? ' ' : '?'; + } + } + + $string = ''; + $j = 0; + $b = $i = -1; + $mask = wordwrap($mask, $width, '#', $cut); + + while (false !== $b = strpos($mask, '#', $b + 1)) { + for (++$i; $i < $b; ++$i) { + $string .= $chars[$j]; + unset($chars[$j++]); + } + + if ($break === $chars[$j] || ' ' === $chars[$j]) { + unset($chars[$j++]); + } + + $string .= $break; + } + + $str = clone $this; + $str->string = $string.implode('', $chars); + + return $str; + } + + public function __sleep(): array + { + return ['string']; + } + + public function __clone() + { + $this->ignoreCase = false; + } + + public function __toString(): string + { + return $this->string; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/AbstractUnicodeString.php b/tools/php-cs-fixer/vendor/symfony/string/AbstractUnicodeString.php new file mode 100644 index 00000000..df7265f3 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/AbstractUnicodeString.php @@ -0,0 +1,590 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String; + +use Symfony\Component\String\Exception\ExceptionInterface; +use Symfony\Component\String\Exception\InvalidArgumentException; +use Symfony\Component\String\Exception\RuntimeException; + +/** + * Represents a string of abstract Unicode characters. + * + * Unicode defines 3 types of "characters" (bytes, code points and grapheme clusters). + * This class is the abstract type to use as a type-hint when the logic you want to + * implement is Unicode-aware but doesn't care about code points vs grapheme clusters. + * + * @author Nicolas Grekas + * + * @throws ExceptionInterface + */ +abstract class AbstractUnicodeString extends AbstractString +{ + public const NFC = \Normalizer::NFC; + public const NFD = \Normalizer::NFD; + public const NFKC = \Normalizer::NFKC; + public const NFKD = \Normalizer::NFKD; + + // all ASCII letters sorted by typical frequency of occurrence + private const ASCII = "\x20\x65\x69\x61\x73\x6E\x74\x72\x6F\x6C\x75\x64\x5D\x5B\x63\x6D\x70\x27\x0A\x67\x7C\x68\x76\x2E\x66\x62\x2C\x3A\x3D\x2D\x71\x31\x30\x43\x32\x2A\x79\x78\x29\x28\x4C\x39\x41\x53\x2F\x50\x22\x45\x6A\x4D\x49\x6B\x33\x3E\x35\x54\x3C\x44\x34\x7D\x42\x7B\x38\x46\x77\x52\x36\x37\x55\x47\x4E\x3B\x4A\x7A\x56\x23\x48\x4F\x57\x5F\x26\x21\x4B\x3F\x58\x51\x25\x59\x5C\x09\x5A\x2B\x7E\x5E\x24\x40\x60\x7F\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"; + + // the subset of folded case mappings that is not in lower case mappings + private const FOLD_FROM = ['İ', 'µ', 'ſ', "\xCD\x85", 'ς', 'ϐ', 'ϑ', 'ϕ', 'ϖ', 'ϰ', 'ϱ', 'ϵ', 'ẛ', "\xE1\xBE\xBE", 'ß', 'ʼn', 'ǰ', 'ΐ', 'ΰ', 'և', 'ẖ', 'ẗ', 'ẘ', 'ẙ', 'ẚ', 'ẞ', 'ὐ', 'ὒ', 'ὔ', 'ὖ', 'ᾀ', 'ᾁ', 'ᾂ', 'ᾃ', 'ᾄ', 'ᾅ', 'ᾆ', 'ᾇ', 'ᾈ', 'ᾉ', 'ᾊ', 'ᾋ', 'ᾌ', 'ᾍ', 'ᾎ', 'ᾏ', 'ᾐ', 'ᾑ', 'ᾒ', 'ᾓ', 'ᾔ', 'ᾕ', 'ᾖ', 'ᾗ', 'ᾘ', 'ᾙ', 'ᾚ', 'ᾛ', 'ᾜ', 'ᾝ', 'ᾞ', 'ᾟ', 'ᾠ', 'ᾡ', 'ᾢ', 'ᾣ', 'ᾤ', 'ᾥ', 'ᾦ', 'ᾧ', 'ᾨ', 'ᾩ', 'ᾪ', 'ᾫ', 'ᾬ', 'ᾭ', 'ᾮ', 'ᾯ', 'ᾲ', 'ᾳ', 'ᾴ', 'ᾶ', 'ᾷ', 'ᾼ', 'ῂ', 'ῃ', 'ῄ', 'ῆ', 'ῇ', 'ῌ', 'ῒ', 'ῖ', 'ῗ', 'ῢ', 'ῤ', 'ῦ', 'ῧ', 'ῲ', 'ῳ', 'ῴ', 'ῶ', 'ῷ', 'ῼ', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'ſt', 'st', 'ﬓ', 'ﬔ', 'ﬕ', 'ﬖ', 'ﬗ']; + private const FOLD_TO = ['i̇', 'μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', 'ṡ', 'ι', 'ss', 'ʼn', 'ǰ', 'ΐ', 'ΰ', 'եւ', 'ẖ', 'ẗ', 'ẘ', 'ẙ', 'aʾ', 'ss', 'ὐ', 'ὒ', 'ὔ', 'ὖ', 'ἀι', 'ἁι', 'ἂι', 'ἃι', 'ἄι', 'ἅι', 'ἆι', 'ἇι', 'ἀι', 'ἁι', 'ἂι', 'ἃι', 'ἄι', 'ἅι', 'ἆι', 'ἇι', 'ἠι', 'ἡι', 'ἢι', 'ἣι', 'ἤι', 'ἥι', 'ἦι', 'ἧι', 'ἠι', 'ἡι', 'ἢι', 'ἣι', 'ἤι', 'ἥι', 'ἦι', 'ἧι', 'ὠι', 'ὡι', 'ὢι', 'ὣι', 'ὤι', 'ὥι', 'ὦι', 'ὧι', 'ὠι', 'ὡι', 'ὢι', 'ὣι', 'ὤι', 'ὥι', 'ὦι', 'ὧι', 'ὰι', 'αι', 'άι', 'ᾶ', 'ᾶι', 'αι', 'ὴι', 'ηι', 'ήι', 'ῆ', 'ῆι', 'ηι', 'ῒ', 'ῖ', 'ῗ', 'ῢ', 'ῤ', 'ῦ', 'ῧ', 'ὼι', 'ωι', 'ώι', 'ῶ', 'ῶι', 'ωι', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'st', 'st', 'մն', 'մե', 'մի', 'վն', 'մխ']; + + // the subset of https://github.com/unicode-org/cldr/blob/master/common/transforms/Latin-ASCII.xml that is not in NFKD + private const TRANSLIT_FROM = ['Æ', 'Ð', 'Ø', 'Þ', 'ß', 'æ', 'ð', 'ø', 'þ', 'Đ', 'đ', 'Ħ', 'ħ', 'ı', 'ĸ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'ʼn', 'Ŋ', 'ŋ', 'Œ', 'œ', 'Ŧ', 'ŧ', 'ƀ', 'Ɓ', 'Ƃ', 'ƃ', 'Ƈ', 'ƈ', 'Ɖ', 'Ɗ', 'Ƌ', 'ƌ', 'Ɛ', 'Ƒ', 'ƒ', 'Ɠ', 'ƕ', 'Ɩ', 'Ɨ', 'Ƙ', 'ƙ', 'ƚ', 'Ɲ', 'ƞ', 'Ƣ', 'ƣ', 'Ƥ', 'ƥ', 'ƫ', 'Ƭ', 'ƭ', 'Ʈ', 'Ʋ', 'Ƴ', 'ƴ', 'Ƶ', 'ƶ', 'DŽ', 'Dž', 'dž', 'Ǥ', 'ǥ', 'ȡ', 'Ȥ', 'ȥ', 'ȴ', 'ȵ', 'ȶ', 'ȷ', 'ȸ', 'ȹ', 'Ⱥ', 'Ȼ', 'ȼ', 'Ƚ', 'Ⱦ', 'ȿ', 'ɀ', 'Ƀ', 'Ʉ', 'Ɇ', 'ɇ', 'Ɉ', 'ɉ', 'Ɍ', 'ɍ', 'Ɏ', 'ɏ', 'ɓ', 'ɕ', 'ɖ', 'ɗ', 'ɛ', 'ɟ', 'ɠ', 'ɡ', 'ɢ', 'ɦ', 'ɧ', 'ɨ', 'ɪ', 'ɫ', 'ɬ', 'ɭ', 'ɱ', 'ɲ', 'ɳ', 'ɴ', 'ɶ', 'ɼ', 'ɽ', 'ɾ', 'ʀ', 'ʂ', 'ʈ', 'ʉ', 'ʋ', 'ʏ', 'ʐ', 'ʑ', 'ʙ', 'ʛ', 'ʜ', 'ʝ', 'ʟ', 'ʠ', 'ʣ', 'ʥ', 'ʦ', 'ʪ', 'ʫ', 'ᴀ', 'ᴁ', 'ᴃ', 'ᴄ', 'ᴅ', 'ᴆ', 'ᴇ', 'ᴊ', 'ᴋ', 'ᴌ', 'ᴍ', 'ᴏ', 'ᴘ', 'ᴛ', 'ᴜ', 'ᴠ', 'ᴡ', 'ᴢ', 'ᵫ', 'ᵬ', 'ᵭ', 'ᵮ', 'ᵯ', 'ᵰ', 'ᵱ', 'ᵲ', 'ᵳ', 'ᵴ', 'ᵵ', 'ᵶ', 'ᵺ', 'ᵻ', 'ᵽ', 'ᵾ', 'ᶀ', 'ᶁ', 'ᶂ', 'ᶃ', 'ᶄ', 'ᶅ', 'ᶆ', 'ᶇ', 'ᶈ', 'ᶉ', 'ᶊ', 'ᶌ', 'ᶍ', 'ᶎ', 'ᶏ', 'ᶑ', 'ᶒ', 'ᶓ', 'ᶖ', 'ᶙ', 'ẚ', 'ẜ', 'ẝ', 'ẞ', 'Ỻ', 'ỻ', 'Ỽ', 'ỽ', 'Ỿ', 'ỿ', '©', '®', '₠', '₢', '₣', '₤', '₧', '₺', '₹', 'ℌ', '℞', '㎧', '㎮', '㏆', '㏗', '㏞', '㏟', '¼', '½', '¾', '⅓', '⅔', '⅕', '⅖', '⅗', '⅘', '⅙', '⅚', '⅛', '⅜', '⅝', '⅞', '⅟', '〇', '‘', '’', '‚', '‛', '“', '”', '„', '‟', '′', '″', '〝', '〞', '«', '»', '‹', '›', '‐', '‑', '‒', '–', '—', '―', '︱', '︲', '﹘', '‖', '⁄', '⁅', '⁆', '⁎', '、', '。', '〈', '〉', '《', '》', '〔', '〕', '〘', '〙', '〚', '〛', '︑', '︒', '︹', '︺', '︽', '︾', '︿', '﹀', '﹑', '﹝', '﹞', '⦅', '⦆', '。', '、', '×', '÷', '−', '∕', '∖', '∣', '∥', '≪', '≫', '⦅', '⦆']; + private const TRANSLIT_TO = ['AE', 'D', 'O', 'TH', 'ss', 'ae', 'd', 'o', 'th', 'D', 'd', 'H', 'h', 'i', 'q', 'L', 'l', 'L', 'l', '\'n', 'N', 'n', 'OE', 'oe', 'T', 't', 'b', 'B', 'B', 'b', 'C', 'c', 'D', 'D', 'D', 'd', 'E', 'F', 'f', 'G', 'hv', 'I', 'I', 'K', 'k', 'l', 'N', 'n', 'OI', 'oi', 'P', 'p', 't', 'T', 't', 'T', 'V', 'Y', 'y', 'Z', 'z', 'DZ', 'Dz', 'dz', 'G', 'g', 'd', 'Z', 'z', 'l', 'n', 't', 'j', 'db', 'qp', 'A', 'C', 'c', 'L', 'T', 's', 'z', 'B', 'U', 'E', 'e', 'J', 'j', 'R', 'r', 'Y', 'y', 'b', 'c', 'd', 'd', 'e', 'j', 'g', 'g', 'G', 'h', 'h', 'i', 'I', 'l', 'l', 'l', 'm', 'n', 'n', 'N', 'OE', 'r', 'r', 'r', 'R', 's', 't', 'u', 'v', 'Y', 'z', 'z', 'B', 'G', 'H', 'j', 'L', 'q', 'dz', 'dz', 'ts', 'ls', 'lz', 'A', 'AE', 'B', 'C', 'D', 'D', 'E', 'J', 'K', 'L', 'M', 'O', 'P', 'T', 'U', 'V', 'W', 'Z', 'ue', 'b', 'd', 'f', 'm', 'n', 'p', 'r', 'r', 's', 't', 'z', 'th', 'I', 'p', 'U', 'b', 'd', 'f', 'g', 'k', 'l', 'm', 'n', 'p', 'r', 's', 'v', 'x', 'z', 'a', 'd', 'e', 'e', 'i', 'u', 'a', 's', 's', 'SS', 'LL', 'll', 'V', 'v', 'Y', 'y', '(C)', '(R)', 'CE', 'Cr', 'Fr.', 'L.', 'Pts', 'TL', 'Rs', 'x', 'Rx', 'm/s', 'rad/s', 'C/kg', 'pH', 'V/m', 'A/m', ' 1/4', ' 1/2', ' 3/4', ' 1/3', ' 2/3', ' 1/5', ' 2/5', ' 3/5', ' 4/5', ' 1/6', ' 5/6', ' 1/8', ' 3/8', ' 5/8', ' 7/8', ' 1/', '0', '\'', '\'', ',', '\'', '"', '"', ',,', '"', '\'', '"', '"', '"', '<<', '>>', '<', '>', '-', '-', '-', '-', '-', '-', '-', '-', '-', '||', '/', '[', ']', '*', ',', '.', '<', '>', '<<', '>>', '[', ']', '[', ']', '[', ']', ',', '.', '[', ']', '<<', '>>', '<', '>', ',', '[', ']', '((', '))', '.', ',', '*', '/', '-', '/', '\\', '|', '||', '<<', '>>', '((', '))']; + + private static array $transliterators = []; + private static array $tableZero; + private static array $tableWide; + + public static function fromCodePoints(int ...$codes): static + { + $string = ''; + + foreach ($codes as $code) { + if (0x80 > $code %= 0x200000) { + $string .= \chr($code); + } elseif (0x800 > $code) { + $string .= \chr(0xC0 | $code >> 6).\chr(0x80 | $code & 0x3F); + } elseif (0x10000 > $code) { + $string .= \chr(0xE0 | $code >> 12).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); + } else { + $string .= \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); + } + } + + return new static($string); + } + + /** + * Generic UTF-8 to ASCII transliteration. + * + * Install the intl extension for best results. + * + * @param string[]|\Transliterator[]|\Closure[] $rules See "*-Latin" rules from Transliterator::listIDs() + */ + public function ascii(array $rules = []): self + { + $str = clone $this; + $s = $str->string; + $str->string = ''; + + array_unshift($rules, 'nfd'); + $rules[] = 'latin-ascii'; + + if (\function_exists('transliterator_transliterate')) { + $rules[] = 'any-latin/bgn'; + } + + $rules[] = 'nfkd'; + $rules[] = '[:nonspacing mark:] remove'; + + while (\strlen($s) - 1 > $i = strspn($s, self::ASCII)) { + if (0 < --$i) { + $str->string .= substr($s, 0, $i); + $s = substr($s, $i); + } + + if (!$rule = array_shift($rules)) { + $rules = []; // An empty rule interrupts the next ones + } + + if ($rule instanceof \Transliterator) { + $s = $rule->transliterate($s); + } elseif ($rule instanceof \Closure) { + $s = $rule($s); + } elseif ($rule) { + if ('nfd' === $rule = strtolower($rule)) { + normalizer_is_normalized($s, self::NFD) ?: $s = normalizer_normalize($s, self::NFD); + } elseif ('nfkd' === $rule) { + normalizer_is_normalized($s, self::NFKD) ?: $s = normalizer_normalize($s, self::NFKD); + } elseif ('[:nonspacing mark:] remove' === $rule) { + $s = preg_replace('/\p{Mn}++/u', '', $s); + } elseif ('latin-ascii' === $rule) { + $s = str_replace(self::TRANSLIT_FROM, self::TRANSLIT_TO, $s); + } elseif ('de-ascii' === $rule) { + $s = preg_replace("/([AUO])\u{0308}(?=\p{Ll})/u", '$1e', $s); + $s = str_replace(["a\u{0308}", "o\u{0308}", "u\u{0308}", "A\u{0308}", "O\u{0308}", "U\u{0308}"], ['ae', 'oe', 'ue', 'AE', 'OE', 'UE'], $s); + } elseif (\function_exists('transliterator_transliterate')) { + if (null === $transliterator = self::$transliterators[$rule] ??= \Transliterator::create($rule)) { + if ('any-latin/bgn' === $rule) { + $rule = 'any-latin'; + $transliterator = self::$transliterators[$rule] ??= \Transliterator::create($rule); + } + + if (null === $transliterator) { + throw new InvalidArgumentException(sprintf('Unknown transliteration rule "%s".', $rule)); + } + + self::$transliterators['any-latin/bgn'] = $transliterator; + } + + $s = $transliterator->transliterate($s); + } + } elseif (!\function_exists('iconv')) { + $s = preg_replace('/[^\x00-\x7F]/u', '?', $s); + } else { + $s = @preg_replace_callback('/[^\x00-\x7F]/u', static function ($c) { + $c = (string) iconv('UTF-8', 'ASCII//TRANSLIT', $c[0]); + + if ('' === $c && '' === iconv('UTF-8', 'ASCII//TRANSLIT', '²')) { + throw new \LogicException(sprintf('"%s" requires a translit-able iconv implementation, try installing "gnu-libiconv" if you\'re using Alpine Linux.', static::class)); + } + + return 1 < \strlen($c) ? ltrim($c, '\'`"^~') : ('' !== $c ? $c : '?'); + }, $s); + } + } + + $str->string .= $s; + + return $str; + } + + public function camel(): static + { + $str = clone $this; + $str->string = str_replace(' ', '', preg_replace_callback('/\b.(?![A-Z]{2,})/u', static function ($m) { + static $i = 0; + + return 1 === ++$i ? ('İ' === $m[0] ? 'i̇' : mb_strtolower($m[0], 'UTF-8')) : mb_convert_case($m[0], \MB_CASE_TITLE, 'UTF-8'); + }, preg_replace('/[^\pL0-9]++/u', ' ', $this->string))); + + return $str; + } + + /** + * @return int[] + */ + public function codePointsAt(int $offset): array + { + $str = $this->slice($offset, 1); + + if ('' === $str->string) { + return []; + } + + $codePoints = []; + + foreach (preg_split('//u', $str->string, -1, \PREG_SPLIT_NO_EMPTY) as $c) { + $codePoints[] = mb_ord($c, 'UTF-8'); + } + + return $codePoints; + } + + public function folded(bool $compat = true): static + { + $str = clone $this; + + if (!$compat || !\defined('Normalizer::NFKC_CF')) { + $str->string = normalizer_normalize($str->string, $compat ? \Normalizer::NFKC : \Normalizer::NFC); + $str->string = mb_strtolower(str_replace(self::FOLD_FROM, self::FOLD_TO, $this->string), 'UTF-8'); + } else { + $str->string = normalizer_normalize($str->string, \Normalizer::NFKC_CF); + } + + return $str; + } + + public function join(array $strings, string $lastGlue = null): static + { + $str = clone $this; + + $tail = null !== $lastGlue && 1 < \count($strings) ? $lastGlue.array_pop($strings) : ''; + $str->string = implode($this->string, $strings).$tail; + + if (!preg_match('//u', $str->string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + return $str; + } + + public function lower(): static + { + $str = clone $this; + $str->string = mb_strtolower(str_replace('İ', 'i̇', $str->string), 'UTF-8'); + + return $str; + } + + public function match(string $regexp, int $flags = 0, int $offset = 0): array + { + $match = ((\PREG_PATTERN_ORDER | \PREG_SET_ORDER) & $flags) ? 'preg_match_all' : 'preg_match'; + + if ($this->ignoreCase) { + $regexp .= 'i'; + } + + set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m)); + + try { + if (false === $match($regexp.'u', $this->string, $matches, $flags | \PREG_UNMATCHED_AS_NULL, $offset)) { + throw new RuntimeException('Matching failed with error: '.preg_last_error_msg()); + } + } finally { + restore_error_handler(); + } + + return $matches; + } + + public function normalize(int $form = self::NFC): static + { + if (!\in_array($form, [self::NFC, self::NFD, self::NFKC, self::NFKD])) { + throw new InvalidArgumentException('Unsupported normalization form.'); + } + + $str = clone $this; + normalizer_is_normalized($str->string, $form) ?: $str->string = normalizer_normalize($str->string, $form); + + return $str; + } + + public function padBoth(int $length, string $padStr = ' '): static + { + if ('' === $padStr || !preg_match('//u', $padStr)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $pad = clone $this; + $pad->string = $padStr; + + return $this->pad($length, $pad, \STR_PAD_BOTH); + } + + public function padEnd(int $length, string $padStr = ' '): static + { + if ('' === $padStr || !preg_match('//u', $padStr)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $pad = clone $this; + $pad->string = $padStr; + + return $this->pad($length, $pad, \STR_PAD_RIGHT); + } + + public function padStart(int $length, string $padStr = ' '): static + { + if ('' === $padStr || !preg_match('//u', $padStr)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $pad = clone $this; + $pad->string = $padStr; + + return $this->pad($length, $pad, \STR_PAD_LEFT); + } + + public function replaceMatches(string $fromRegexp, string|callable $to): static + { + if ($this->ignoreCase) { + $fromRegexp .= 'i'; + } + + if (\is_array($to) || $to instanceof \Closure) { + $replace = 'preg_replace_callback'; + $to = static function (array $m) use ($to): string { + $to = $to($m); + + if ('' !== $to && (!\is_string($to) || !preg_match('//u', $to))) { + throw new InvalidArgumentException('Replace callback must return a valid UTF-8 string.'); + } + + return $to; + }; + } elseif ('' !== $to && !preg_match('//u', $to)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } else { + $replace = 'preg_replace'; + } + + set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m)); + + try { + if (null === $string = $replace($fromRegexp.'u', $to, $this->string)) { + $lastError = preg_last_error(); + + foreach (get_defined_constants(true)['pcre'] as $k => $v) { + if ($lastError === $v && str_ends_with($k, '_ERROR')) { + throw new RuntimeException('Matching failed with '.$k.'.'); + } + } + + throw new RuntimeException('Matching failed with unknown error code.'); + } + } finally { + restore_error_handler(); + } + + $str = clone $this; + $str->string = $string; + + return $str; + } + + public function reverse(): static + { + $str = clone $this; + $str->string = implode('', array_reverse(preg_split('/(\X)/u', $str->string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY))); + + return $str; + } + + public function snake(): static + { + $str = $this->camel(); + $str->string = mb_strtolower(preg_replace(['/(\p{Lu}+)(\p{Lu}\p{Ll})/u', '/([\p{Ll}0-9])(\p{Lu})/u'], '\1_\2', $str->string), 'UTF-8'); + + return $str; + } + + public function title(bool $allWords = false): static + { + $str = clone $this; + + $limit = $allWords ? -1 : 1; + + $str->string = preg_replace_callback('/\b./u', static fn (array $m): string => mb_convert_case($m[0], \MB_CASE_TITLE, 'UTF-8'), $str->string, $limit); + + return $str; + } + + public function trim(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static + { + if (" \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}" !== $chars && !preg_match('//u', $chars)) { + throw new InvalidArgumentException('Invalid UTF-8 chars.'); + } + $chars = preg_quote($chars); + + $str = clone $this; + $str->string = preg_replace("{^[$chars]++|[$chars]++$}uD", '', $str->string); + + return $str; + } + + public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static + { + if (" \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}" !== $chars && !preg_match('//u', $chars)) { + throw new InvalidArgumentException('Invalid UTF-8 chars.'); + } + $chars = preg_quote($chars); + + $str = clone $this; + $str->string = preg_replace("{[$chars]++$}uD", '', $str->string); + + return $str; + } + + public function trimPrefix($prefix): static + { + if (!$this->ignoreCase) { + return parent::trimPrefix($prefix); + } + + $str = clone $this; + + if ($prefix instanceof \Traversable) { + $prefix = iterator_to_array($prefix, false); + } elseif ($prefix instanceof parent) { + $prefix = $prefix->string; + } + + $prefix = implode('|', array_map('preg_quote', (array) $prefix)); + $str->string = preg_replace("{^(?:$prefix)}iuD", '', $this->string); + + return $str; + } + + public function trimStart(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static + { + if (" \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}" !== $chars && !preg_match('//u', $chars)) { + throw new InvalidArgumentException('Invalid UTF-8 chars.'); + } + $chars = preg_quote($chars); + + $str = clone $this; + $str->string = preg_replace("{^[$chars]++}uD", '', $str->string); + + return $str; + } + + public function trimSuffix($suffix): static + { + if (!$this->ignoreCase) { + return parent::trimSuffix($suffix); + } + + $str = clone $this; + + if ($suffix instanceof \Traversable) { + $suffix = iterator_to_array($suffix, false); + } elseif ($suffix instanceof parent) { + $suffix = $suffix->string; + } + + $suffix = implode('|', array_map('preg_quote', (array) $suffix)); + $str->string = preg_replace("{(?:$suffix)$}iuD", '', $this->string); + + return $str; + } + + public function upper(): static + { + $str = clone $this; + $str->string = mb_strtoupper($str->string, 'UTF-8'); + + return $str; + } + + public function width(bool $ignoreAnsiDecoration = true): int + { + $width = 0; + $s = str_replace(["\x00", "\x05", "\x07"], '', $this->string); + + if (str_contains($s, "\r")) { + $s = str_replace(["\r\n", "\r"], "\n", $s); + } + + if (!$ignoreAnsiDecoration) { + $s = preg_replace('/[\p{Cc}\x7F]++/u', '', $s); + } + + foreach (explode("\n", $s) as $s) { + if ($ignoreAnsiDecoration) { + $s = preg_replace('/(?:\x1B(?: + \[ [\x30-\x3F]*+ [\x20-\x2F]*+ [\x40-\x7E] + | [P\]X^_] .*? \x1B\\\\ + | [\x41-\x7E] + )|[\p{Cc}\x7F]++)/xu', '', $s); + } + + $lineWidth = $this->wcswidth($s); + + if ($lineWidth > $width) { + $width = $lineWidth; + } + } + + return $width; + } + + private function pad(int $len, self $pad, int $type): static + { + $sLen = $this->length(); + + if ($len <= $sLen) { + return clone $this; + } + + $padLen = $pad->length(); + $freeLen = $len - $sLen; + $len = $freeLen % $padLen; + + switch ($type) { + case \STR_PAD_RIGHT: + return $this->append(str_repeat($pad->string, intdiv($freeLen, $padLen)).($len ? $pad->slice(0, $len) : '')); + + case \STR_PAD_LEFT: + return $this->prepend(str_repeat($pad->string, intdiv($freeLen, $padLen)).($len ? $pad->slice(0, $len) : '')); + + case \STR_PAD_BOTH: + $freeLen /= 2; + + $rightLen = ceil($freeLen); + $len = $rightLen % $padLen; + $str = $this->append(str_repeat($pad->string, intdiv($rightLen, $padLen)).($len ? $pad->slice(0, $len) : '')); + + $leftLen = floor($freeLen); + $len = $leftLen % $padLen; + + return $str->prepend(str_repeat($pad->string, intdiv($leftLen, $padLen)).($len ? $pad->slice(0, $len) : '')); + + default: + throw new InvalidArgumentException('Invalid padding type.'); + } + } + + /** + * Based on https://github.com/jquast/wcwidth, a Python implementation of https://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c. + */ + private function wcswidth(string $string): int + { + $width = 0; + + foreach (preg_split('//u', $string, -1, \PREG_SPLIT_NO_EMPTY) as $c) { + $codePoint = mb_ord($c, 'UTF-8'); + + if (0 === $codePoint // NULL + || 0x034F === $codePoint // COMBINING GRAPHEME JOINER + || (0x200B <= $codePoint && 0x200F >= $codePoint) // ZERO WIDTH SPACE to RIGHT-TO-LEFT MARK + || 0x2028 === $codePoint // LINE SEPARATOR + || 0x2029 === $codePoint // PARAGRAPH SEPARATOR + || (0x202A <= $codePoint && 0x202E >= $codePoint) // LEFT-TO-RIGHT EMBEDDING to RIGHT-TO-LEFT OVERRIDE + || (0x2060 <= $codePoint && 0x2063 >= $codePoint) // WORD JOINER to INVISIBLE SEPARATOR + ) { + continue; + } + + // Non printable characters + if (32 > $codePoint // C0 control characters + || (0x07F <= $codePoint && 0x0A0 > $codePoint) // C1 control characters and DEL + ) { + return -1; + } + + self::$tableZero ??= require __DIR__.'/Resources/data/wcswidth_table_zero.php'; + + if ($codePoint >= self::$tableZero[0][0] && $codePoint <= self::$tableZero[$ubound = \count(self::$tableZero) - 1][1]) { + $lbound = 0; + while ($ubound >= $lbound) { + $mid = floor(($lbound + $ubound) / 2); + + if ($codePoint > self::$tableZero[$mid][1]) { + $lbound = $mid + 1; + } elseif ($codePoint < self::$tableZero[$mid][0]) { + $ubound = $mid - 1; + } else { + continue 2; + } + } + } + + self::$tableWide ??= require __DIR__.'/Resources/data/wcswidth_table_wide.php'; + + if ($codePoint >= self::$tableWide[0][0] && $codePoint <= self::$tableWide[$ubound = \count(self::$tableWide) - 1][1]) { + $lbound = 0; + while ($ubound >= $lbound) { + $mid = floor(($lbound + $ubound) / 2); + + if ($codePoint > self::$tableWide[$mid][1]) { + $lbound = $mid + 1; + } elseif ($codePoint < self::$tableWide[$mid][0]) { + $ubound = $mid - 1; + } else { + $width += 2; + + continue 2; + } + } + } + + ++$width; + } + + return $width; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/ByteString.php b/tools/php-cs-fixer/vendor/symfony/string/ByteString.php new file mode 100644 index 00000000..f5050ddf --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/ByteString.php @@ -0,0 +1,485 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String; + +use Symfony\Component\String\Exception\ExceptionInterface; +use Symfony\Component\String\Exception\InvalidArgumentException; +use Symfony\Component\String\Exception\RuntimeException; + +/** + * Represents a binary-safe string of bytes. + * + * @author Nicolas Grekas + * @author Hugo Hamon + * + * @throws ExceptionInterface + */ +class ByteString extends AbstractString +{ + private const ALPHABET_ALPHANUMERIC = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + + public function __construct(string $string = '') + { + $this->string = $string; + } + + /* + * The following method was derived from code of the Hack Standard Library (v4.40 - 2020-05-03) + * + * https://github.com/hhvm/hsl/blob/80a42c02f036f72a42f0415e80d6b847f4bf62d5/src/random/private.php#L16 + * + * Code subject to the MIT license (https://github.com/hhvm/hsl/blob/master/LICENSE). + * + * Copyright (c) 2004-2020, Facebook, Inc. (https://www.facebook.com/) + */ + + public static function fromRandom(int $length = 16, string $alphabet = null): self + { + if ($length <= 0) { + throw new InvalidArgumentException(sprintf('A strictly positive length is expected, "%d" given.', $length)); + } + + $alphabet ??= self::ALPHABET_ALPHANUMERIC; + $alphabetSize = \strlen($alphabet); + $bits = (int) ceil(log($alphabetSize, 2.0)); + if ($bits <= 0 || $bits > 56) { + throw new InvalidArgumentException('The length of the alphabet must in the [2^1, 2^56] range.'); + } + + $ret = ''; + while ($length > 0) { + $urandomLength = (int) ceil(2 * $length * $bits / 8.0); + $data = random_bytes($urandomLength); + $unpackedData = 0; + $unpackedBits = 0; + for ($i = 0; $i < $urandomLength && $length > 0; ++$i) { + // Unpack 8 bits + $unpackedData = ($unpackedData << 8) | \ord($data[$i]); + $unpackedBits += 8; + + // While we have enough bits to select a character from the alphabet, keep + // consuming the random data + for (; $unpackedBits >= $bits && $length > 0; $unpackedBits -= $bits) { + $index = ($unpackedData & ((1 << $bits) - 1)); + $unpackedData >>= $bits; + // Unfortunately, the alphabet size is not necessarily a power of two. + // Worst case, it is 2^k + 1, which means we need (k+1) bits and we + // have around a 50% chance of missing as k gets larger + if ($index < $alphabetSize) { + $ret .= $alphabet[$index]; + --$length; + } + } + } + } + + return new static($ret); + } + + public function bytesAt(int $offset): array + { + $str = $this->string[$offset] ?? ''; + + return '' === $str ? [] : [\ord($str)]; + } + + public function append(string ...$suffix): static + { + $str = clone $this; + $str->string .= 1 >= \count($suffix) ? ($suffix[0] ?? '') : implode('', $suffix); + + return $str; + } + + public function camel(): static + { + $str = clone $this; + + $parts = explode(' ', trim(ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $this->string)))); + $parts[0] = 1 !== \strlen($parts[0]) && ctype_upper($parts[0]) ? $parts[0] : lcfirst($parts[0]); + $str->string = implode('', $parts); + + return $str; + } + + public function chunk(int $length = 1): array + { + if (1 > $length) { + throw new InvalidArgumentException('The chunk length must be greater than zero.'); + } + + if ('' === $this->string) { + return []; + } + + $str = clone $this; + $chunks = []; + + foreach (str_split($this->string, $length) as $chunk) { + $str->string = $chunk; + $chunks[] = clone $str; + } + + return $chunks; + } + + public function endsWith(string|iterable|AbstractString $suffix): bool + { + if ($suffix instanceof AbstractString) { + $suffix = $suffix->string; + } elseif (!\is_string($suffix)) { + return parent::endsWith($suffix); + } + + return '' !== $suffix && \strlen($this->string) >= \strlen($suffix) && 0 === substr_compare($this->string, $suffix, -\strlen($suffix), null, $this->ignoreCase); + } + + public function equalsTo(string|iterable|AbstractString $string): bool + { + if ($string instanceof AbstractString) { + $string = $string->string; + } elseif (!\is_string($string)) { + return parent::equalsTo($string); + } + + if ('' !== $string && $this->ignoreCase) { + return 0 === strcasecmp($string, $this->string); + } + + return $string === $this->string; + } + + public function folded(): static + { + $str = clone $this; + $str->string = strtolower($str->string); + + return $str; + } + + public function indexOf(string|iterable|AbstractString $needle, int $offset = 0): ?int + { + if ($needle instanceof AbstractString) { + $needle = $needle->string; + } elseif (!\is_string($needle)) { + return parent::indexOf($needle, $offset); + } + + if ('' === $needle) { + return null; + } + + $i = $this->ignoreCase ? stripos($this->string, $needle, $offset) : strpos($this->string, $needle, $offset); + + return false === $i ? null : $i; + } + + public function indexOfLast(string|iterable|AbstractString $needle, int $offset = 0): ?int + { + if ($needle instanceof AbstractString) { + $needle = $needle->string; + } elseif (!\is_string($needle)) { + return parent::indexOfLast($needle, $offset); + } + + if ('' === $needle) { + return null; + } + + $i = $this->ignoreCase ? strripos($this->string, $needle, $offset) : strrpos($this->string, $needle, $offset); + + return false === $i ? null : $i; + } + + public function isUtf8(): bool + { + return '' === $this->string || preg_match('//u', $this->string); + } + + public function join(array $strings, string $lastGlue = null): static + { + $str = clone $this; + + $tail = null !== $lastGlue && 1 < \count($strings) ? $lastGlue.array_pop($strings) : ''; + $str->string = implode($this->string, $strings).$tail; + + return $str; + } + + public function length(): int + { + return \strlen($this->string); + } + + public function lower(): static + { + $str = clone $this; + $str->string = strtolower($str->string); + + return $str; + } + + public function match(string $regexp, int $flags = 0, int $offset = 0): array + { + $match = ((\PREG_PATTERN_ORDER | \PREG_SET_ORDER) & $flags) ? 'preg_match_all' : 'preg_match'; + + if ($this->ignoreCase) { + $regexp .= 'i'; + } + + set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m)); + + try { + if (false === $match($regexp, $this->string, $matches, $flags | \PREG_UNMATCHED_AS_NULL, $offset)) { + throw new RuntimeException('Matching failed with error: '.preg_last_error_msg()); + } + } finally { + restore_error_handler(); + } + + return $matches; + } + + public function padBoth(int $length, string $padStr = ' '): static + { + $str = clone $this; + $str->string = str_pad($this->string, $length, $padStr, \STR_PAD_BOTH); + + return $str; + } + + public function padEnd(int $length, string $padStr = ' '): static + { + $str = clone $this; + $str->string = str_pad($this->string, $length, $padStr, \STR_PAD_RIGHT); + + return $str; + } + + public function padStart(int $length, string $padStr = ' '): static + { + $str = clone $this; + $str->string = str_pad($this->string, $length, $padStr, \STR_PAD_LEFT); + + return $str; + } + + public function prepend(string ...$prefix): static + { + $str = clone $this; + $str->string = (1 >= \count($prefix) ? ($prefix[0] ?? '') : implode('', $prefix)).$str->string; + + return $str; + } + + public function replace(string $from, string $to): static + { + $str = clone $this; + + if ('' !== $from) { + $str->string = $this->ignoreCase ? str_ireplace($from, $to, $this->string) : str_replace($from, $to, $this->string); + } + + return $str; + } + + public function replaceMatches(string $fromRegexp, string|callable $to): static + { + if ($this->ignoreCase) { + $fromRegexp .= 'i'; + } + + $replace = \is_array($to) || $to instanceof \Closure ? 'preg_replace_callback' : 'preg_replace'; + + set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m)); + + try { + if (null === $string = $replace($fromRegexp, $to, $this->string)) { + $lastError = preg_last_error(); + + foreach (get_defined_constants(true)['pcre'] as $k => $v) { + if ($lastError === $v && str_ends_with($k, '_ERROR')) { + throw new RuntimeException('Matching failed with '.$k.'.'); + } + } + + throw new RuntimeException('Matching failed with unknown error code.'); + } + } finally { + restore_error_handler(); + } + + $str = clone $this; + $str->string = $string; + + return $str; + } + + public function reverse(): static + { + $str = clone $this; + $str->string = strrev($str->string); + + return $str; + } + + public function slice(int $start = 0, int $length = null): static + { + $str = clone $this; + $str->string = (string) substr($this->string, $start, $length ?? \PHP_INT_MAX); + + return $str; + } + + public function snake(): static + { + $str = $this->camel(); + $str->string = strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], '\1_\2', $str->string)); + + return $str; + } + + public function splice(string $replacement, int $start = 0, int $length = null): static + { + $str = clone $this; + $str->string = substr_replace($this->string, $replacement, $start, $length ?? \PHP_INT_MAX); + + return $str; + } + + public function split(string $delimiter, int $limit = null, int $flags = null): array + { + if (1 > $limit ??= \PHP_INT_MAX) { + throw new InvalidArgumentException('Split limit must be a positive integer.'); + } + + if ('' === $delimiter) { + throw new InvalidArgumentException('Split delimiter is empty.'); + } + + if (null !== $flags) { + return parent::split($delimiter, $limit, $flags); + } + + $str = clone $this; + $chunks = $this->ignoreCase + ? preg_split('{'.preg_quote($delimiter).'}iD', $this->string, $limit) + : explode($delimiter, $this->string, $limit); + + foreach ($chunks as &$chunk) { + $str->string = $chunk; + $chunk = clone $str; + } + + return $chunks; + } + + public function startsWith(string|iterable|AbstractString $prefix): bool + { + if ($prefix instanceof AbstractString) { + $prefix = $prefix->string; + } elseif (!\is_string($prefix)) { + return parent::startsWith($prefix); + } + + return '' !== $prefix && 0 === ($this->ignoreCase ? strncasecmp($this->string, $prefix, \strlen($prefix)) : strncmp($this->string, $prefix, \strlen($prefix))); + } + + public function title(bool $allWords = false): static + { + $str = clone $this; + $str->string = $allWords ? ucwords($str->string) : ucfirst($str->string); + + return $str; + } + + public function toUnicodeString(string $fromEncoding = null): UnicodeString + { + return new UnicodeString($this->toCodePointString($fromEncoding)->string); + } + + public function toCodePointString(string $fromEncoding = null): CodePointString + { + $u = new CodePointString(); + + if (\in_array($fromEncoding, [null, 'utf8', 'utf-8', 'UTF8', 'UTF-8'], true) && preg_match('//u', $this->string)) { + $u->string = $this->string; + + return $u; + } + + set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m)); + + try { + try { + $validEncoding = false !== mb_detect_encoding($this->string, $fromEncoding ?? 'Windows-1252', true); + } catch (InvalidArgumentException $e) { + if (!\function_exists('iconv')) { + throw $e; + } + + $u->string = iconv($fromEncoding ?? 'Windows-1252', 'UTF-8', $this->string); + + return $u; + } + } finally { + restore_error_handler(); + } + + if (!$validEncoding) { + throw new InvalidArgumentException(sprintf('Invalid "%s" string.', $fromEncoding ?? 'Windows-1252')); + } + + $u->string = mb_convert_encoding($this->string, 'UTF-8', $fromEncoding ?? 'Windows-1252'); + + return $u; + } + + public function trim(string $chars = " \t\n\r\0\x0B\x0C"): static + { + $str = clone $this; + $str->string = trim($str->string, $chars); + + return $str; + } + + public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C"): static + { + $str = clone $this; + $str->string = rtrim($str->string, $chars); + + return $str; + } + + public function trimStart(string $chars = " \t\n\r\0\x0B\x0C"): static + { + $str = clone $this; + $str->string = ltrim($str->string, $chars); + + return $str; + } + + public function upper(): static + { + $str = clone $this; + $str->string = strtoupper($str->string); + + return $str; + } + + public function width(bool $ignoreAnsiDecoration = true): int + { + $string = preg_match('//u', $this->string) ? $this->string : preg_replace('/[\x80-\xFF]/', '?', $this->string); + + return (new CodePointString($string))->width($ignoreAnsiDecoration); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/CHANGELOG.md b/tools/php-cs-fixer/vendor/symfony/string/CHANGELOG.md new file mode 100644 index 00000000..31a3b54d --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/CHANGELOG.md @@ -0,0 +1,40 @@ +CHANGELOG +========= + +6.2 +--- + + * Add support for emoji in `AsciiSlugger` + +5.4 +--- + + * Add `trimSuffix()` and `trimPrefix()` methods + +5.3 +--- + + * Made `AsciiSlugger` fallback to parent locale's symbolsMap + +5.2.0 +----- + + * added a `FrenchInflector` class + +5.1.0 +----- + + * added the `AbstractString::reverse()` method + * made `AbstractString::width()` follow POSIX.1-2001 + * added `LazyString` which provides memoizing stringable objects + * The component is not marked as `@experimental` anymore + * added the `s()` helper method to get either an `UnicodeString` or `ByteString` instance, + depending of the input string UTF-8 compliancy + * added `$cut` parameter to `Symfony\Component\String\AbstractString::truncate()` + * added `AbstractString::containsAny()` + * allow passing a string of custom characters to `ByteString::fromRandom()` + +5.0.0 +----- + + * added the component as experimental diff --git a/tools/php-cs-fixer/vendor/symfony/string/CodePointString.php b/tools/php-cs-fixer/vendor/symfony/string/CodePointString.php new file mode 100644 index 00000000..f5c900fb --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/CodePointString.php @@ -0,0 +1,260 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String; + +use Symfony\Component\String\Exception\ExceptionInterface; +use Symfony\Component\String\Exception\InvalidArgumentException; + +/** + * Represents a string of Unicode code points encoded as UTF-8. + * + * @author Nicolas Grekas + * @author Hugo Hamon + * + * @throws ExceptionInterface + */ +class CodePointString extends AbstractUnicodeString +{ + public function __construct(string $string = '') + { + if ('' !== $string && !preg_match('//u', $string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $this->string = $string; + } + + public function append(string ...$suffix): static + { + $str = clone $this; + $str->string .= 1 >= \count($suffix) ? ($suffix[0] ?? '') : implode('', $suffix); + + if (!preg_match('//u', $str->string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + return $str; + } + + public function chunk(int $length = 1): array + { + if (1 > $length) { + throw new InvalidArgumentException('The chunk length must be greater than zero.'); + } + + if ('' === $this->string) { + return []; + } + + $rx = '/('; + while (65535 < $length) { + $rx .= '.{65535}'; + $length -= 65535; + } + $rx .= '.{'.$length.'})/us'; + + $str = clone $this; + $chunks = []; + + foreach (preg_split($rx, $this->string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY) as $chunk) { + $str->string = $chunk; + $chunks[] = clone $str; + } + + return $chunks; + } + + public function codePointsAt(int $offset): array + { + $str = $offset ? $this->slice($offset, 1) : $this; + + return '' === $str->string ? [] : [mb_ord($str->string, 'UTF-8')]; + } + + public function endsWith(string|iterable|AbstractString $suffix): bool + { + if ($suffix instanceof AbstractString) { + $suffix = $suffix->string; + } elseif (!\is_string($suffix)) { + return parent::endsWith($suffix); + } + + if ('' === $suffix || !preg_match('//u', $suffix)) { + return false; + } + + if ($this->ignoreCase) { + return preg_match('{'.preg_quote($suffix).'$}iuD', $this->string); + } + + return \strlen($this->string) >= \strlen($suffix) && 0 === substr_compare($this->string, $suffix, -\strlen($suffix)); + } + + public function equalsTo(string|iterable|AbstractString $string): bool + { + if ($string instanceof AbstractString) { + $string = $string->string; + } elseif (!\is_string($string)) { + return parent::equalsTo($string); + } + + if ('' !== $string && $this->ignoreCase) { + return \strlen($string) === \strlen($this->string) && 0 === mb_stripos($this->string, $string, 0, 'UTF-8'); + } + + return $string === $this->string; + } + + public function indexOf(string|iterable|AbstractString $needle, int $offset = 0): ?int + { + if ($needle instanceof AbstractString) { + $needle = $needle->string; + } elseif (!\is_string($needle)) { + return parent::indexOf($needle, $offset); + } + + if ('' === $needle) { + return null; + } + + $i = $this->ignoreCase ? mb_stripos($this->string, $needle, $offset, 'UTF-8') : mb_strpos($this->string, $needle, $offset, 'UTF-8'); + + return false === $i ? null : $i; + } + + public function indexOfLast(string|iterable|AbstractString $needle, int $offset = 0): ?int + { + if ($needle instanceof AbstractString) { + $needle = $needle->string; + } elseif (!\is_string($needle)) { + return parent::indexOfLast($needle, $offset); + } + + if ('' === $needle) { + return null; + } + + $i = $this->ignoreCase ? mb_strripos($this->string, $needle, $offset, 'UTF-8') : mb_strrpos($this->string, $needle, $offset, 'UTF-8'); + + return false === $i ? null : $i; + } + + public function length(): int + { + return mb_strlen($this->string, 'UTF-8'); + } + + public function prepend(string ...$prefix): static + { + $str = clone $this; + $str->string = (1 >= \count($prefix) ? ($prefix[0] ?? '') : implode('', $prefix)).$this->string; + + if (!preg_match('//u', $str->string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + return $str; + } + + public function replace(string $from, string $to): static + { + $str = clone $this; + + if ('' === $from || !preg_match('//u', $from)) { + return $str; + } + + if ('' !== $to && !preg_match('//u', $to)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + if ($this->ignoreCase) { + $str->string = implode($to, preg_split('{'.preg_quote($from).'}iuD', $this->string)); + } else { + $str->string = str_replace($from, $to, $this->string); + } + + return $str; + } + + public function slice(int $start = 0, int $length = null): static + { + $str = clone $this; + $str->string = mb_substr($this->string, $start, $length, 'UTF-8'); + + return $str; + } + + public function splice(string $replacement, int $start = 0, int $length = null): static + { + if (!preg_match('//u', $replacement)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $str = clone $this; + $start = $start ? \strlen(mb_substr($this->string, 0, $start, 'UTF-8')) : 0; + $length = $length ? \strlen(mb_substr($this->string, $start, $length, 'UTF-8')) : $length; + $str->string = substr_replace($this->string, $replacement, $start, $length ?? \PHP_INT_MAX); + + return $str; + } + + public function split(string $delimiter, int $limit = null, int $flags = null): array + { + if (1 > $limit ??= \PHP_INT_MAX) { + throw new InvalidArgumentException('Split limit must be a positive integer.'); + } + + if ('' === $delimiter) { + throw new InvalidArgumentException('Split delimiter is empty.'); + } + + if (null !== $flags) { + return parent::split($delimiter.'u', $limit, $flags); + } + + if (!preg_match('//u', $delimiter)) { + throw new InvalidArgumentException('Split delimiter is not a valid UTF-8 string.'); + } + + $str = clone $this; + $chunks = $this->ignoreCase + ? preg_split('{'.preg_quote($delimiter).'}iuD', $this->string, $limit) + : explode($delimiter, $this->string, $limit); + + foreach ($chunks as &$chunk) { + $str->string = $chunk; + $chunk = clone $str; + } + + return $chunks; + } + + public function startsWith(string|iterable|AbstractString $prefix): bool + { + if ($prefix instanceof AbstractString) { + $prefix = $prefix->string; + } elseif (!\is_string($prefix)) { + return parent::startsWith($prefix); + } + + if ('' === $prefix || !preg_match('//u', $prefix)) { + return false; + } + + if ($this->ignoreCase) { + return 0 === mb_stripos($this->string, $prefix, 0, 'UTF-8'); + } + + return 0 === strncmp($this->string, $prefix, \strlen($prefix)); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/Exception/ExceptionInterface.php b/tools/php-cs-fixer/vendor/symfony/string/Exception/ExceptionInterface.php new file mode 100644 index 00000000..36197865 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/Exception/ExceptionInterface.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Exception; + +interface ExceptionInterface extends \Throwable +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/Exception/InvalidArgumentException.php b/tools/php-cs-fixer/vendor/symfony/string/Exception/InvalidArgumentException.php new file mode 100644 index 00000000..6aa586bc --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/Exception/InvalidArgumentException.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Exception; + +class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/Exception/RuntimeException.php b/tools/php-cs-fixer/vendor/symfony/string/Exception/RuntimeException.php new file mode 100644 index 00000000..77cb091f --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/Exception/RuntimeException.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Exception; + +class RuntimeException extends \RuntimeException implements ExceptionInterface +{ +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/Inflector/EnglishInflector.php b/tools/php-cs-fixer/vendor/symfony/string/Inflector/EnglishInflector.php new file mode 100644 index 00000000..feea7f66 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/Inflector/EnglishInflector.php @@ -0,0 +1,541 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Inflector; + +final class EnglishInflector implements InflectorInterface +{ + /** + * Map English plural to singular suffixes. + * + * @see http://english-zone.com/spelling/plurals.html + */ + private const PLURAL_MAP = [ + // First entry: plural suffix, reversed + // Second entry: length of plural suffix + // Third entry: Whether the suffix may succeed a vowel + // Fourth entry: Whether the suffix may succeed a consonant + // Fifth entry: singular suffix, normal + + // bacteria (bacterium), criteria (criterion), phenomena (phenomenon) + ['a', 1, true, true, ['on', 'um']], + + // nebulae (nebula) + ['ea', 2, true, true, 'a'], + + // services (service) + ['secivres', 8, true, true, 'service'], + + // mice (mouse), lice (louse) + ['eci', 3, false, true, 'ouse'], + + // geese (goose) + ['esee', 4, false, true, 'oose'], + + // fungi (fungus), alumni (alumnus), syllabi (syllabus), radii (radius) + ['i', 1, true, true, 'us'], + + // men (man), women (woman) + ['nem', 3, true, true, 'man'], + + // children (child) + ['nerdlihc', 8, true, true, 'child'], + + // oxen (ox) + ['nexo', 4, false, false, 'ox'], + + // indices (index), appendices (appendix), prices (price) + ['seci', 4, false, true, ['ex', 'ix', 'ice']], + + // codes (code) + ['sedoc', 5, false, true, 'code'], + + // selfies (selfie) + ['seifles', 7, true, true, 'selfie'], + + // zombies (zombie) + ['seibmoz', 7, true, true, 'zombie'], + + // movies (movie) + ['seivom', 6, true, true, 'movie'], + + // names (name) + ['seman', 5, true, false, 'name'], + + // conspectuses (conspectus), prospectuses (prospectus) + ['sesutcep', 8, true, true, 'pectus'], + + // feet (foot) + ['teef', 4, true, true, 'foot'], + + // geese (goose) + ['eseeg', 5, true, true, 'goose'], + + // teeth (tooth) + ['hteet', 5, true, true, 'tooth'], + + // news (news) + ['swen', 4, true, true, 'news'], + + // series (series) + ['seires', 6, true, true, 'series'], + + // babies (baby) + ['sei', 3, false, true, 'y'], + + // accesses (access), addresses (address), kisses (kiss) + ['sess', 4, true, false, 'ss'], + + // statuses (status) + ['sesutats', 8, true, true, 'status'], + + // analyses (analysis), ellipses (ellipsis), fungi (fungus), + // neuroses (neurosis), theses (thesis), emphases (emphasis), + // oases (oasis), crises (crisis), houses (house), bases (base), + // atlases (atlas) + ['ses', 3, true, true, ['s', 'se', 'sis']], + + // objectives (objective), alternative (alternatives) + ['sevit', 5, true, true, 'tive'], + + // drives (drive) + ['sevird', 6, false, true, 'drive'], + + // lives (life), wives (wife) + ['sevi', 4, false, true, 'ife'], + + // moves (move) + ['sevom', 5, true, true, 'move'], + + // hooves (hoof), dwarves (dwarf), elves (elf), leaves (leaf), caves (cave), staves (staff) + ['sev', 3, true, true, ['f', 've', 'ff']], + + // axes (axis), axes (ax), axes (axe) + ['sexa', 4, false, false, ['ax', 'axe', 'axis']], + + // indexes (index), matrixes (matrix) + ['sex', 3, true, false, 'x'], + + // quizzes (quiz) + ['sezz', 4, true, false, 'z'], + + // bureaus (bureau) + ['suae', 4, false, true, 'eau'], + + // fees (fee), trees (tree), employees (employee) + ['see', 3, true, true, 'ee'], + + // edges (edge) + ['segd', 4, true, true, 'dge'], + + // roses (rose), garages (garage), cassettes (cassette), + // waltzes (waltz), heroes (hero), bushes (bush), arches (arch), + // shoes (shoe) + ['se', 2, true, true, ['', 'e']], + + // status (status) + ['sutats', 6, true, true, 'status'], + + // tags (tag) + ['s', 1, true, true, ''], + + // chateaux (chateau) + ['xuae', 4, false, true, 'eau'], + + // people (person) + ['elpoep', 6, true, true, 'person'], + ]; + + /** + * Map English singular to plural suffixes. + * + * @see http://english-zone.com/spelling/plurals.html + */ + private const SINGULAR_MAP = [ + // First entry: singular suffix, reversed + // Second entry: length of singular suffix + // Third entry: Whether the suffix may succeed a vowel + // Fourth entry: Whether the suffix may succeed a consonant + // Fifth entry: plural suffix, normal + + // criterion (criteria) + ['airetirc', 8, false, false, 'criterion'], + + // nebulae (nebula) + ['aluben', 6, false, false, 'nebulae'], + + // children (child) + ['dlihc', 5, true, true, 'children'], + + // prices (price) + ['eci', 3, false, true, 'ices'], + + // services (service) + ['ecivres', 7, true, true, 'services'], + + // lives (life), wives (wife) + ['efi', 3, false, true, 'ives'], + + // selfies (selfie) + ['eifles', 6, true, true, 'selfies'], + + // movies (movie) + ['eivom', 5, true, true, 'movies'], + + // lice (louse) + ['esuol', 5, false, true, 'lice'], + + // mice (mouse) + ['esuom', 5, false, true, 'mice'], + + // geese (goose) + ['esoo', 4, false, true, 'eese'], + + // houses (house), bases (base) + ['es', 2, true, true, 'ses'], + + // geese (goose) + ['esoog', 5, true, true, 'geese'], + + // caves (cave) + ['ev', 2, true, true, 'ves'], + + // drives (drive) + ['evird', 5, false, true, 'drives'], + + // objectives (objective), alternative (alternatives) + ['evit', 4, true, true, 'tives'], + + // moves (move) + ['evom', 4, true, true, 'moves'], + + // staves (staff) + ['ffats', 5, true, true, 'staves'], + + // hooves (hoof), dwarves (dwarf), elves (elf), leaves (leaf) + ['ff', 2, true, true, 'ffs'], + + // hooves (hoof), dwarves (dwarf), elves (elf), leaves (leaf) + ['f', 1, true, true, ['fs', 'ves']], + + // arches (arch) + ['hc', 2, true, true, 'ches'], + + // bushes (bush) + ['hs', 2, true, true, 'shes'], + + // teeth (tooth) + ['htoot', 5, true, true, 'teeth'], + + // bacteria (bacterium), criteria (criterion), phenomena (phenomenon) + ['mu', 2, true, true, 'a'], + + // men (man), women (woman) + ['nam', 3, true, true, 'men'], + + // people (person) + ['nosrep', 6, true, true, ['persons', 'people']], + + // bacteria (bacterium), criteria (criterion), phenomena (phenomenon) + ['noi', 3, true, true, 'ions'], + + // coupon (coupons) + ['nop', 3, true, true, 'pons'], + + // seasons (season), treasons (treason), poisons (poison), lessons (lesson) + ['nos', 3, true, true, 'sons'], + + // icons (icon) + ['noc', 3, true, true, 'cons'], + + // bacteria (bacterium), criteria (criterion), phenomena (phenomenon) + ['no', 2, true, true, 'a'], + + // echoes (echo) + ['ohce', 4, true, true, 'echoes'], + + // heroes (hero) + ['oreh', 4, true, true, 'heroes'], + + // atlases (atlas) + ['salta', 5, true, true, 'atlases'], + + // irises (iris) + ['siri', 4, true, true, 'irises'], + + // analyses (analysis), ellipses (ellipsis), neuroses (neurosis) + // theses (thesis), emphases (emphasis), oases (oasis), + // crises (crisis) + ['sis', 3, true, true, 'ses'], + + // accesses (access), addresses (address), kisses (kiss) + ['ss', 2, true, false, 'sses'], + + // syllabi (syllabus) + ['suballys', 8, true, true, 'syllabi'], + + // buses (bus) + ['sub', 3, true, true, 'buses'], + + // circuses (circus) + ['suc', 3, true, true, 'cuses'], + + // status (status) + ['sutats', 6, true, true, ['status', 'statuses']], + + // conspectuses (conspectus), prospectuses (prospectus) + ['sutcep', 6, true, true, 'pectuses'], + + // fungi (fungus), alumni (alumnus), syllabi (syllabus), radii (radius) + ['su', 2, true, true, 'i'], + + // news (news) + ['swen', 4, true, true, 'news'], + + // feet (foot) + ['toof', 4, true, true, 'feet'], + + // chateaux (chateau), bureaus (bureau) + ['uae', 3, false, true, ['eaus', 'eaux']], + + // oxen (ox) + ['xo', 2, false, false, 'oxen'], + + // hoaxes (hoax) + ['xaoh', 4, true, false, 'hoaxes'], + + // indices (index) + ['xedni', 5, false, true, ['indicies', 'indexes']], + + // boxes (box) + ['xo', 2, false, true, 'oxes'], + + // indexes (index), matrixes (matrix) + ['x', 1, true, false, ['cies', 'xes']], + + // appendices (appendix) + ['xi', 2, false, true, 'ices'], + + // babies (baby) + ['y', 1, false, true, 'ies'], + + // quizzes (quiz) + ['ziuq', 4, true, false, 'quizzes'], + + // waltzes (waltz) + ['z', 1, true, true, 'zes'], + ]; + + /** + * A list of words which should not be inflected, reversed. + */ + private const UNINFLECTED = [ + '', + + // data + 'atad', + + // deer + 'reed', + + // equipment + 'tnempiuqe', + + // feedback + 'kcabdeef', + + // fish + 'hsif', + + // health + 'htlaeh', + + // history + 'yrotsih', + + // info + 'ofni', + + // information + 'noitamrofni', + + // money + 'yenom', + + // moose + 'esoom', + + // series + 'seires', + + // sheep + 'peehs', + + // species + 'seiceps', + + // traffic + 'ciffart', + ]; + + public function singularize(string $plural): array + { + $pluralRev = strrev($plural); + $lowerPluralRev = strtolower($pluralRev); + $pluralLength = \strlen($lowerPluralRev); + + // Check if the word is one which is not inflected, return early if so + if (\in_array($lowerPluralRev, self::UNINFLECTED, true)) { + return [$plural]; + } + + // The outer loop iterates over the entries of the plural table + // The inner loop $j iterates over the characters of the plural suffix + // in the plural table to compare them with the characters of the actual + // given plural suffix + foreach (self::PLURAL_MAP as $map) { + $suffix = $map[0]; + $suffixLength = $map[1]; + $j = 0; + + // Compare characters in the plural table and of the suffix of the + // given plural one by one + while ($suffix[$j] === $lowerPluralRev[$j]) { + // Let $j point to the next character + ++$j; + + // Successfully compared the last character + // Add an entry with the singular suffix to the singular array + if ($j === $suffixLength) { + // Is there any character preceding the suffix in the plural string? + if ($j < $pluralLength) { + $nextIsVowel = str_contains('aeiou', $lowerPluralRev[$j]); + + if (!$map[2] && $nextIsVowel) { + // suffix may not succeed a vowel but next char is one + break; + } + + if (!$map[3] && !$nextIsVowel) { + // suffix may not succeed a consonant but next char is one + break; + } + } + + $newBase = substr($plural, 0, $pluralLength - $suffixLength); + $newSuffix = $map[4]; + + // Check whether the first character in the plural suffix + // is uppercased. If yes, uppercase the first character in + // the singular suffix too + $firstUpper = ctype_upper($pluralRev[$j - 1]); + + if (\is_array($newSuffix)) { + $singulars = []; + + foreach ($newSuffix as $newSuffixEntry) { + $singulars[] = $newBase.($firstUpper ? ucfirst($newSuffixEntry) : $newSuffixEntry); + } + + return $singulars; + } + + return [$newBase.($firstUpper ? ucfirst($newSuffix) : $newSuffix)]; + } + + // Suffix is longer than word + if ($j === $pluralLength) { + break; + } + } + } + + // Assume that plural and singular is identical + return [$plural]; + } + + public function pluralize(string $singular): array + { + $singularRev = strrev($singular); + $lowerSingularRev = strtolower($singularRev); + $singularLength = \strlen($lowerSingularRev); + + // Check if the word is one which is not inflected, return early if so + if (\in_array($lowerSingularRev, self::UNINFLECTED, true)) { + return [$singular]; + } + + // The outer loop iterates over the entries of the singular table + // The inner loop $j iterates over the characters of the singular suffix + // in the singular table to compare them with the characters of the actual + // given singular suffix + foreach (self::SINGULAR_MAP as $map) { + $suffix = $map[0]; + $suffixLength = $map[1]; + $j = 0; + + // Compare characters in the singular table and of the suffix of the + // given plural one by one + + while ($suffix[$j] === $lowerSingularRev[$j]) { + // Let $j point to the next character + ++$j; + + // Successfully compared the last character + // Add an entry with the plural suffix to the plural array + if ($j === $suffixLength) { + // Is there any character preceding the suffix in the plural string? + if ($j < $singularLength) { + $nextIsVowel = str_contains('aeiou', $lowerSingularRev[$j]); + + if (!$map[2] && $nextIsVowel) { + // suffix may not succeed a vowel but next char is one + break; + } + + if (!$map[3] && !$nextIsVowel) { + // suffix may not succeed a consonant but next char is one + break; + } + } + + $newBase = substr($singular, 0, $singularLength - $suffixLength); + $newSuffix = $map[4]; + + // Check whether the first character in the singular suffix + // is uppercased. If yes, uppercase the first character in + // the singular suffix too + $firstUpper = ctype_upper($singularRev[$j - 1]); + + if (\is_array($newSuffix)) { + $plurals = []; + + foreach ($newSuffix as $newSuffixEntry) { + $plurals[] = $newBase.($firstUpper ? ucfirst($newSuffixEntry) : $newSuffixEntry); + } + + return $plurals; + } + + return [$newBase.($firstUpper ? ucfirst($newSuffix) : $newSuffix)]; + } + + // Suffix is longer than word + if ($j === $singularLength) { + break; + } + } + } + + // Assume that plural is singular with a trailing `s` + return [$singular.'s']; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/Inflector/FrenchInflector.php b/tools/php-cs-fixer/vendor/symfony/string/Inflector/FrenchInflector.php new file mode 100644 index 00000000..955abbf4 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/Inflector/FrenchInflector.php @@ -0,0 +1,151 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Inflector; + +/** + * French inflector. + * + * This class does only inflect nouns; not adjectives nor composed words like "soixante-dix". + */ +final class FrenchInflector implements InflectorInterface +{ + /** + * A list of all rules for pluralise. + * + * @see https://la-conjugaison.nouvelobs.com/regles/grammaire/le-pluriel-des-noms-121.php + */ + private const PLURALIZE_REGEXP = [ + // First entry: regexp + // Second entry: replacement + + // Words finishing with "s", "x" or "z" are invariables + // Les mots finissant par "s", "x" ou "z" sont invariables + ['/(s|x|z)$/i', '\1'], + + // Words finishing with "eau" are pluralized with a "x" + // Les mots finissant par "eau" prennent tous un "x" au pluriel + ['/(eau)$/i', '\1x'], + + // Words finishing with "au" are pluralized with a "x" excepted "landau" + // Les mots finissant par "au" prennent un "x" au pluriel sauf "landau" + ['/^(landau)$/i', '\1s'], + ['/(au)$/i', '\1x'], + + // Words finishing with "eu" are pluralized with a "x" excepted "pneu", "bleu", "émeu" + // Les mots finissant en "eu" prennent un "x" au pluriel sauf "pneu", "bleu", "émeu" + ['/^(pneu|bleu|émeu)$/i', '\1s'], + ['/(eu)$/i', '\1x'], + + // Words finishing with "al" are pluralized with a "aux" excepted + // Les mots finissant en "al" se terminent en "aux" sauf + ['/^(bal|carnaval|caracal|chacal|choral|corral|étal|festival|récital|val)$/i', '\1s'], + ['/al$/i', '\1aux'], + + // Aspirail, bail, corail, émail, fermail, soupirail, travail, vantail et vitrail font leur pluriel en -aux + ['/^(aspir|b|cor|ém|ferm|soupir|trav|vant|vitr)ail$/i', '\1aux'], + + // Bijou, caillou, chou, genou, hibou, joujou et pou qui prennent un x au pluriel + ['/^(bij|caill|ch|gen|hib|jouj|p)ou$/i', '\1oux'], + + // Invariable words + ['/^(cinquante|soixante|mille)$/i', '\1'], + + // French titles + ['/^(mon|ma)(sieur|dame|demoiselle|seigneur)$/', 'mes\2s'], + ['/^(Mon|Ma)(sieur|dame|demoiselle|seigneur)$/', 'Mes\2s'], + ]; + + /** + * A list of all rules for singularize. + */ + private const SINGULARIZE_REGEXP = [ + // First entry: regexp + // Second entry: replacement + + // Aspirail, bail, corail, émail, fermail, soupirail, travail, vantail et vitrail font leur pluriel en -aux + ['/((aspir|b|cor|ém|ferm|soupir|trav|vant|vitr))aux$/i', '\1ail'], + + // Words finishing with "eau" are pluralized with a "x" + // Les mots finissant par "eau" prennent tous un "x" au pluriel + ['/(eau)x$/i', '\1'], + + // Words finishing with "al" are pluralized with a "aux" expected + // Les mots finissant en "al" se terminent en "aux" sauf + ['/(amir|anim|arsen|boc|can|capit|capor|chev|crist|génér|hopit|hôpit|idé|journ|littor|loc|m|mét|minér|princip|radic|termin)aux$/i', '\1al'], + + // Words finishing with "au" are pluralized with a "x" excepted "landau" + // Les mots finissant par "au" prennent un "x" au pluriel sauf "landau" + ['/(au)x$/i', '\1'], + + // Words finishing with "eu" are pluralized with a "x" excepted "pneu", "bleu", "émeu" + // Les mots finissant en "eu" prennent un "x" au pluriel sauf "pneu", "bleu", "émeu" + ['/(eu)x$/i', '\1'], + + // Words finishing with "ou" are pluralized with a "s" excepted bijou, caillou, chou, genou, hibou, joujou, pou + // Les mots finissant par "ou" prennent un "s" sauf bijou, caillou, chou, genou, hibou, joujou, pou + ['/(bij|caill|ch|gen|hib|jouj|p)oux$/i', '\1ou'], + + // French titles + ['/^mes(dame|demoiselle)s$/', 'ma\1'], + ['/^Mes(dame|demoiselle)s$/', 'Ma\1'], + ['/^mes(sieur|seigneur)s$/', 'mon\1'], + ['/^Mes(sieur|seigneur)s$/', 'Mon\1'], + + // Default rule + ['/s$/i', ''], + ]; + + /** + * A list of words which should not be inflected. + * This list is only used by singularize. + */ + private const UNINFLECTED = '/^(abcès|accès|abus|albatros|anchois|anglais|autobus|bois|brebis|carquois|cas|chas|colis|concours|corps|cours|cyprès|décès|devis|discours|dos|embarras|engrais|entrelacs|excès|fils|fois|gâchis|gars|glas|héros|intrus|jars|jus|kermès|lacis|legs|lilas|marais|mars|matelas|mépris|mets|mois|mors|obus|os|palais|paradis|parcours|pardessus|pays|plusieurs|poids|pois|pouls|printemps|processus|progrès|puits|pus|rabais|radis|recors|recours|refus|relais|remords|remous|rictus|rhinocéros|repas|rubis|sans|sas|secours|sens|souris|succès|talus|tapis|tas|taudis|temps|tiers|univers|velours|verglas|vernis|virus)$/i'; + + public function singularize(string $plural): array + { + if ($this->isInflectedWord($plural)) { + return [$plural]; + } + + foreach (self::SINGULARIZE_REGEXP as $rule) { + [$regexp, $replace] = $rule; + + if (1 === preg_match($regexp, $plural)) { + return [preg_replace($regexp, $replace, $plural)]; + } + } + + return [$plural]; + } + + public function pluralize(string $singular): array + { + if ($this->isInflectedWord($singular)) { + return [$singular]; + } + + foreach (self::PLURALIZE_REGEXP as $rule) { + [$regexp, $replace] = $rule; + + if (1 === preg_match($regexp, $singular)) { + return [preg_replace($regexp, $replace, $singular)]; + } + } + + return [$singular.'s']; + } + + private function isInflectedWord(string $word): bool + { + return 1 === preg_match(self::UNINFLECTED, $word); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/Inflector/InflectorInterface.php b/tools/php-cs-fixer/vendor/symfony/string/Inflector/InflectorInterface.php new file mode 100644 index 00000000..67f28340 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/Inflector/InflectorInterface.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Inflector; + +interface InflectorInterface +{ + /** + * Returns the singular forms of a string. + * + * If the method can't determine the form with certainty, several possible singulars are returned. + * + * @return string[] + */ + public function singularize(string $plural): array; + + /** + * Returns the plural forms of a string. + * + * If the method can't determine the form with certainty, several possible plurals are returned. + * + * @return string[] + */ + public function pluralize(string $singular): array; +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/LICENSE b/tools/php-cs-fixer/vendor/symfony/string/LICENSE new file mode 100644 index 00000000..f37c76b5 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2019-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/php-cs-fixer/vendor/symfony/string/LazyString.php b/tools/php-cs-fixer/vendor/symfony/string/LazyString.php new file mode 100644 index 00000000..0341beaf --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/LazyString.php @@ -0,0 +1,145 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String; + +/** + * A string whose value is computed lazily by a callback. + * + * @author Nicolas Grekas + */ +class LazyString implements \Stringable, \JsonSerializable +{ + private \Closure|string $value; + + /** + * @param callable|array $callback A callable or a [Closure, method] lazy-callable + */ + public static function fromCallable(callable|array $callback, mixed ...$arguments): static + { + if (\is_array($callback) && !\is_callable($callback) && !(($callback[0] ?? null) instanceof \Closure || 2 < \count($callback))) { + throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be a callable or a [Closure, method] lazy-callable, "%s" given.', __METHOD__, '['.implode(', ', array_map('get_debug_type', $callback)).']')); + } + + $lazyString = new static(); + $lazyString->value = static function () use (&$callback, &$arguments): string { + static $value; + + if (null !== $arguments) { + if (!\is_callable($callback)) { + $callback[0] = $callback[0](); + $callback[1] ??= '__invoke'; + } + $value = $callback(...$arguments); + $callback = self::getPrettyName($callback); + $arguments = null; + } + + return $value ?? ''; + }; + + return $lazyString; + } + + public static function fromStringable(string|int|float|bool|\Stringable $value): static + { + if (\is_object($value)) { + return static::fromCallable($value->__toString(...)); + } + + $lazyString = new static(); + $lazyString->value = (string) $value; + + return $lazyString; + } + + /** + * Tells whether the provided value can be cast to string. + */ + final public static function isStringable(mixed $value): bool + { + return \is_string($value) || $value instanceof \Stringable || \is_scalar($value); + } + + /** + * Casts scalars and stringable objects to strings. + * + * @throws \TypeError When the provided value is not stringable + */ + final public static function resolve(\Stringable|string|int|float|bool $value): string + { + return $value; + } + + public function __toString(): string + { + if (\is_string($this->value)) { + return $this->value; + } + + try { + return $this->value = ($this->value)(); + } catch (\Throwable $e) { + if (\TypeError::class === $e::class && __FILE__ === $e->getFile()) { + $type = explode(', ', $e->getMessage()); + $type = substr(array_pop($type), 0, -\strlen(' returned')); + $r = new \ReflectionFunction($this->value); + $callback = $r->getStaticVariables()['callback']; + + $e = new \TypeError(sprintf('Return value of %s() passed to %s::fromCallable() must be of the type string, %s returned.', $callback, static::class, $type)); + } + + throw $e; + } + } + + public function __sleep(): array + { + $this->__toString(); + + return ['value']; + } + + public function jsonSerialize(): string + { + return $this->__toString(); + } + + private function __construct() + { + } + + private static function getPrettyName(callable $callback): string + { + if (\is_string($callback)) { + return $callback; + } + + if (\is_array($callback)) { + $class = \is_object($callback[0]) ? get_debug_type($callback[0]) : $callback[0]; + $method = $callback[1]; + } elseif ($callback instanceof \Closure) { + $r = new \ReflectionFunction($callback); + + if (str_contains($r->name, '{closure}') || !$class = $r->getClosureCalledClass()) { + return $r->name; + } + + $class = $class->name; + $method = $r->name; + } else { + $class = get_debug_type($callback); + $method = '__invoke'; + } + + return $class.'::'.$method; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/README.md b/tools/php-cs-fixer/vendor/symfony/string/README.md new file mode 100644 index 00000000..9c7e1e19 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/README.md @@ -0,0 +1,14 @@ +String Component +================ + +The String component provides an object-oriented API to strings and deals +with bytes, UTF-8 code points and grapheme clusters in a unified way. + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/string.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/tools/php-cs-fixer/vendor/symfony/string/Resources/data/wcswidth_table_wide.php b/tools/php-cs-fixer/vendor/symfony/string/Resources/data/wcswidth_table_wide.php new file mode 100644 index 00000000..8314c8fd --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/Resources/data/wcswidth_table_wide.php @@ -0,0 +1,1155 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String; + +if (!\function_exists(u::class)) { + function u(?string $string = ''): UnicodeString + { + return new UnicodeString($string ?? ''); + } +} + +if (!\function_exists(b::class)) { + function b(?string $string = ''): ByteString + { + return new ByteString($string ?? ''); + } +} + +if (!\function_exists(s::class)) { + /** + * @return UnicodeString|ByteString + */ + function s(?string $string = ''): AbstractString + { + $string ??= ''; + + return preg_match('//u', $string) ? new UnicodeString($string) : new ByteString($string); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/Slugger/AsciiSlugger.php b/tools/php-cs-fixer/vendor/symfony/string/Slugger/AsciiSlugger.php new file mode 100644 index 00000000..9f7eba94 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/Slugger/AsciiSlugger.php @@ -0,0 +1,207 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Slugger; + +use Symfony\Component\Intl\Transliterator\EmojiTransliterator; +use Symfony\Component\String\AbstractUnicodeString; +use Symfony\Component\String\UnicodeString; +use Symfony\Contracts\Translation\LocaleAwareInterface; + +if (!interface_exists(LocaleAwareInterface::class)) { + throw new \LogicException('You cannot use the "Symfony\Component\String\Slugger\AsciiSlugger" as the "symfony/translation-contracts" package is not installed. Try running "composer require symfony/translation-contracts".'); +} + +/** + * @author Titouan Galopin + */ +class AsciiSlugger implements SluggerInterface, LocaleAwareInterface +{ + private const LOCALE_TO_TRANSLITERATOR_ID = [ + 'am' => 'Amharic-Latin', + 'ar' => 'Arabic-Latin', + 'az' => 'Azerbaijani-Latin', + 'be' => 'Belarusian-Latin', + 'bg' => 'Bulgarian-Latin', + 'bn' => 'Bengali-Latin', + 'de' => 'de-ASCII', + 'el' => 'Greek-Latin', + 'fa' => 'Persian-Latin', + 'he' => 'Hebrew-Latin', + 'hy' => 'Armenian-Latin', + 'ka' => 'Georgian-Latin', + 'kk' => 'Kazakh-Latin', + 'ky' => 'Kirghiz-Latin', + 'ko' => 'Korean-Latin', + 'mk' => 'Macedonian-Latin', + 'mn' => 'Mongolian-Latin', + 'or' => 'Oriya-Latin', + 'ps' => 'Pashto-Latin', + 'ru' => 'Russian-Latin', + 'sr' => 'Serbian-Latin', + 'sr_Cyrl' => 'Serbian-Latin', + 'th' => 'Thai-Latin', + 'tk' => 'Turkmen-Latin', + 'uk' => 'Ukrainian-Latin', + 'uz' => 'Uzbek-Latin', + 'zh' => 'Han-Latin', + ]; + + private ?string $defaultLocale; + private \Closure|array $symbolsMap = [ + 'en' => ['@' => 'at', '&' => 'and'], + ]; + private bool|string $emoji = false; + + /** + * Cache of transliterators per locale. + * + * @var \Transliterator[] + */ + private array $transliterators = []; + + public function __construct(string $defaultLocale = null, array|\Closure $symbolsMap = null) + { + $this->defaultLocale = $defaultLocale; + $this->symbolsMap = $symbolsMap ?? $this->symbolsMap; + } + + public function setLocale(string $locale): void + { + $this->defaultLocale = $locale; + } + + public function getLocale(): string + { + return $this->defaultLocale; + } + + /** + * @param bool|string $emoji true will use the same locale, + * false will disable emoji, + * and a string to use a specific locale + */ + public function withEmoji(bool|string $emoji = true): static + { + if (false !== $emoji && !class_exists(EmojiTransliterator::class)) { + throw new \LogicException(sprintf('You cannot use the "%s()" method as the "symfony/intl" package is not installed. Try running "composer require symfony/intl".', __METHOD__)); + } + + $new = clone $this; + $new->emoji = $emoji; + + return $new; + } + + public function slug(string $string, string $separator = '-', string $locale = null): AbstractUnicodeString + { + $locale ??= $this->defaultLocale; + + $transliterator = []; + if ($locale && ('de' === $locale || str_starts_with($locale, 'de_'))) { + // Use the shortcut for German in UnicodeString::ascii() if possible (faster and no requirement on intl) + $transliterator = ['de-ASCII']; + } elseif (\function_exists('transliterator_transliterate') && $locale) { + $transliterator = (array) $this->createTransliterator($locale); + } + + if ($emojiTransliterator = $this->createEmojiTransliterator($locale)) { + $transliterator[] = $emojiTransliterator; + } + + if ($this->symbolsMap instanceof \Closure) { + // If the symbols map is passed as a closure, there is no need to fallback to the parent locale + // as the closure can just provide substitutions for all locales of interest. + $symbolsMap = $this->symbolsMap; + array_unshift($transliterator, static fn ($s) => $symbolsMap($s, $locale)); + } + + $unicodeString = (new UnicodeString($string))->ascii($transliterator); + + if (\is_array($this->symbolsMap)) { + $map = null; + if (isset($this->symbolsMap[$locale])) { + $map = $this->symbolsMap[$locale]; + } else { + $parent = self::getParentLocale($locale); + if ($parent && isset($this->symbolsMap[$parent])) { + $map = $this->symbolsMap[$parent]; + } + } + if ($map) { + foreach ($map as $char => $replace) { + $unicodeString = $unicodeString->replace($char, ' '.$replace.' '); + } + } + } + + return $unicodeString + ->replaceMatches('/[^A-Za-z0-9]++/', $separator) + ->trim($separator) + ; + } + + private function createTransliterator(string $locale): ?\Transliterator + { + if (\array_key_exists($locale, $this->transliterators)) { + return $this->transliterators[$locale]; + } + + // Exact locale supported, cache and return + if ($id = self::LOCALE_TO_TRANSLITERATOR_ID[$locale] ?? null) { + return $this->transliterators[$locale] = \Transliterator::create($id.'/BGN') ?? \Transliterator::create($id); + } + + // Locale not supported and no parent, fallback to any-latin + if (!$parent = self::getParentLocale($locale)) { + return $this->transliterators[$locale] = null; + } + + // Try to use the parent locale (ie. try "de" for "de_AT") and cache both locales + if ($id = self::LOCALE_TO_TRANSLITERATOR_ID[$parent] ?? null) { + $transliterator = \Transliterator::create($id.'/BGN') ?? \Transliterator::create($id); + } + + return $this->transliterators[$locale] = $this->transliterators[$parent] = $transliterator ?? null; + } + + private function createEmojiTransliterator(?string $locale): ?EmojiTransliterator + { + if (\is_string($this->emoji)) { + $locale = $this->emoji; + } elseif (!$this->emoji) { + return null; + } + + while (null !== $locale) { + try { + return EmojiTransliterator::create("emoji-$locale"); + } catch (\IntlException) { + $locale = self::getParentLocale($locale); + } + } + + return null; + } + + private static function getParentLocale(?string $locale): ?string + { + if (!$locale) { + return null; + } + if (false === $str = strrchr($locale, '_')) { + // no parent locale + return null; + } + + return substr($locale, 0, -\strlen($str)); + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/Slugger/SluggerInterface.php b/tools/php-cs-fixer/vendor/symfony/string/Slugger/SluggerInterface.php new file mode 100644 index 00000000..c679ed93 --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/Slugger/SluggerInterface.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String\Slugger; + +use Symfony\Component\String\AbstractUnicodeString; + +/** + * Creates a URL-friendly slug from a given string. + * + * @author Titouan Galopin + */ +interface SluggerInterface +{ + /** + * Creates a slug for the given string and locale, using appropriate transliteration when needed. + */ + public function slug(string $string, string $separator = '-', string $locale = null): AbstractUnicodeString; +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/UnicodeString.php b/tools/php-cs-fixer/vendor/symfony/string/UnicodeString.php new file mode 100644 index 00000000..bc09627c --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/UnicodeString.php @@ -0,0 +1,382 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\String; + +use Symfony\Component\String\Exception\ExceptionInterface; +use Symfony\Component\String\Exception\InvalidArgumentException; + +/** + * Represents a string of Unicode grapheme clusters encoded as UTF-8. + * + * A letter followed by combining characters (accents typically) form what Unicode defines + * as a grapheme cluster: a character as humans mean it in written texts. This class knows + * about the concept and won't split a letter apart from its combining accents. It also + * ensures all string comparisons happen on their canonically-composed representation, + * ignoring e.g. the order in which accents are listed when a letter has many of them. + * + * @see https://unicode.org/reports/tr15/ + * + * @author Nicolas Grekas + * @author Hugo Hamon + * + * @throws ExceptionInterface + */ +class UnicodeString extends AbstractUnicodeString +{ + public function __construct(string $string = '') + { + if ('' === $string || normalizer_is_normalized($this->string = $string)) { + return; + } + + if (false === $string = normalizer_normalize($string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $this->string = $string; + } + + public function append(string ...$suffix): static + { + $str = clone $this; + $str->string = $this->string.(1 >= \count($suffix) ? ($suffix[0] ?? '') : implode('', $suffix)); + + if (normalizer_is_normalized($str->string)) { + return $str; + } + + if (false === $string = normalizer_normalize($str->string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $str->string = $string; + + return $str; + } + + public function chunk(int $length = 1): array + { + if (1 > $length) { + throw new InvalidArgumentException('The chunk length must be greater than zero.'); + } + + if ('' === $this->string) { + return []; + } + + $rx = '/('; + while (65535 < $length) { + $rx .= '\X{65535}'; + $length -= 65535; + } + $rx .= '\X{'.$length.'})/u'; + + $str = clone $this; + $chunks = []; + + foreach (preg_split($rx, $this->string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY) as $chunk) { + $str->string = $chunk; + $chunks[] = clone $str; + } + + return $chunks; + } + + public function endsWith(string|iterable|AbstractString $suffix): bool + { + if ($suffix instanceof AbstractString) { + $suffix = $suffix->string; + } elseif (!\is_string($suffix)) { + return parent::endsWith($suffix); + } + + $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC; + normalizer_is_normalized($suffix, $form) ?: $suffix = normalizer_normalize($suffix, $form); + + if ('' === $suffix || false === $suffix) { + return false; + } + + if ($this->ignoreCase) { + return 0 === mb_stripos(grapheme_extract($this->string, \strlen($suffix), \GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix)), $suffix, 0, 'UTF-8'); + } + + return $suffix === grapheme_extract($this->string, \strlen($suffix), \GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix)); + } + + public function equalsTo(string|iterable|AbstractString $string): bool + { + if ($string instanceof AbstractString) { + $string = $string->string; + } elseif (!\is_string($string)) { + return parent::equalsTo($string); + } + + $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC; + normalizer_is_normalized($string, $form) ?: $string = normalizer_normalize($string, $form); + + if ('' !== $string && false !== $string && $this->ignoreCase) { + return \strlen($string) === \strlen($this->string) && 0 === mb_stripos($this->string, $string, 0, 'UTF-8'); + } + + return $string === $this->string; + } + + public function indexOf(string|iterable|AbstractString $needle, int $offset = 0): ?int + { + if ($needle instanceof AbstractString) { + $needle = $needle->string; + } elseif (!\is_string($needle)) { + return parent::indexOf($needle, $offset); + } + + $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC; + normalizer_is_normalized($needle, $form) ?: $needle = normalizer_normalize($needle, $form); + + if ('' === $needle || false === $needle) { + return null; + } + + try { + $i = $this->ignoreCase ? grapheme_stripos($this->string, $needle, $offset) : grapheme_strpos($this->string, $needle, $offset); + } catch (\ValueError) { + return null; + } + + return false === $i ? null : $i; + } + + public function indexOfLast(string|iterable|AbstractString $needle, int $offset = 0): ?int + { + if ($needle instanceof AbstractString) { + $needle = $needle->string; + } elseif (!\is_string($needle)) { + return parent::indexOfLast($needle, $offset); + } + + $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC; + normalizer_is_normalized($needle, $form) ?: $needle = normalizer_normalize($needle, $form); + + if ('' === $needle || false === $needle) { + return null; + } + + $string = $this->string; + + if (0 > $offset) { + // workaround https://bugs.php.net/74264 + if (0 > $offset += grapheme_strlen($needle)) { + $string = grapheme_substr($string, 0, $offset); + } + $offset = 0; + } + + $i = $this->ignoreCase ? grapheme_strripos($string, $needle, $offset) : grapheme_strrpos($string, $needle, $offset); + + return false === $i ? null : $i; + } + + public function join(array $strings, string $lastGlue = null): static + { + $str = parent::join($strings, $lastGlue); + normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string); + + return $str; + } + + public function length(): int + { + return grapheme_strlen($this->string); + } + + public function normalize(int $form = self::NFC): static + { + $str = clone $this; + + if (\in_array($form, [self::NFC, self::NFKC], true)) { + normalizer_is_normalized($str->string, $form) ?: $str->string = normalizer_normalize($str->string, $form); + } elseif (!\in_array($form, [self::NFD, self::NFKD], true)) { + throw new InvalidArgumentException('Unsupported normalization form.'); + } elseif (!normalizer_is_normalized($str->string, $form)) { + $str->string = normalizer_normalize($str->string, $form); + $str->ignoreCase = null; + } + + return $str; + } + + public function prepend(string ...$prefix): static + { + $str = clone $this; + $str->string = (1 >= \count($prefix) ? ($prefix[0] ?? '') : implode('', $prefix)).$this->string; + + if (normalizer_is_normalized($str->string)) { + return $str; + } + + if (false === $string = normalizer_normalize($str->string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $str->string = $string; + + return $str; + } + + public function replace(string $from, string $to): static + { + $str = clone $this; + normalizer_is_normalized($from) ?: $from = normalizer_normalize($from); + + if ('' !== $from && false !== $from) { + $tail = $str->string; + $result = ''; + $indexOf = $this->ignoreCase ? 'grapheme_stripos' : 'grapheme_strpos'; + + while ('' !== $tail && false !== $i = $indexOf($tail, $from)) { + $slice = grapheme_substr($tail, 0, $i); + $result .= $slice.$to; + $tail = substr($tail, \strlen($slice) + \strlen($from)); + } + + $str->string = $result.$tail; + + if (normalizer_is_normalized($str->string)) { + return $str; + } + + if (false === $string = normalizer_normalize($str->string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $str->string = $string; + } + + return $str; + } + + public function replaceMatches(string $fromRegexp, string|callable $to): static + { + $str = parent::replaceMatches($fromRegexp, $to); + normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string); + + return $str; + } + + public function slice(int $start = 0, int $length = null): static + { + $str = clone $this; + + $str->string = (string) grapheme_substr($this->string, $start, $length ?? 2147483647); + + return $str; + } + + public function splice(string $replacement, int $start = 0, int $length = null): static + { + $str = clone $this; + + $start = $start ? \strlen(grapheme_substr($this->string, 0, $start)) : 0; + $length = $length ? \strlen(grapheme_substr($this->string, $start, $length ?? 2147483647)) : $length; + $str->string = substr_replace($this->string, $replacement, $start, $length ?? 2147483647); + + if (normalizer_is_normalized($str->string)) { + return $str; + } + + if (false === $string = normalizer_normalize($str->string)) { + throw new InvalidArgumentException('Invalid UTF-8 string.'); + } + + $str->string = $string; + + return $str; + } + + public function split(string $delimiter, int $limit = null, int $flags = null): array + { + if (1 > $limit ??= 2147483647) { + throw new InvalidArgumentException('Split limit must be a positive integer.'); + } + + if ('' === $delimiter) { + throw new InvalidArgumentException('Split delimiter is empty.'); + } + + if (null !== $flags) { + return parent::split($delimiter.'u', $limit, $flags); + } + + normalizer_is_normalized($delimiter) ?: $delimiter = normalizer_normalize($delimiter); + + if (false === $delimiter) { + throw new InvalidArgumentException('Split delimiter is not a valid UTF-8 string.'); + } + + $str = clone $this; + $tail = $this->string; + $chunks = []; + $indexOf = $this->ignoreCase ? 'grapheme_stripos' : 'grapheme_strpos'; + + while (1 < $limit && false !== $i = $indexOf($tail, $delimiter)) { + $str->string = grapheme_substr($tail, 0, $i); + $chunks[] = clone $str; + $tail = substr($tail, \strlen($str->string) + \strlen($delimiter)); + --$limit; + } + + $str->string = $tail; + $chunks[] = clone $str; + + return $chunks; + } + + public function startsWith(string|iterable|AbstractString $prefix): bool + { + if ($prefix instanceof AbstractString) { + $prefix = $prefix->string; + } elseif (!\is_string($prefix)) { + return parent::startsWith($prefix); + } + + $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC; + normalizer_is_normalized($prefix, $form) ?: $prefix = normalizer_normalize($prefix, $form); + + if ('' === $prefix || false === $prefix) { + return false; + } + + if ($this->ignoreCase) { + return 0 === mb_stripos(grapheme_extract($this->string, \strlen($prefix), \GRAPHEME_EXTR_MAXBYTES), $prefix, 0, 'UTF-8'); + } + + return $prefix === grapheme_extract($this->string, \strlen($prefix), \GRAPHEME_EXTR_MAXBYTES); + } + + public function __wakeup(): void + { + if (!\is_string($this->string)) { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + normalizer_is_normalized($this->string) ?: $this->string = normalizer_normalize($this->string); + } + + public function __clone() + { + if (null === $this->ignoreCase) { + normalizer_is_normalized($this->string) ?: $this->string = normalizer_normalize($this->string); + } + + $this->ignoreCase = false; + } +} diff --git a/tools/php-cs-fixer/vendor/symfony/string/composer.json b/tools/php-cs-fixer/vendor/symfony/string/composer.json new file mode 100644 index 00000000..26ce26da --- /dev/null +++ b/tools/php-cs-fixer/vendor/symfony/string/composer.json @@ -0,0 +1,43 @@ +{ + "name": "symfony/string", + "type": "library", + "description": "Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way", + "keywords": ["string", "utf8", "utf-8", "grapheme", "i18n", "unicode"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.2", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-intl-grapheme": "~1.0", + "symfony/polyfill-intl-normalizer": "~1.0", + "symfony/polyfill-mbstring": "~1.0" + }, + "require-dev": { + "symfony/error-handler": "^6.4|^7.0", + "symfony/intl": "^6.4|^7.0", + "symfony/http-client": "^6.4|^7.0", + "symfony/translation-contracts": "^2.5|^3.0", + "symfony/var-exporter": "^6.4|^7.0" + }, + "conflict": { + "symfony/translation-contracts": "<2.5" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\String\\": "" }, + "files": [ "Resources/functions.php" ], + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +}